diff --git "a/3851.jsonl" "b/3851.jsonl" new file mode 100644--- /dev/null +++ "b/3851.jsonl" @@ -0,0 +1,664 @@ +{"seq_id":"647713391","text":"# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom fairseq import utils\nfrom fairseq.data import encoders\n\n\nclass RobertaHubInterface(nn.Module):\n \"\"\"A simple PyTorch Hub interface to RoBERTa.\n\n Usage: https://github.com/pytorch/fairseq/tree/master/examples/roberta\n \"\"\"\n\n def __init__(self, cfg, task, model):\n super().__init__()\n self.cfg = cfg\n self.task = task\n self.model = model\n self.max_positions = [self.model.max_positions()]\n\n self.bpe = encoders.build_bpe(cfg.bpe)\n\n # this is useful for determining the device\n self.register_buffer(\"_float_tensor\", torch.tensor([0], dtype=torch.float))\n\n @property\n def device(self):\n return self._float_tensor.device\n\n def masked_encode(self,\n sentence: str,\n *addl_sentences,\n mask_prob=0.0,\n random_token_prob=0.0,\n leave_unmasked_prob=0.0,\n sort=False,\n descending=False,\n no_separator=False) -> torch.LongTensor:\n start_tok = self.task.source_dictionary.encode_line('', append_eos=False, add_if_not_exist=False)\n end_tok = self.task.source_dictionary.encode_line('', append_eos=False, add_if_not_exist=False)\n pad_tok = torch.tensor([self.task.source_dictionary.pad_index])\n\n if random_token_prob > 0.0:\n weights = np.ones(len(self.task.source_dictionary))\n weights[:self.task.source_dictionary.nspecial] = 0\n weights = weights / weights.sum()\n\n def masked_encode_sent(sent):\n bpe_sentence = self.task.source_dictionary.encode_line(self.bpe.encode(sent), append_eos=False, add_if_not_exist=False)\n if (mask_prob == 0.0):\n return bpe_sentence\n\n # decide elements to mask\n sz = len(bpe_sentence)\n mask = np.full(sz, False)\n num_mask = int(\n # add a random number for probabilistic rounding\n mask_prob * sz + np.random.rand()\n )\n\n if sort:\n seq_probs = self.sequence_probability(torch.cat((start_tok, bpe_sentence, end_tok)).long().cuda())\n _, sort_idx = torch.sort(seq_probs[1:-1], descending=descending)\n sort_idx = sort_idx.cpu()\n mask[sort_idx[:num_mask]] = True\n else:\n mask[np.random.choice(sz, num_mask, replace=False)] = True\n\n mask_targets = np.full(len(mask), self.task.source_dictionary.pad_index)\n mask_targets[mask] = bpe_sentence[torch.from_numpy(mask.astype(np.uint8)) == 1]\n\n # decide unmasking and random replacement\n rand_or_unmask_prob = random_token_prob + leave_unmasked_prob\n if rand_or_unmask_prob > 0.0:\n rand_or_unmask = mask & (np.random.rand(sz) < rand_or_unmask_prob)\n if random_token_prob == 0.0:\n unmask = rand_or_unmask\n rand_mask = None\n elif leave_unmasked_prob == 0.0:\n unmask = None\n rand_mask = rand_or_unmask\n else:\n unmask_prob = leave_unmasked_prob / rand_or_unmask_prob\n decision = np.random.rand(sz) < unmask_prob\n unmask = rand_or_unmask & decision\n rand_mask = rand_or_unmask & (~decision)\n else:\n unmask = rand_mask = None\n\n if unmask is not None:\n mask = mask ^ unmask\n\n bpe_sentence[mask] = self.task.mask_idx\n if rand_mask is not None:\n num_rand = rand_mask.sum()\n if num_rand > 0:\n bpe_sentence[rand_mask] = torch.from_numpy(np.random.choice(\n len(self.task.source_dictionary),\n num_rand,\n p=weights,\n )).int()\n return bpe_sentence, torch.from_numpy(mask_targets)\n\n bpe_sent, mask_targets = masked_encode_sent(sentence)\n bpe_sent = torch.cat((start_tok, bpe_sent, end_tok))\n mask_targets = torch.cat((pad_tok, mask_targets, pad_tok))\n\n for s in addl_sentences:\n if not no_separator:\n bpe_sent = torch.cat((bpe_sent, start_tok))\n mask_targets = torch.cat((mask_targets, pad_tok))\n tmp_sent, tmp_targets = masked_encode_sent(s)\n bpe_sent = torch.cat((bpe_sent, tmp_sent, end_tok))\n mask_targets = torch.cat((mask_targets, tmp_targets, pad_tok))\n return bpe_sent.long(), mask_targets.long()\n\n def encode(\n self, sentence: str, *addl_sentences, no_separator=False\n ) -> torch.LongTensor:\n \"\"\"\n BPE-encode a sentence (or multiple sentences).\n\n Every sequence begins with a beginning-of-sentence (``) symbol.\n Every sentence ends with an end-of-sentence (``) and we use an\n extra end-of-sentence (``) as a separator.\n\n Example (single sentence): ` a b c `\n Example (sentence pair): ` d e f 1 2 3 `\n\n The BPE encoding follows GPT-2. One subtle detail is that the GPT-2 BPE\n requires leading spaces. For example::\n\n >>> roberta.encode('Hello world').tolist()\n [0, 31414, 232, 2]\n >>> roberta.encode(' world').tolist()\n [0, 232, 2]\n >>> roberta.encode('world').tolist()\n [0, 8331, 2]\n \"\"\"\n bpe_sentence = \" \" + self.bpe.encode(sentence) + \" \"\n for s in addl_sentences:\n bpe_sentence += \" \" if not no_separator else \"\"\n bpe_sentence += \" \" + self.bpe.encode(s) + \" \"\n tokens = self.task.source_dictionary.encode_line(\n bpe_sentence, append_eos=False, add_if_not_exist=False\n )\n return tokens.long()\n\n def decode(self, tokens: torch.LongTensor, split_sent=False):\n assert tokens.dim() == 1\n tokens = tokens.numpy()\n tokens = np.delete(tokens, np.argwhere(tokens == self.task.source_dictionary.pad()))\n if tokens[0] == self.task.source_dictionary.bos():\n tokens = tokens[1:] # remove \n while(tokens[-1] == self.task.source_dictionary.eos()):\n tokens = tokens[:-1] # remove \n eos_mask = (tokens == self.task.source_dictionary.eos())\n doc_mask = eos_mask[1:] & eos_mask[:-1]\n if split_sent:\n sentences = np.split(tokens, eos_mask[:-1].nonzero()[0] + 1)\n else:\n sentences = np.split(tokens, doc_mask.nonzero()[0] + 1)\n sentences = [self.bpe.decode(self.task.source_dictionary.string(s)) for s in sentences]\n sentences = [s for s in sentences if s != '']\n if len(sentences) == 1 and not split_sent:\n return sentences[0]\n return sentences\n\n\n def extract_features(\n self, tokens: torch.LongTensor, return_all_hiddens: bool = False\n ) -> torch.Tensor:\n if tokens.dim() == 1:\n tokens = tokens.unsqueeze(0)\n if tokens.size(-1) > self.model.max_positions():\n raise ValueError(\n \"tokens exceeds maximum length: {} > {}\".format(\n tokens.size(-1), self.model.max_positions()\n )\n )\n features, extra = self.model(\n tokens.to(device=self.device),\n features_only=True,\n return_all_hiddens=return_all_hiddens,\n )\n if return_all_hiddens:\n # convert from T x B x C -> B x T x C\n inner_states = extra[\"inner_states\"]\n return [inner_state.transpose(0, 1) for inner_state in inner_states]\n else:\n return features # just the last layer's features\n\n def register_classification_head(\n self, name: str, num_classes: int = None, embedding_size: int = None, **kwargs\n ):\n self.model.register_classification_head(\n name, num_classes=num_classes, embedding_size=embedding_size, **kwargs\n )\n\n def predict(self, head: str, tokens: torch.LongTensor, return_logits: bool = False):\n features = self.extract_features(tokens.to(device=self.device))\n logits = self.model.classification_heads[head](features)\n if return_logits:\n return logits\n return F.log_softmax(logits, dim=-1)\n\n def extract_features_aligned_to_words(\n self, sentence: str, return_all_hiddens: bool = False\n ) -> torch.Tensor:\n \"\"\"Extract RoBERTa features, aligned to spaCy's word-level tokenizer.\"\"\"\n from fairseq.models.roberta import alignment_utils\n from spacy.tokens import Doc\n\n nlp = alignment_utils.spacy_nlp()\n tokenizer = alignment_utils.spacy_tokenizer()\n\n # tokenize both with GPT-2 BPE and spaCy\n bpe_toks = self.encode(sentence)\n spacy_toks = tokenizer(sentence)\n spacy_toks_ws = [t.text_with_ws for t in tokenizer(sentence)]\n alignment = alignment_utils.align_bpe_to_words(self, bpe_toks, spacy_toks_ws)\n\n # extract features and align them\n features = self.extract_features(\n bpe_toks, return_all_hiddens=return_all_hiddens\n )\n features = features.squeeze(0)\n aligned_feats = alignment_utils.align_features_to_words(\n self, features, alignment\n )\n\n # wrap in spaCy Doc\n doc = Doc(\n nlp.vocab,\n words=[\"\"] + [x.text for x in spacy_toks] + [\"\"],\n spaces=[True]\n + [x.endswith(\" \") for x in spacy_toks_ws[:-1]]\n + [True, False],\n )\n assert len(doc) == aligned_feats.size(0)\n doc.user_token_hooks[\"vector\"] = lambda token: aligned_feats[token.i]\n return doc\n\n def fill_mask(self, masked_input: str, topk: int = 5):\n masked_token = \"\"\n assert (\n masked_token in masked_input and masked_input.count(masked_token) == 1\n ), \"Please add one {0} token for the input, eg: 'He is a {0} guy'\".format(\n masked_token\n )\n\n text_spans = masked_input.split(masked_token)\n text_spans_bpe = (\n (\" {0} \".format(masked_token))\n .join([self.bpe.encode(text_span.rstrip()) for text_span in text_spans])\n .strip()\n )\n tokens = self.task.source_dictionary.encode_line(\n \" \" + text_spans_bpe + \" \",\n append_eos=False,\n add_if_not_exist=False,\n )\n\n masked_index = (tokens == self.task.mask_idx).nonzero(as_tuple=False)\n if tokens.dim() == 1:\n tokens = tokens.unsqueeze(0)\n\n with utils.model_eval(self.model):\n features, extra = self.model(\n tokens.long().to(device=self.device),\n features_only=False,\n return_all_hiddens=False,\n )\n logits = features[0, masked_index, :].squeeze()\n prob = logits.softmax(dim=0)\n values, index = prob.topk(k=topk, dim=0)\n topk_predicted_token_bpe = self.task.source_dictionary.string(index)\n\n topk_filled_outputs = []\n for index, predicted_token_bpe in enumerate(\n topk_predicted_token_bpe.split(\" \")\n ):\n predicted_token = self.bpe.decode(predicted_token_bpe)\n # Quick hack to fix https://github.com/pytorch/fairseq/issues/1306\n if predicted_token_bpe.startswith(\"\\u2581\"):\n predicted_token = \" \" + predicted_token\n if \" {0}\".format(masked_token) in masked_input:\n topk_filled_outputs.append(\n (\n masked_input.replace(\n \" {0}\".format(masked_token), predicted_token\n ),\n values[index].item(),\n predicted_token,\n )\n )\n else:\n topk_filled_outputs.append(\n (\n masked_input.replace(masked_token, predicted_token),\n values[index].item(),\n predicted_token,\n )\n )\n return topk_filled_outputs\n\n\n def reconstruction_prob_tok(self, masked_tokens, target_tokens, reconstruct=False, source_model=None, topk=1, lamb=1):\n\n single = False\n\n # expand batch size 1\n if masked_tokens.dim() == 1:\n single = True\n masked_tokens = masked_tokens.unsqueeze(0)\n target_tokens = target_tokens.unsqueeze(0)\n\n masked_fill = torch.ones_like(masked_tokens)\n\n masked_index = (target_tokens != self.task.source_dictionary.pad_index).nonzero(as_tuple=True)\n masked_orig_index = target_tokens[masked_index]\n\n # edge case of no masked tokens\n if len(masked_orig_index) == 0:\n if reconstruct:\n return masked_tokens, masked_fill, torch.full((len(masked_tokens),), 0.0)\n else:\n return 1.0\n\n masked_orig_enum = [list(range(len(masked_orig_index))), masked_orig_index]\n\n with utils.model_eval(self.model):\n features, _ = self.model(\n masked_tokens.long().to(device=self.device),\n features_only=False,\n return_all_hiddens=False,\n )\n probs = features[masked_index]\n\n if source_model:\n # normalize before subtracting\n probs = probs.softmax(dim=-1)\n orig_probs = probs.detach().clone()\n with utils.model_eval(source_model):\n s_features, _ = source_model.model(\n masked_tokens.long().to(device=self.device),\n features_only=False,\n return_all_hiddens=False,\n )\n s_logits = s_features[masked_index]\n s_probs = s_logits.softmax(dim=-1)\n prob_diffs = probs - s_probs\n prob_mask = (prob_diffs > 0).float()\n prob_mask[prob_mask != 1] = torch.exp(lamb * prob_diffs[prob_mask != 1])\n probs = probs * prob_mask\n\n if source_model:\n negate = 0\n else:\n negate = float('-inf')\n\n for i in range(len(probs)):\n probs[i][self.task.source_dictionary.bos()] = negate # 0\n probs[i][self.task.source_dictionary.eos()] = negate # 2\n probs[i][self.task.source_dictionary.pad()] = negate # 1\n probs[i][-4:] = negate\n\n if (reconstruct):\n\n recon_prob = 0\n\n # sample from topk if not unrestricted\n if topk != -1:\n probs, indices = probs.topk(k=topk, dim=-1)\n # normalize after topk if necessary\n if not source_model:\n probs = probs.softmax(dim=-1)\n\n if (len(masked_index) > 1):\n tok_samples = [torch.multinomial(prob, 1) for prob in probs]\n if topk != -1:\n samples = torch.cat([idx[tok] for tok, idx in zip(tok_samples, indices)])\n else:\n samples = torch.cat(tok_samples)\n\n (masked_i, masked_j) = masked_index\n recon_prob = []\n idx = 0\n curr_prob = 0\n curr_i = 0\n while idx < len(masked_i):\n if masked_i[idx] != curr_i:\n recon_prob.append(curr_prob)\n curr_prob = 0\n curr_i += 1\n continue\n if source_model:\n curr_prob += torch.log(orig_probs[idx][tok_samples[idx]])\n else:\n curr_prob += torch.log(probs[idx][tok_samples[idx]])\n idx += 1\n recon_prob.append(curr_prob)\n while len(recon_prob) < len(masked_tokens):\n recon_prob.append(-float('inf'))\n recon_prob = torch.tensor(recon_prob)\n\n else:\n tok_sample = torch.multinomial(probs, 1)\n if topk != -1:\n samples = indices[tok_sample]\n else:\n samples = tok_sample\n if source_model:\n recon_prob = torch.tensor([orig_probs[tok_sample].item()])\n else:\n recon_prob = torch.tensor([probs[tok_sample].item()])\n\n # set samples\n masked_tokens[masked_index] = samples\n masked_fill[masked_index] = samples\n\n if single:\n return masked_tokens[0], masked_fill[0], recon_prob[0]\n else:\n return masked_tokens, masked_fill, recon_prob\n\n return torch.sum(torch.log(probs[masked_orig_enum])).item()\n\n def sequence_probability(self, tokens):\n single = False\n\n # expand batch size 1\n if tokens.dim() == 1:\n single = True\n tokens = tokens.unsqueeze(0)\n\n with utils.eval(self.model):\n features, extra = self.model(\n tokens.long().to(device=self.device),\n features_only=False,\n return_all_hiddens=False,\n )\n\n tokens = tokens.unsqueeze(-1)\n logits = torch.gather(features, -1, tokens).squeeze(-1)\n probs = logits.softmax(dim=-1)\n\n if single:\n return probs[0]\n else:\n return probs\n\n def max_probability(self, tokens):\n single = False\n\n # expand batch size 1\n if tokens.dim() == 1:\n single = True\n tokens = tokens.unsqueeze(0)\n\n with utils.eval(self.model):\n features, extra = self.model(\n tokens.long().to(device=self.device),\n features_only=False,\n return_all_hiddens=False,\n )\n\n logits, indices = torch.max(features, dim=-1)\n probs = logits.softmax(dim=-1)\n\n if single:\n return probs[0], indices[0]\n else:\n return probs, indices\n\n\n\n def disambiguate_pronoun(self, sentence: str) -> bool:\n \"\"\"\n Usage::\n\n >>> disambiguate_pronoun('The _trophy_ would not fit in the brown suitcase because [it] was too big.')\n True\n\n >>> disambiguate_pronoun('The trophy would not fit in the brown suitcase because [it] was too big.')\n 'The trophy'\n \"\"\"\n assert hasattr(\n self.task, \"disambiguate_pronoun\"\n ), \"roberta.disambiguate_pronoun() requires a model trained with the WSC task.\"\n with utils.model_eval(self.model):\n return self.task.disambiguate_pronoun(\n self.model, sentence, use_cuda=self.device.type == \"cuda\"\n )\n","sub_path":"fairseq/models/roberta/hub_interface.py","file_name":"hub_interface.py","file_ext":"py","file_size_in_byte":19138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"65807852","text":"import time\nimport os\nimport functools\nfrom plop.collector import Collector\n\n\ndef plop(log_to=\"/tmp/plop\", log_file=None):\n \"\"\" Decorator for your functions. Use this to profile your slow functions\n by adding a @plop(). \n \n @plop()\n def slow_function():\n return slow_stuff\n\n \"\"\"\n if log_file is None:\n log_file = str(int(time.time())) + \".log\"\n\n def decorator(function):\n @functools.wraps(function)\n\n def wrapper(*args, **kwargs):\n log = os.path.join(log_to,log_file)\n plop = Collector()\n plop.start()\n result = function(*args, **kwargs)\n plop.stop()\n with open(log, 'a') as f:\n f.write(repr(dict(plop.stack_counts)))\n return result\n\n return wrapper\n return decorator\n","sub_path":"plop/decorator.py","file_name":"decorator.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"84852583","text":"import tensorflow as tf\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport os\r\n\r\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\r\n\r\nplotdata={'batchsize':[],'loss':[]}\r\n\r\ntrain_x=np.linspace(-1,1,100)\r\ntrain_y=2*train_x+np.random.randn(100)*0.3\r\n\r\ntf.reset_default_graph()#初始化化图\r\n\r\nx=tf.placeholder('float')\r\ny=tf.placeholder('float')\r\n\r\nw=tf.Variable(tf.random_normal([1]),name='weight')\r\nb=tf.Variable(tf.zeros([1]),name='bise')\r\n\r\nz=tf.multiply(x,w)+b\r\ntf.summary.histogram('z',z ) #直方图显示\r\n\r\ncost=tf.reduce_mean(tf.square(y-z))\r\ntf.summary.scalar('cost',cost) #标量显示\r\n\r\nlearning_rate=0.01\r\noptimizer=tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)\r\ninit=tf.global_variables_initializer()\r\ntrain_epoch=20\r\ndisplay_epoch=2\r\nsaver=tf.train.Saver(max_to_keep=1)\r\nsavedir='log/'\r\nwith tf.Session() as sess:\r\n sess.run(init)\r\n mergar_summery_op=tf.summary.merge_all()\r\n summary_writer=tf.summary.FileWriter('log/with_summaries',sess.graph)\r\n for epoch in range(train_epoch):\r\n for (x1,y1) in zip(train_x,train_y):\r\n sess.run(optimizer,feed_dict=({x:x1,y:y1}))\r\n summary_str=sess.run(mergar_summery_op,feed_dict=({x:x1,y:y1}))\r\n summary_writer.add_summary(summary_str,epoch)\r\n if epoch % display_epoch==0:\r\n loss=sess.run(cost,feed_dict=({x:train_x,y:train_y}))\r\n print('epoch:',epoch+1,'cost', loss, sess.run(w), sess.run(b))\r\n plotdata['batchsize'].append(epoch)\r\n plotdata['loss'].append(loss)\r\n saver.save(sess,savedir+'linermodel.cpkt',global_step=epoch)\r\n plt.plot(train_x, train_y, 'ro')\r\n plt.plot(train_x,train_x*sess.run(w)+sess.run(b))\r\n plt.legend()\r\n plt.show()\r\n print('x=0.2:',sess.run(z,feed_dict=({x:0.2})))\r\nwith tf.Session() as sess2:\r\n sess2.run(tf.global_variables_initializer())\r\n saver.restore(sess2,savedir+'linermodel.cpkt-'+ str(18)) # 导出保存的模型\r\n print(sess2.run(z,feed_dict=({x:0.2})))\r\nwith tf.Session() as sess3:\r\n sess3.run(tf.global_variables_initializer())\r\n ckpt=tf.train.get_checkpoint_state(savedir)\r\n if ckpt and ckpt.model_checkpoint_path:\r\n saver.restore(sess3,ckpt.model_checkpoint_path)\r\n\r\n print(sess3.run(z,feed_dict=({x:0.2})))\r\nwith tf.Session() as sess4:\r\n sess4.run(tf.global_variables_initializer())\r\n kpt = tf.train.latest_checkpoint(savedir)\r\n if kpt!=None:\r\n saver.restore(sess4,kpt)\r\n print(sess4.run(z,feed_dict=({x:0.2})))","sub_path":"ray_LSTM/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"621545657","text":"# generator idea from https://machinelearningmastery.com\n\n\n#####################\n\n# use MLflow\n\n#####################\nimport mlflow.keras\n\nmlflow.keras.autolog()\n\nfrom keras.datasets.mnist import load_data\n\n# load data\n(trainX, trainy), (testX, testy) = load_data()\n\n\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, Dropout, Flatten, Dense, LeakyReLU, Conv2DTranspose, Reshape\nfrom keras.optimizers import Adam\nimport numpy as np\n\nfrom numpy import ones\nfrom numpy import zeros, vstack\nfrom numpy.random import randn\nfrom numpy.random import randint\n\n\n\n#@click.command(help=\"Trains an GAN Keras model on MNIST dataset.\"\n # \"The model and its metrics are logged with mlflow.\")\n#@click.option(\"--epochs\", type=click.INT, default=10, help=\"Number of training epochs\")\n\nclass mnist_GAN_Generator(object):\n\n def __init__(self, X_real):\n\n self.X = np.expand_dims(X_real, -1).astype('float32') / 255.0\n self.latent_dims = 100\n\n def define_discriminator(self, in_shape=(28, 28, 1)):\n model = Sequential()\n model.add(Conv2D(64, (3, 3), strides=(2, 2), padding='same', input_shape=in_shape))\n model.add(LeakyReLU(alpha=0.2))\n model.add(Dropout(0.4))\n model.add(Conv2D(64, (3, 3), strides=(2, 2), padding='same'))\n model.add(LeakyReLU(alpha=0.2))\n model.add(Dropout(0.4))\n model.add(Flatten())\n model.add(Dense(1, activation='sigmoid'))\n # compile model\n opt = Adam(lr=0.0002, beta_1=0.5)\n model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])\n return model\n\n def define_generator(self):\n model = Sequential()\n # foundation for 7x7 image\n n_nodes = 128 * 7 * 7\n model.add(Dense(n_nodes, input_dim=self.latent_dims))\n model.add(LeakyReLU(alpha=0.2))\n model.add(Reshape((7, 7, 128)))\n # upsample to 14x14\n model.add(Conv2DTranspose(128, (4, 4), strides=(2, 2), padding='same'))\n model.add(LeakyReLU(alpha=0.2))\n # upsample to 28x28\n model.add(Conv2DTranspose(128, (4, 4), strides=(2, 2), padding='same'))\n model.add(LeakyReLU(alpha=0.2))\n model.add(Conv2D(1, (7, 7), activation='sigmoid', padding='same'))\n return model\n\n # define the combined generator and discriminator model, for updating the generator\n\n def define_gan(self, g_model, d_model):\n # make weights in the discriminator not trainable\n d_model.trainable = False\n # connect them\n model = Sequential()\n # add generator\n model.add(g_model)\n # add the discriminator\n model.add(d_model)\n # compile model\n opt = Adam(lr=0.0002, beta_1=0.5)\n model.compile(loss='binary_crossentropy', optimizer=opt)\n return model\n\n # generate points in latent space as input for the generator\n def generate_latent_points(self, n_samples):\n # generate points in the latent space\n x_input = randn(self.latent_dims * n_samples)\n # reshape into a batch of inputs for the network\n x_input = x_input.reshape(n_samples, self.latent_dims)\n return x_input\n\n def generate_real_samples(self, n_samples):\n # choose random instances\n ix = randint(0, self.X.shape[0], n_samples)\n # retrieve selected images\n X = self.X[ix]\n # generate 'real' class labels (1)\n y = ones((n_samples, 1))\n return X, y\n\n def generate_fake_samples(self, g_model, n_samples):\n # generate points in latent space\n x_input = self.generate_latent_points(n_samples)\n # predict outputs\n X = g_model.predict(x_input)\n # create 'fake' class labels (0)\n y = zeros((n_samples, 1))\n return X, y\n\n # train the generator and discriminator\n def train(self, g_model, d_model, gan_model, n_epochs=100, n_batch=256):\n bat_per_epo = int(self.X.shape[0] / n_batch)\n half_batch = int(n_batch / 2)\n # manually enumerate epochs\n for i in range(n_epochs):\n # enumerate batches over the training set\n for j in range(bat_per_epo):\n # get randomly selected 'real' samples\n X_real, y_real = self.generate_real_samples(half_batch)\n # generate 'fake' examples\n X_fake, y_fake = self.generate_fake_samples(g_model, half_batch)\n # create training set for the discriminator\n X, y = vstack((X_real, X_fake)), vstack((y_real, y_fake))\n # update discriminator model weights\n d_loss, _ = d_model.train_on_batch(X, y)\n # prepare points in latent space as input for the generator\n X_gan = self.generate_latent_points(n_batch)\n # create inverted labels for the fake samples\n y_gan = ones((n_batch, 1))\n # update the generator via the discriminator's error\n g_loss = gan_model.train_on_batch(X_gan, y_gan)\n # summarize loss on this batch\n print('>%d, %d/%d, d=%.3f, g=%.3f' % (i + 1, j + 1, bat_per_epo, d_loss, g_loss))\n\n return g_model\n\n def plot_results(self, g_model):\n X, _ = self.generate_fake_samples(g_model, n_samples=25)\n # plot the generated samples\n for i in range(n_samples):\n # define subplot\n plt.subplot(5, 5, 1 + i)\n # turn off axis labels\n plt.axis('off')\n # plot single image\n plt.imshow(X[i, :, :, 0], cmap='gray_r')\n # show the figure\n plt.show()\n\n\nif __name__ == '__main__':\n\n\n gan_obj = mnist_GAN_Generator(trainX)\n\n g_model = gan_obj.define_generator()\n d_model = gan_obj.define_discriminator()\n gan_model = gan_obj.define_gan(g_model, d_model)\n\n #use generation model to generate synthetic MNIST digits\n\n generation_model = gan_obj.train(g_model, d_model, gan_model)\n gan_obj.plot_results(generation_model)\n\n\n","sub_path":"tasks/computer-vision/image-generation/GAN_MNIST/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"206636631","text":"ins = open( \"numbers.txt\", \"r\" )\ntext = ''\ntotal = 0\n\nfor line in ins:\n text += line\n\nnewFile = text.splitlines()\n\nfor i in range(len(newFile)):\n total += int(newFile[i])\n\nprint(str(total)[0:10])\n","sub_path":"programming-puzzles/projecteuler/project-0013/euler-0013.py","file_name":"euler-0013.py","file_ext":"py","file_size_in_byte":202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"262763419","text":"# 时间:2020.10.10 14点24分\n# 描述:请编写程序输出前n个正整数的全排列(n<10),并通过9个测试用例(即n从1到9)观察n逐步增大时程序的运行时间\n# 输入:输入给出正整数n(<10)。\n# 输出:输出1到n的全排列。每种排列占一行,数字间无空格。排列的输出顺序为字典序\n# 改良版:解决内存超限问题\nimport itertools\n\n\ndef Permutation(numbers):\n \"对元素进行全排列,并将结果保存在一个列表中返回\"\n result=[]\n numbers_len=len(numbers)\n\n if numbers_len==1:\n #当集合中只有它自身的时候,返回自己\n return [numbers]\n else:\n for i in numbers:\n # 遍历每一个元素,得到当前字符和其他字符集合\n temp=numbers.copy()\n temp.remove(i)\n\n # 递归关键步骤:ri Prem(temp)\n result +=[[i] + k for k in Permutation(temp)]\n\n return result\n\n#获取输入值n\nn=int(input())\n\n#根据输入获取元素集合\nnumbers=list(range(1, n + 1))\n\n'''\n\n# 对元素进行全排列,并将结果输出\nresult_Permutation=Permutation(numbers)\nfor i in result_Permutation:\n # 列表里保存的是“嵌套”的结果,所有需要处理一下:循环输出每一个\n print(\"\".join([str(n) for n in i]))\n\n'''\n\n#改良版:解决内存超限问题,调用自带的工具\nresult=list(itertools.permutations(numbers, n))\n\n#输出结果\nfor i in result:\n # 列表里保存的是“嵌套”的结果,所有需要处理一下:循环输出每一个\n print(\"\".join([str(n) for n in i]))\n\n","sub_path":"第三周任务/Permutation.py","file_name":"Permutation.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"622565402","text":"from board import *\nimport random\nimport math\n\n##################################################################\nclass Node(object): \n player = None # root of the tree\n \n def __init__(self, board, turn):\n self.state = board\n self.turn = turn # may not be Node.player\n self.action = board.validMoves(turn)\n \n def isLeaf(self):\n # should be extended to consider next turn by the opponent..\n return len(self.action) == 0\n\n def reward(self):\n return 1 if self.state.winner() == Node.player else -1\n \n def randomChild(self):\n move = random.choice(self.action)\n boardNext = self.state.boardAfterMove(self.turn, move)\n return Node(boardNext, opponent(self.turn))\n \n##################################################################\nclass NodeMCTS(Node):\n created = dict() # key: hash value / val: board\n\n @classmethod\n def init(cls, player):\n Node.player = player\n cls.created.clear()\n \n # should be called by the class method create() only\n def __init__(self, board, parent=None, parentAction=None):\n if parent == None: # root\n turn = Node.player\n else:\n turn = opponent(parent.turn)\n Node.__init__(self, board, turn)\n self._parent = parent\n self.parentAction = parentAction\n self.child = [None]*len(self.action) # currently expanded children\n self.N = 0\n self.Q = 0\n\n @classmethod\n def create(cls, board, parent=None, parentAction=None):\n return NodeMCTS(board, parent, parentAction)\n \"\"\"\n hashValue = board.hashValue()\n if hashValue in cls.created:\n return cls.created[hashValue]\n else:\n node = NodeMCTS(board, parent, parentAction)\n cls.created[hashValue] = node\n return node\n \"\"\"\n \n def isRoot(self): return self._parent == None\n def parent(self): return self._parent\n \n def fullyExpanded(self): return (None not in self.child)\n\n def expand(self):\n n = len(self.action)\n L = []\n for i in range(n):\n if self.child[i] == None:\n L.append(i)\n i = random.choice(L)\n move = self.action[i]\n boardNext = self.state.boardAfterMove(self.turn, move)\n node = NodeMCTS.create(boardNext, self, move)\n self.child[i] = node\n return node\n\n def bestChild(self, c):\n best = None\n max = -10000000\n for node in self.child:\n if node == None: continue # node that is not yet expanded\n assert node.N >= 1\n val = float(node.Q)/node.N + c*(math.log(self.N)/node.N)**0.5\n if max < val:\n best = node\n max = val\n return best, max\n \n def update(self, delta):\n self.N += 1\n self.Q += delta\n\n##################################################################\nclass MCTS:\n def __init__(self, board, player, curDepth, maxDepth, canvas=None):\n #random.seed(0) # make deterministic for DEBUG\n NodeMCTS.init(player)\n self.root = NodeMCTS.create(board)\n self.player = player\n self.curDepth = curDepth\n self.maxDepth = maxDepth\n self.canvas = canvas\n \n def run(self):\n for i in range(NUM_MC_TRIALS):\n v = self.treePolicy()\n delta = self.defaultPolicy(v)\n self.backup(v, delta)\n bestChild, maxVal = self.root.bestChild(0)\n return (maxVal, bestChild.parentAction)\n\n def treePolicy(self):\n v = self.root\n depth = self.curDepth\n while not v.isLeaf() and depth < self.maxDepth:\n depth += 1\n if not v.fullyExpanded():\n return v.expand()\n else:\n v, _ = v.bestChild(2)\n return v\n\n def defaultPolicy(self, v): # later measure \n depth = self.curDepth\n while not v.isLeaf() and depth < self.maxDepth:\n depth += 1\n v = v.randomChild()\n # print (\"depth of MCTS:\", depth)\n return v.reward()\n\n def backup(self, v, delta):\n while True:\n v.update(delta)\n if v.isRoot(): break\n v = v.parent()\n","sub_path":"code/L07_2/tree_search_MCTS.py","file_name":"tree_search_MCTS.py","file_ext":"py","file_size_in_byte":4289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"607544310","text":"def writerChildFunction(\nqTo\n,qFrom\n, window_size = [200,200]\n, window_position = [0,0]\n):\n\timport sdl2\n\timport sdl2.ext\n\timport sys\n\timport time\n\ttry:\n\t\timport appnope\n\t\tappnope.nope()\n\texcept:\n\t\tpass\n\n\tsdl2.SDL_Init(sdl2.SDL_INIT_VIDEO)\n\twindow = sdl2.ext.Window(\"writer\",size=window_size,position=window_position,flags=sdl2.SDL_WINDOW_SHOWN)\n\twindowID = sdl2.SDL_GetWindowID(window.window)\n\twindowSurf = sdl2.SDL_GetWindowSurface(window.window)\n\tsdl2.ext.fill(windowSurf.contents,sdl2.pixels.SDL_Color(r=255, g=255, b=255, a=255))\n\twindow.refresh()\n\n\tfor i in range(10):\n\t\tsdl2.SDL_PumpEvents() #to show the windows\n\n\tfiles = {}\n\n\tdef exitSafely():\n\t\ttry:\n\t\t\tfor index,fileObj in files.items():\n\t\t\t\tfileObj.close()\n\t\t\t\t# gpg -r \"Michael Lawrence \" -e mac.txt\n\t\texcept:\n\t\t\tpass\n\t\tsys.exit()\n\n\twhile True:\n\t\tif not qTo.empty():\n\t\t\tmessage = qTo.get()\n\t\t\tif message=='quit':\n\t\t\t\texitSafely()\n\t\t\telif message[0]=='new_file':\n\t\t\t\tfiles[message[1]] = open(message[2],'w')\n\t\t\telif message[0]=='write':\n\t\t\t\tfiles[message[1]].write(message[2]+'\\n')\n\t\telse:\n\t\t\ttime.sleep(1)\n\t\tsdl2.SDL_PumpEvents()\n\t\tfor event in sdl2.ext.get_events():\n\t\t\tif event.type==sdl2.SDL_WINDOWEVENT:\n\t\t\t\tif (event.window.event==sdl2.SDL_WINDOWEVENT_CLOSE):\n\t\t\t\t\texitSafely()\n\nwriterChildFunction(qTo,qFrom,**initDict)","sub_path":"writer_child.py","file_name":"writer_child.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"570255596","text":"'''\nA palindromic number reads the same both ways. The largest\npalindrome made from the product of two 2-digit numbers is\n9009 = 91 x 99.\n\nFind the largest palindrome made from the product of two 3-digit numbers.\n'''\n\n#Working palindrome detector\ndef isPalindrome(numCheck):\n\tfirstHalf = \"\"\n\tsecondHalf = \"\"\n\tnumCheck = str(numCheck)\n\n\n\tfor i in range(0,int(len(numCheck)/2)):\n\t\tfirstHalf += numCheck[i]\n\tfor i in range(int(len(numCheck))-1, int(len(numCheck)/2)-1, -1):\n\t\tsecondHalf += numCheck[i]\n\n\tif (firstHalf == secondHalf):\n\t\treturn True\n\treturn False\n\nanswer = 0\nfor i in range(100,999):\n\tfor j in range(100,999):\n\t\tif (isPalindrome(i*j)):\n\t\t\tif (i*j > answer):\n\t\t\t\tanswer = i*j\n\t\t\t#print(\"Found: \" + str(i*j) + \" = \" + str(i) + \" X \" + str(j))\nprint(\"==============\")\nprint(\" Results\")\nprint(\"==============\")\nprint(\"Answer: \" + str(answer))\ninput()","sub_path":"Euler4.py","file_name":"Euler4.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"538938893","text":"# Authors: Brian O'Connor\n# Date: March 2018\n#\n# Description: a quick script to load the lambda\n\nimport os\nimport os.path\nimport argparse\nimport json\nimport jsonschema\nimport datetime\nimport re\nimport dateutil\nimport ast\n#from urllib import urlopen\nfrom subprocess import Popen, PIPE\n\ndef input_Options():\n \"\"\"\n Creates the parse options\n \"\"\"\n parser = argparse.ArgumentParser(description='Directory that contains Json files.')\n parser.add_argument('-d', '--test-directory', help='Directory that contains the json metadata files')\n\n args = parser.parse_args()\n return args\n\ndef main():\n args = input_Options()\n\n # environment\n my_env = os.environ.copy()\n\n # delete\n command=\"aws cloudformation delete-stack --stack-name apigateway\"\n run_command(command)\n run_command(\"sleep 30\")\n\n # download deps\n command=\"npm install --production\"\n run_command(command)\n\n # start by bundling\n command=\"./bundle.sh\"\n run_command(command)\n\n # upload\n command=\"aws s3 cp lambda.zip s3://$S3Bucket/lambda.zip\"\n run_command(command)\n\n # create stack\n command=\"aws cloudformation create-stack --stack-name apigateway --template-body file://template.json --capabilities CAPABILITY_IAM --parameters ParameterKey=S3Bucket,ParameterValue=$S3Bucket\"\n run_command(command)\n\n # wait for stack\n command=\"aws cloudformation wait stack-create-complete --stack-name apigateway\"\n run_command(command)\n\n # pull back arn\n command=\"aws cloudformation describe-stacks --stack-name apigateway --query Stacks[0].Outputs\"\n stdout, stderr = run_command(command)\n metadata_struct = json.loads(stdout)\n print (\"ARN INFO: \"+str(metadata_struct[0]['OutputValue']))\n arn_str = str(metadata_struct[0]['OutputValue'])\n\n # use the ARN in the template\n command=\"sed 's/$LambdaArn/\"+arn_str+\"/g' swagger.json.template > swagger.json\"\n run_command(command)\n\n command=\"aws apigateway import-rest-api --fail-on-warnings --body file://swagger.json\"\n stdout, stderr = run_command(command)\n metadata_struct = json.loads(stdout)\n ApiId = metadata_struct['id']\n\n command=\"aws cloudformation update-stack --stack-name apigateway --template-body file://template.json --capabilities CAPABILITY_IAM --parameters ParameterKey=S3Bucket,UsePreviousValue=true ParameterKey=S3Key,UsePreviousValue=true ParameterKey=ApiId,ParameterValue=\"+str(ApiId)\n run_command(command)\n\n command=\"aws apigateway create-deployment --rest-api-id \"+str(ApiId)+\" --stage-name v1\"\n run_command(command)\n\ndef run_command(command):\n my_env = os.environ.copy()\n print(\"COMMAND: \"+str(command))\n c_data=Popen(command, shell=True, stdout=PIPE, stderr=PIPE, env=my_env)\n stdout, stderr = c_data.communicate()\n print(\"STDOUT: \"+str(stdout))\n print(\"STDERR: \"+str(stderr))\n return(stdout, stderr)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":2905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"508376387","text":"\"\"\"\nGiven an array of integers, find two numbers such that they add up to a specific target number.\n\nThe function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.\n\nYou may assume that each input would have exactly one solution.\n\nInput: numbers={2, 7, 11, 15}, target=9\nOutput: index1=1, index2=2\n\"\"\"\n\n\nclass Solution:\n # @return a tuple, (index1, index2)\n def twoSum(self, num, target):\n storage = {}\n for i, x in enumerate(num):\n if x in storage:\n return [storage[x], i + 1]\n else:\n storage[target - x] = i + 1\n return []\n \n","sub_path":"leetcode/Two Sum.py","file_name":"Two Sum.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"176250755","text":"import logging\n\n\nclass Logger(object):\n @staticmethod\n def setLogger(name, filePath = 'cardata.log'):#/media/pi/usb/logCarData/\n logger = logging.getLogger(name)\n logger.setLevel(logging.INFO)\n\n formatter = logging.Formatter('%(name)s - %(levelname)s: %(message)s')\n fh = logging.FileHandler(filePath)\n fh.setLevel(logging.INFO)\n ch = logging.StreamHandler()\n ch.setLevel(logging.INFO)\n\n fh.setFormatter(formatter)\n ch.setFormatter(formatter)\n\n logger.addHandler(fh)\n logger.addHandler(ch)\n return logger\n\n\n","sub_path":"OperationUtils/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"359816246","text":"import QAction\nimport QStatus\nimport QTools\nimport Quasar\n\nimport calendar\nimport time\n\nclass QPing(QAction.QAction):\n def __init__(self, device_type='Q330', show_restricted=False, show_unavailable=False):\n self._raw_results = {}\n self._device_type = device_type\n self._show_restricted = show_restricted\n self._show_unavailable = show_restricted\n self._restricted_status = [\n 'PowerSupply',\n 'Thread',\n ]\n self._bitmapped_status = {\n 'AuxiliaryBoard' : 2,\n 'DynamicIP' : 1,\n 'EnvironmentalProcessor' : 6,\n 'SerialSensor' : 4,\n }\n self._unsupported_status = []\n self.private = [\n 'action',\n 'status'\n ]\n QAction.QAction.__init__(self)\n\n def get_raw_results(self):\n return self._raw_results\n\n def get_raw_result(self, key):\n result = None\n if self._raw_results.has_key(key):\n result = self._raw_results[key]\n return result\n\n def is_restricted(self, status):\n return status in self._restricted_status\n\n def remove_restricted(self, statuses):\n pruned = []\n for status in statuses:\n if status not in self._restricted_status:\n pruned.append(status)\n return pruned\n\n\n def val_action(self, value):\n if type(value) != str:\n raise TypeError('action')\n if value not in ['detect', 'info', 'status', 'monitor']:\n raise ValueError('action')\n return value\n\n def val_status(self, value):\n n_value = []\n if type(value) != list:\n raise TypeError('status')\n for status in value:\n type_list = Quasar.Status.StatusBits[self._device_type].keys()\n if status == \"all\":\n n_value = type_list\n if not self._show_restricted:\n n_value = self.remove_restricted(n_value)\n break;\n else:\n restrictions = self._restricted_status\n if self._show_restricted:\n restrictions = []\n r_status = QTools.verify_status_type(status, type_list, exclusions=restrictions)\n if (r_status is None) and (status != 'all'):\n raise ValueError('status')\n #if self.is_restricted(r_status):\n # raise ValueError('status')\n n_value.extend(r_status)\n value = n_value\n return value\n\n def _execute(self, q330):\n method_name = '_exec_' + self.action\n getattr(self, method_name)(q330)\n\n def _exec_detect(self, q330):\n ping = Quasar.Commands.c1_ping.c1_ping()\n time_start = time.time() * 1000.0\n response = q330.sendCommand(ping, 0)\n time_end = time.time() * 1000.0\n if isinstance(response, Quasar.Commands.c1_ping.c1_ping) and (response.getType() == 1):\n self._print(\"Ping received a response. Delay was %.02f ms\" % (time_end - time_start))\n else:\n raise QTools.QExMessage(\"Ping failed\")\n\n def _exec_info(self, q330):\n ping_result = self._ping_info(q330)\n if ping_result is not None:\n sub_dict = QStatus.formatPingInfo(ping_result)\n values = []\n for sub_key in sub_dict.keys():\n values.append(sub_dict[sub_key])\n values.sort()\n main_title = \"Ping Info\"\n self._print(\"%s:\" % main_title)\n self._print(\"\".rjust(len(main_title), \"=\"))\n max_title_len = max(map(len, map(lambda x: x[1], values)))\n for (idx, title, value) in values:\n self._print(\" %s: %s\" % (title.rjust(max_title_len), value))\n self._add_result(sub_dict)\n else:\n raise QTools.QExMessage(\"Ping failed\")\n\n def _ping_info(self, q330):\n result = None\n ping = Quasar.Commands.c1_ping.c1_ping(type=4)\n response = q330.sendCommand(ping, 0)\n if isinstance(response, Quasar.Commands.c1_ping.c1_ping) and (response.getType() == 5):\n result = response.asDictionary()\n self._raw_results['ping_info'] = result\n return result\n\n def _ping_status(self, q330):\n result = None\n ping = Quasar.Commands.c1_ping.c1_ping(type=2)\n ping.setStatusRequestBitmap(0)\n response = q330.sendCommand(ping, 0)\n if isinstance(response, Quasar.Commands.c1_ping.c1_ping) and (response.getType() == 3):\n result = response.asDictionary()\n self._raw_results['ping_status'] = result\n return result\n\n def _batch_ping(self, q330, status_types):\n include_ping_data = False\n include_ping_info = False\n bitmap_checks = []\n\n results = {}\n self.remaining = {}\n for status in status_types:\n if status == 'ping_status':\n include_ping_data = True\n elif status == 'ping_info':\n include_ping_info = True\n else:\n if self._bitmapped_status.has_key(status):\n include_ping_info = True\n bitmap_checks.append(status)\n self.remaining[status] = 1\n\n if include_ping_info:\n results['ping_info'] = self._ping_info(q330)\n\n self._unsupported_status = []\n if len(bitmap_checks):\n bitmap = results['ping_info']['Flags']\n for key in bitmap_checks:\n if (bitmap & (0x00000001 << self._bitmapped_status[key])) == 0:\n if not self._show_unavailable:\n del self.remaining[key]\n self._unsupported_status.append(key)\n\n if len(self._unsupported_status):\n self._print(\"The following status are not available:\")\n for s in self._unsupported_status:\n self._print(\" %s\" % s)\n self._print()\n\n while len(self.remaining.keys()):\n ping = Quasar.Commands.c1_ping.c1_ping(type=2)\n request_keys = self.remaining.keys()\n bitmap = Quasar.Status.getBitmapFromKeys(request_keys, q330.getDeviceType())\n ping.setStatusRequestBitmap(bitmap)\n\n responses = q330.sendCommand(ping, receiveMultiple=1)\n for response in responses:\n status_types = []\n if response.getType() == 3:\n status_types = Quasar.Status.getKeysFromBitmap(response.getStatusBitmap(), q330.getDeviceType())\n if include_ping_data:\n result = response.asDictionary()\n results['ping_status'] = result\n self._raw_results['ping_status'] = result\n for status_type in status_types:\n if self.remaining.has_key(status_type):\n results[status_type] = response.getStatusClass().asDictionary()\n del self.remaining[status_type]\n return results\n\n def _exec_status(self, q330):\n if self.status[0] == 'all':\n self.status = sorted(Quasar.Status.StatusBits[q330.getDeviceType()].keys())\n all_results = self._batch_ping(q330, self.status)\n for status_type in sorted(self.status):\n if not all_results.has_key(status_type):\n continue\n result_dict = all_results[status_type]\n # Store the raw results\n self._raw_results[status_type] = result_dict\n # Fomat the results\n results = QStatus.formatted({status_type:result_dict})\n key = status_type\n main_title = \"%s Status\" % key\n self._print(\"%s:\" % main_title)\n self._print(\"\".rjust(len(main_title), \"=\"))\n sub_dict = results[key]\n values = []\n for sub_key in sub_dict.keys():\n values.append(sub_dict[sub_key])\n values.sort()\n max_title_len = max(map(len, map(lambda x: x[1], values)))\n for (idx, title, value) in values:\n self._print(\" %s: %s\" % (title.rjust(max_title_len), value))\n self._print()\n self._add_result(results[key])\n\n def _exec_monitor(self, q330):\n status_types = [ 'ping_info', \n 'ping_status',\n 'Global', \n 'PLL',\n 'BoomPosition',\n 'DataPort1',\n 'DataPort2',\n 'DataPort3',\n 'DataPort4' ]\n\n # Collect all of the status information needed in order\n # to construct our results. This way all of our data \n # is available at once, which is useful considering that\n # some of the information for sections in the print-out\n # are pulled from multiple status types.\n #\n # _batch_ping uses the minimum necessary number of request\n results = self._batch_ping(q330, status_types)\n\n # Ping Info Stats\n if results.has_key('ping_info'):\n result = results['ping_info']\n # Tag ID\n if result.has_key('KMIPropertyTag') and result.has_key('SystemSoftwareVersion'):\n version = result['SystemSoftwareVersion']\n version_major = version >> 8\n version_minor = version & 0x00ff\n self._print(\" Tag ID: %d\" % result['KMIPropertyTag'])\n self._print(\" Firmware: %d.%d\" % (version_major, version_minor))\n # Ping Status Stats\n if results.has_key('ping_status'):\n result = results['ping_status']\n # Time of Last Reboot\n if result.has_key('TimeOfLastReboot'):\n time_reboot = QTools.q330_to_unix_time(result['TimeOfLastReboot'])\n time_now = float(calendar.timegm(time.gmtime()))\n uptime = (time_now - time_reboot) / 86400.0\n self._print(\" Boot Time: %s UTC (%.02f days uptime)\" % (time.strftime(\"%Y/%m/%d %H:%M\", time.gmtime(time_reboot)), uptime))\n # Global Stats\n if results.has_key('Global'):\n result = Quasar.Status.StatusDict(results['Global'], prefix='Global_')\n # Station Time\n if result.has_key('SecondsOffset') and result.has_key('USecOffset') and result.has_key('CurrentDataSequenceNumber'):\n seconds = result['SecondsOffset'] + result['CurrentDataSequenceNumber']\n usecs = result['USecOffset']\n time_now = float(calendar.timegm(time.gmtime()))\n time_station = QTools.q330_to_unix_time(seconds)\n self._print(\" GPS Time: %s.%06d\" % (time.strftime(\"%Y/%m/%d %H:%M:%S\", time.gmtime(time_station)), usecs))\n # Clock Quality\n if result.has_key('ClockQuality'):\n clock_quality = result['ClockQuality']\n result_string = \"\"\n if ((clock_quality & 0xc0) >> 6) == 1:\n result_string += \"PLL Hold\"\n elif ((clock_quality & 0xc0) >> 6) == 2:\n result_string += \"PLL Tracking\"\n elif ((clock_quality & 0xc0) >> 6) == 3:\n result_string += \"PLL Locked\"\n else:\n result_string += \"PLL not enabled\"\n if not (clock_quality & 0x01):\n result_string += \" (Clock has never been locked)\"\n elif clock_quality & 0x20:\n result_string += \" (Speculative Lock based on internal clock)\"\n elif clock_quality & 0x10:\n result_string += \" (Timemarks currently frozen due to filtering)\"\n elif clock_quality & 0x04:\n result_string += \" (Clock has 3-D lock)\"\n elif clock_quality & 0x02:\n result_string += \" (Clock has 2-D lock)\"\n elif clock_quality & 0x08:\n result_string += \" (Clock has 1-D lock)\"\n else:\n result_string += \" (Clock has been locked)\"\n self._print(\" Clock Quality: %s\" % result_string)\n # PLL Stats\n if results.has_key('PLL'):\n result = Quasar.Status.StatusDict(results['PLL'], prefix='PLL_')\n # Phase\n if result.has_key('TimeError'):\n time_error = result['TimeError']\n result_string = \"%dus\" % int(time_error * 1000000)\n self._print(\" Phase: %s\" % result_string)\n # Boom Position Stats\n if results.has_key('BoomPosition'):\n result = Quasar.Status.StatusDict(results['BoomPosition'], prefix='BoomPosition_')\n # System Temperature\n if result.has_key('SystemTemperature'):\n self._print(\" Temperature: %d C\" % result['SystemTemperature'])\n # System Power\n if result.has_key('InputPower') and result.has_key('MainCurrent'):\n volts = result['InputPower'] * 0.15\n amps = result['MainCurrent'] / 1000.0\n watts = volts * amps\n self._print(\" Input Power: %.02f VDC, %.02f W\" % (volts, watts))\n if result.has_key('MainCurrent'):\n pass\n # Boom Positions\n for i in range(1,7):\n key = \"Channel%dBoom\" % i\n position = \"Unknown\"\n if result.has_key(key):\n position = \"%d\" % result[key]\n result_string = \" Boom %d: %s\" % (i, position)\n self._print(result_string)\n\n # Data Port Stats\n if results.has_key('ping_info'):\n info = results['ping_info']\n data_ports = {}\n max_capacity_len = 0\n max_percent_len = 0\n max_packets_len = 0\n for i in range(1, 5):\n data_ports[i] = {}\n dp_info = data_ports[i]\n key = \"DataPort%d\" % i\n port_key = \"DataPort%dPacketMemorySize\" % i\n if results.has_key(key) and info.has_key(port_key):\n result = Quasar.Status.StatusDict(results[key], prefix=key+'_')\n buffer_bytes = info[port_key]\n buffer_capacity = buffer_bytes / 1048576.0\n buffer_capacity_str = \"%.02f\" % buffer_capacity\n max_capacity_len = max(len(buffer_capacity_str), max_capacity_len)\n dp_info['capacity'] = buffer_capacity_str\n # Buffer Percent Full\n if result.has_key('BytesOfPacketCurrentlyUsed'):\n buffer_used = float(result['BytesOfPacketCurrentlyUsed'])\n buffer_percent = (buffer_used / buffer_bytes) * 100.0\n buffer_percent_str = \"%.02f%%\" % buffer_percent\n max_percent_len = max(len(buffer_percent_str), max_percent_len)\n dp_info['percent'] = buffer_percent_str\n # Packet Counts\n if result.has_key('TotalDataPacketsSent'):\n packet_count_str = QTools.fancy_integer(result['TotalDataPacketsSent'])\n max_packets_len = max(len(packet_count_str), max_packets_len)\n dp_info['packets'] = packet_count_str\n\n for i in range(1, 5):\n dp_info = data_ports[i]\n data_port_str = \" Data Port %d:\" % i\n if dp_info.has_key('capacity'):\n data_port_str += \" %s MiB\" % dp_info['capacity'].rjust(max_capacity_len)\n if dp_info.has_key('percent'):\n data_port_str += \" (%s full).\" % dp_info['percent'].rjust(max_percent_len)\n if dp_info.has_key('packets'):\n data_port_str += \" Packets sent: %s\" % dp_info['packets'].rjust(max_packets_len)\n\n self._print(data_port_str)\n\n self._add_result(results)\n\n","sub_path":"CnC/QPing.py","file_name":"QPing.py","file_ext":"py","file_size_in_byte":16100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"319285985","text":"\n# use https://github.com/JRodrigoF/AVrecordeR to mix video and audio\nimport cv2\nimport imagezmq\nimage_hub = imagezmq.ImageHub()\nwhile True: # show streamed images until Ctrl-C\n\tprint(\"here\")\n\trpi_name, image = image_hub.recv_image()\n\tcv2.imshow(rpi_name, image) # 1 window for each RPi\n\tcv2.waitKey(1)\n\timage_hub.send_reply(b'OK')\n\n","sub_path":"imagezmq-streaming/simpleReceiver.py","file_name":"simpleReceiver.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"498386462","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\n\nfrom django.conf import settings\n\nimport responses\n\nfrom olympia.amo.tests import addon_factory, TestCase, user_factory\nfrom olympia.ratings.models import Rating\n\nfrom .models import AkismetReport\n\n\nclass TestAkismetReportsModel(TestCase):\n\n def test_create_for_rating(self):\n user = user_factory(homepage='https://spam.spam/')\n addon = addon_factory()\n rating = Rating.objects.create(\n addon=addon, user=user, rating=4, body='spám?',\n ip_address='1.23.45.67')\n ua = 'foo/baa'\n referrer = 'https://mozilla.org/'\n report = AkismetReport.create_for_rating(rating, ua, referrer)\n\n assert report.rating_instance == rating\n data = report._get_data()\n assert data == {\n 'blog': settings.SITE_URL,\n 'user_ip': rating.ip_address,\n 'user_agent': ua,\n 'referrer': referrer,\n 'permalink': addon.get_url_path(),\n 'comment_type': 'user-review',\n 'comment_author': user.username,\n 'comment_author_email': user.email,\n 'comment_author_url': user.homepage,\n 'comment_content': rating.body,\n 'comment_date_gmt': rating.modified,\n 'comment_post_modified_gmt': addon.last_updated,\n 'blog_charset': 'utf-8',\n 'is_test': not settings.AKISMET_REAL_SUBMIT,\n }\n\n def _create_report(self, kws=None):\n defaults = dict(\n comment_type='user-review',\n user_ip='9.8.7.6.5',\n user_agent='Agent Bond',\n referrer='á4565',\n user_name='steve',\n user_email='steve@steve.com',\n user_homepage='http://spam.spam',\n content_link='https://addons.mozilla.org',\n content_modified=datetime.now(),\n comment='spammy McSpam?',\n comment_modified=datetime.now(),\n )\n if kws:\n defaults.update(**kws)\n instance = AkismetReport.objects.create(**defaults)\n return instance\n\n @responses.activate\n def test_comment_check(self):\n report = self._create_report()\n\n url = settings.AKISMET_API_URL.format(\n api_key='none', action='comment-check')\n responses.add(responses.POST, url, json=True)\n responses.add(\n responses.POST, url, json=True,\n headers={'X-akismet-pro-tip': 'discard'})\n # Headers should be ignored on False but add anyway.\n responses.add(\n responses.POST, url, json=False,\n headers={'X-akismet-pro-tip': 'discard'})\n\n result = report.comment_check()\n assert result == report.result == AkismetReport.MAYBE_SPAM\n\n result = report.comment_check()\n assert result == report.result == AkismetReport.DEFINITE_SPAM\n\n result = report.comment_check()\n assert result == report.result == AkismetReport.HAM\n","sub_path":"src/olympia/lib/akismet/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"205653830","text":"#!/usr/bin/python3\n\"\"\"show all states or only state id\"\"\"\nfrom api.v1.views import app_views, index\nfrom models.state import State\nfrom models import storage\nfrom flask import jsonify, abort, make_response, request\n\n\n@app_views.route('/states/', methods=['GET'], strict_slashes=False)\ndef retrieve_obj():\n \"\"\"list of all State objects\"\"\"\n all_obj = []\n for obj in storage.all('State').values():\n all_obj.append(obj.to_dict())\n return jsonify(all_obj)\n\n\n@app_views.route('states/', methods=['GET'], strict_slashes=False)\ndef retrieve_obj_id(state_id):\n \"\"\"the state based on the id \"\"\"\n obj = storage.get('State', state_id)\n if obj is None:\n abort(404)\n return jsonify(obj.to_dict())\n\n\n@app_views.route('states/', methods=['DELETE'], strict_slashes=False)\ndef delete_id(state_id):\n \"\"\" funtion to deletes a State for id\"\"\"\n obj = storage.get('State', state_id)\n if obj is None:\n abort(404)\n else:\n storage.delete(obj)\n storage.save()\n return make_response(jsonify({}), 200)\n\n\n@app_views.route('/states', methods=['POST'])\ndef create_state():\n \"\"\"Create new state\"\"\"\n data = request.get_json(silent=True)\n if data is None:\n abort(400, \"Not a JSON\")\n elif \"name\" not in data.keys():\n abort(400, \"Missing Name\")\n else:\n new_state = State(**data)\n storage.new(new_state)\n storage.save()\n return make_response(jsonify(new_state.to_dict()), 201)\n\n\n@app_views.route('/states/', methods=['PUT'])\ndef update_state(state_id=None):\n \"\"\"Update state for id\"\"\"\n data = storage.get('State', state_id)\n if data is None:\n abort(404)\n\n r = request.get_json(silent=True)\n if r is None:\n abort(400, \"Not a JSON\")\n else:\n for key, value in r.items():\n if key in ['id', 'created_at', 'updated_at']:\n pass\n else:\n setattr(data, key, value)\n storage.save()\n return make_response(jsonify(data.to_dict()), 200)\n","sub_path":"api/v1/views/states.py","file_name":"states.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"228940634","text":"#Done by Carlos Amaral (22/07/2020)\n\n\nimport csv\n\nfilename = 'data/sitka_weather_07-2018_simple.csv'\nwith open(filename) as f:\n reader = csv.reader(f)\n header_row = next(reader)\n\n #Get high temperatures from this file.\n highs = []\n for row in reader:\n high = int(row[5])\n highs.append(high)\n\nprint(highs)","sub_path":"Chapter_16_Downloading_Data/csv_file_format/sitka_highs2.py","file_name":"sitka_highs2.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"230058293","text":"def getDataFromCSV(fileName=\"../Datasets/multiple_linear_regression.csv\"):\n fileContent = getFileContents(fileName).split(\"\\n\")\n x = []\n y = []\n i = 0\n for row in fileContent:\n arr = row.split(',')\n x.append([1, int(arr[0]), int(arr[1])])\n y.append(float(arr[2]))\n i = i + 1\n result = [x, y]\n return result\n\n\ndef getFileContents(fileName):\n fileDataSet = open(fileName);\n fileContent = fileDataSet.read()\n return fileContent\n\n\ndef saveData(data, fileName=\"teta.csv\"):\n fileData = open(fileName, 'w+')\n fileData.write(str(data[0]) + \",\" + str(data[1]) + \",\" + str(data[2]))\n","sub_path":"LinearRegression/old/fileSystem.py","file_name":"fileSystem.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"564500189","text":"# Solve the following system of three equations and three unknowns in Numpy and report the solution:\n#\n# 2x + 6y -z = 0\n# x + 2y - 2z = 1\n# -5x + 2z = 8\n\nimport numpy as np\n\na = np.array([[2, 6, -1],\n [1, 2, -2],\n [-5, 0, 2]])\n\nb = np.array([0, 1, 8])\n\n# compute the inverse\nA_inv = np.linalg.inv(a)\n\n# solution: A_inv * b\nx = np.dot(A_inv, b)\nprint(x)\n","sub_path":"linear_transformation/linear_equation.py","file_name":"linear_equation.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"298959209","text":"# Copyright 2013-2014 Eucalyptus Systems, Inc.\n#\n# Redistribution and use of this software in source and binary forms,\n# with or without modification, are permitted provided that the following\n# conditions are met:\n#\n# Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\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#\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 multiprocessing import Process\nimport os\nimport subprocess\nimport sys\nimport threading\nimport traceback\n\n\ndef close_all_fds(except_fds=None):\n except_filenos = [1, 2]\n if except_fds is not None:\n for except_fd in except_fds:\n if except_fd is None:\n pass\n elif isinstance(except_fd, int):\n except_filenos.append(except_fd)\n elif hasattr(except_fd, 'fileno'):\n except_filenos.append(except_fd.fileno())\n else:\n raise ValueError('{0} must be an int or have a fileno method'\n .format(repr(except_fd)))\n\n fileno_ranges = []\n next_range_min = 0\n for except_fileno in sorted(except_filenos):\n if except_fileno > next_range_min:\n fileno_ranges.append((next_range_min, except_fileno - 1))\n next_range_min = max(next_range_min, except_fileno + 1)\n fileno_ranges.append((next_range_min, 1024))\n\n for fileno_range in fileno_ranges:\n os.closerange(fileno_range[0], fileno_range[1])\n\n\ndef get_cert_fingerprint(cert_filename):\n openssl = subprocess.Popen(('openssl', 'x509', '-in', cert_filename,\n '-fingerprint', '-sha1', '-noout'),\n stdout=subprocess.PIPE)\n (fingerprint, _) = openssl.communicate()\n return fingerprint.strip().rsplit('=', 1)[-1].replace(':', '').lower()\n\n\ndef open_pipe_fileobjs():\n pipe_r, pipe_w = os.pipe()\n return os.fdopen(pipe_r), os.fdopen(pipe_w, 'w')\n\n\ndef waitpid_in_thread(pid):\n \"\"\"\n Start a thread that calls os.waitpid on a particular PID to prevent\n zombie processes from hanging around after they have finished.\n \"\"\"\n if pid_exists(pid):\n pid_thread = threading.Thread(target=check_and_waitpid, args=(pid, 0))\n pid_thread.daemon = True\n pid_thread.start()\n\n\ndef spawn_process(func, **kwargs):\n proc = Process(target=process_wrapper, args=[func], kwargs=kwargs)\n proc.start()\n return proc\n\n\ndef process_wrapper(func, **kwargs):\n name = getattr(func, '__name__', 'unknown')\n try:\n func(**kwargs)\n except KeyboardInterrupt:\n pass\n except Exception as exc:\n traceback.print_exc()\n msg = 'Error in wrapped process \"{0}\":{1}'.format(str(name), str(exc))\n print >> sys.stderr, msg\n return\n # pylint: disable=W0212\n # os._exit is actually public\n os._exit(os.EX_OK)\n # pylint: enable=W0212\n\n\ndef pid_exists(pid):\n try:\n #Check to see if pid exists\n os.kill(pid, 0)\n return True\n except OSError as ose:\n if ose.errno == os.errno.ESRCH:\n #Pid was not found\n return False\n else:\n raise ose\n\n\ndef check_and_waitpid(pid, status):\n if pid_exists(pid):\n try:\n os.waitpid(pid, status)\n except OSError:\n pass\n","sub_path":"euca2ools/bundle/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"70805380","text":"# Copyright (c) 2015 Universidade Federal Fluminense (UFF)\n# Copyright (c) 2015 Polytechnic Institute of New York University.\n# This file is part of noWorkflow.\n# Please, consult the license terms in the LICENSE file.\n\"\"\" Commands and argument parsers for 'now' \"\"\"\nfrom __future__ import (absolute_import, print_function,\n division, unicode_literals)\n\nimport argparse\n\nfrom .command import Command\nfrom .cmd_run import Run\nfrom .cmd_debug import Debug\nfrom .cmd_list import List\nfrom .cmd_show import Show\nfrom .cmd_diff import Diff\nfrom .cmd_export import Export\nfrom .cmd_restore import Restore\nfrom .cmd_vis import Vis\n\n\ndef main():\n \"\"\" Main function \"\"\"\n parser = argparse.ArgumentParser(description=__doc__)\n subparsers = parser.add_subparsers()\n commands = [\n Run(),\n Debug(),\n List(),\n Show(),\n Diff(),\n Export(),\n Restore(),\n Vis(),\n ]\n for cmd in commands:\n cmd.create_parser(subparsers)\n\n args, _ = parser.parse_known_args()\n args.func(args)\n\n__all__ = [\n b'Command',\n b'Run',\n b'Debug',\n b'List',\n b'Show',\n b'Diff',\n b'Export',\n b'Restore',\n b'Vis',\n b'main',\n]","sub_path":"capture/noworkflow/now/cmd/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"254561429","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# -*- python -*-\nfrom __future__ import unicode_literals, print_function\n\nimport select\nimport sys\nimport pybonjour\n\n\ndef register_callback(sdRef, flags, errorCode, name, regtype, domain):\n if errorCode == pybonjour.kDNSServiceErr_NoError:\n print('Registered service:')\n print(' name =', name)\n print(' regtype =', regtype)\n print(' domain =', domain)\n\n\ndef main(argv):\n name = argv[1]\n regtype = argv[2]\n port = int(argv[3])\n\n with pybonjour.DNSServiceRegister(\n name=name, regtype=regtype, port=port,\n callBack=register_callback) as sdRef:\n\n try:\n while True:\n ready = select.select([sdRef], [], [])\n if sdRef in ready[0]:\n pybonjour.DNSServiceProcessResult(sdRef)\n except KeyboardInterrupt:\n pass\n\n\nif __name__ == '__main__':\n main(sys.argv)\n","sub_path":"examples/register.py","file_name":"register.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"52282552","text":"import input.data\nglobal rankdata\n\ncores = 8\nrankdata = input.data.stuff[cores]\n\n\nComponent( \"BGQ-core\" )\nProgram( \"BGQ-core\", \"lulesh.smc\" )\n\nProperty( \"BGQ-core\", \"app.elementsize\", lambda gid, cid, cids, index: 10 )\nProperty( \"BGQ-core\", \"app.procsperplane\", lambda gid, cid, cids, index: 2 )\nProperty( \"BGQ-core\", \"mpi.commsize\", lambda gid, cid, cids, index: cids)\nProperty( \"BGQ-core\", \"mpi.commRank\", lambda gid, cid, cids, index: cid )\ndef rowmin(g, rank, c, i): return rankdata[rank][\"rowmin\"]\ndef rowmax(g, rank, c, i): return rankdata[rank][\"rowmax\"]\ndef colmin(g, rank, c, i): return rankdata[rank][\"colmin\"]\ndef colmax(g, rank, c, i): return rankdata[rank][\"colmax\"]\ndef planemin(g, rank, c, i): return rankdata[rank][\"planemin\"]\ndef planemax(g, rank, c, i): return rankdata[rank][\"planemax\"]\ndef Zminus(g, rank, c, i): return rankdata[rank][\"Zminus\"]\ndef Zplus(g, rank, c, i): return rankdata[rank][\"Zplus\"]\ndef Yminus(g, rank, c, i): return rankdata[rank][\"Yminus\"]\ndef Yplus(g,rank, c, i): return rankdata[rank][\"Yplus\"]\ndef Xminus(g, rank, c, i): return rankdata[rank][\"Xminus\"]\ndef Xplus(g, rank, c, i): return rankdata[rank][\"Xplus\"]\nProperty( \"BGQ-core\", \"mpi.rowMin\", rowmin )\nProperty( \"BGQ-core\", \"mpi.rowMax\", rowmax )\nProperty( \"BGQ-core\", \"mpi.colMin\", colmin )\nProperty( \"BGQ-core\", \"mpi.colMax\", colmax )\nProperty( \"BGQ-core\", \"mpi.planeMin\", planemin )\nProperty( \"BGQ-core\", \"mpi.planeMax\", planemax )\nProperty( \"BGQ-core\", \"mpi.cartesianZminus\", Zminus )\nProperty( \"BGQ-core\", \"mpi.cartesianZplus\", Zplus )\nProperty( \"BGQ-core\", \"mpi.cartesianYminus\", Yminus )\nProperty( \"BGQ-core\", \"mpi.cartesianYplus\", Yplus )\nProperty( \"BGQ-core\", \"mpi.cartesianXminus\", Xminus )\nProperty( \"BGQ-core\", \"mpi.cartesianXplus\", Xplus )\nAttribute( \"BGQ-core\", \"usage\", 0.0 )\nAttribute( \"BGQ-core\", \"waiting\", False )\nRelation(\"BGQ-core\", \"BGQ-core\", \"cpu\", \"self\")\n#Operation( \"BGQ-core\", \"wait\", NoLookup,\n # Modify( \"waiting\", True ) )\n# Operation( \"BGQ-core\", \"unwait\", NoLookup,\n # Modify( \"waiting\", False ))\nOperation( \"BGQ-core\", \"Compute1\", \"Vulcan-Compute1.csv\",\n Loiter( \"usage\", \"==\", 0.0),\n Modify( \"usage\", 1.0 ),\n Dawdle( AnyOutput() ),\n Modify( \"usage\", 0.0 ) )\nOperation( \"BGQ-core\", \"CalcVolForce\", \"Vulcan-CalcVolForce.csv\",\n Loiter( \"usage\", \"==\", 0.0),\n Modify( \"usage\", 1.0 ),\n Dawdle( AnyOutput() ),\n Modify( \"usage\", 0.0 ) )\t\t \nOperation( \"BGQ-core\", \"CalcAcceleration\", \"Vulcan-CalcAcceleration.csv\",\n Loiter( \"usage\", \"==\", 0.0),\n Modify( \"usage\", 1.0 ),\n Dawdle( AnyOutput() ),\n Modify( \"usage\", 0.0 ) )\nOperation( \"BGQ-core\", \"ApplyAccBdyCond\", \"Vulcan-ApplyAccBdyCond.csv\",\n Loiter( \"usage\", \"==\", 0.0),\n Modify( \"usage\", 1.0 ),\n Dawdle( AnyOutput() ),\n Modify( \"usage\", 0.0 ) )\nOperation( \"BGQ-core\", \"CalcVelocity\", \"Vulcan-CalcVelocity.csv\",\n Loiter( \"usage\", \"==\", 0.0),\n Modify( \"usage\", 1.0 ),\n Dawdle( AnyOutput() ),\n Modify( \"usage\", 0.0 ) )\nOperation( \"BGQ-core\", \"CalcPosition\", \"Vulcan-CalcPosition.csv\",\n Loiter( \"usage\", \"==\", 0.0),\n Modify( \"usage\", 1.0 ),\n Dawdle( AnyOutput() ),\n Modify( \"usage\", 0.0 ) )\nOperation( \"BGQ-core\", \"CalcKinematics\", \"Vulcan-CalcKinematics.csv\",\n Loiter( \"usage\", \"==\", 0.0),\n Modify( \"usage\", 1.0 ),\n Dawdle( AnyOutput() ),\n Modify( \"usage\", 0.0 ) )\nOperation( \"BGQ-core\", \"Compute6\", \"Vulcan-Compute6.csv\",\n Loiter( \"usage\", \"==\", 0.0),\n Modify( \"usage\", 1.0 ),\n Dawdle( AnyOutput() ),\n Modify( \"usage\", 0.0 ) )\nOperation( \"BGQ-core\", \"CalcMQ\", \"Vulcan-CalcMQ.csv\",\n Loiter( \"usage\", \"==\", 0.0),\n Modify( \"usage\", 1.0 ),\n Dawdle( AnyOutput() ),\n Modify( \"usage\", 0.0 ) )\nOperation( \"BGQ-core\", \"CalcMQGradients\", \"Vulcan-CalcMQGradients.csv\",\n Loiter( \"usage\", \"==\", 0.0),\n Modify( \"usage\", 1.0 ),\n Dawdle( AnyOutput() ),\n Modify( \"usage\", 0.0 ) )\nOperation( \"BGQ-core\", \"Compute7\", \"Vulcan-Compute7.csv\",\n Loiter( \"usage\", \"==\", 0.0),\n Modify( \"usage\", 1.0 ),\n Dawdle( AnyOutput() ),\n Modify( \"usage\", 0.0 ) )\nOperation( \"BGQ-core\", \"ApplyMaterialProperties\", \"Vulcan-ApplyMaterialProperties.csv\",\n Loiter( \"usage\", \"==\", 0.0),\n Modify( \"usage\", 1.0 ),\n Dawdle( AnyOutput() ),\n Modify( \"usage\", 0.0 ) )\nOperation( \"BGQ-core\", \"UpdateVolumes\", \"Vulcan-UpdateVolumes.csv\",\n Loiter( \"usage\", \"==\", 0.0),\n Modify( \"usage\", 1.0 ),\n Dawdle( AnyOutput() ),\n Modify( \"usage\", 0.0 ) )\nOperation( \"BGQ-core\", \"CalcTimeConstraints\", \"Vulcan-CalcTimeConstraints.csv\",\n Loiter( \"usage\", \"==\", 0.0),\n Modify( \"usage\", 1.0 ),\n Dawdle( AnyOutput() ),\n Modify( \"usage\", 0.0 ) )\n\nOperation( \"BGQ-core\", \"wait\", NoLookup,\n Modify( \"waiting\", True ),\n Loiter( \"waiting\", \"==\", False ) )\n\nOperation( \"BGQ-core\", \"unwait\", NoLookup,\n Loiter( \"waiting\", \"==\", True ),\n Modify( \"waiting\", False ))\n\nOrdinal(\"BGQ-core\",\"mpi.commRank\")\t\t \nComponent( \"BGQ-network\" )\nAttribute( \"BGQ-network\", \"usage\", 0.0 )\nOperation( \"BGQ-network\", \"transfer\", \"HiPGator2-TT-hack.csv\",\n Loiter( \"usage\", \"==\", 0.0 ),\n Modify( \"usage\", 1.0 ),\n Dawdle( AnyOutput() ),\n Modify( \"usage\", 0.0 ) )\nMailbox( \"BGQ-network\", \"transfer\", lambda source, target, size, tag: [size],\n OnAll )\nMailbox( \"BGQ-core\", \"unwait\", lambda source, target, size, tag: [],\n OnTarget )\nComponent( \"BGQ-connection\" )\nComponent( \"system\" )\nOffspring( \"system\", Tree( [\"BGQ-network\", \"BGQ-core\"], [\"BGQ-connection\"],\n [ 8 ] ) )\nRoot(\"system\")\n\n","sub_path":"apps/miniapps/lulesh/lulesh_v1.0/lulesh.py","file_name":"lulesh.py","file_ext":"py","file_size_in_byte":5966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"409227979","text":"import os\nimport os.path as osp\nimport shutil as sh\nimport random\n\n\nbase_path = '20190725'\nselec_num = 40\n\nIds = []\nfor fold in os.listdir(base_path):\n folder = osp.join(base_path, fold)\n if osp.isdir(folder):\n Ids.append(folder)\n\ndel_ids = random.sample(range(len(Ids)), len(Ids)-selec_num)\nfor i in del_ids:\n print(Ids[i])\n sh.rmtree(Ids[i])\n","sub_path":"datasets/FaceID/random_selec.py","file_name":"random_selec.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"53015895","text":"# -*- coding: utf-8 -*-\nfrom odoo import models, fields, api, _\nfrom odoo.exceptions import UserError\nfrom odoo.tools.float_utils import float_compare\n\n\nclass GoodsContainer(models.Model):\n _name = 'goods.container'\n _inherit = ['mail.thread', 'mail.activity.mixin']\n\n name = fields.Char()\n\n\nclass GoodsTransit(models.Model):\n _name = 'goods.transit'\n _inherit = ['mail.thread', 'mail.activity.mixin']\n\n name = fields.Char()\n partner_id = fields.Many2one('res.partner', 'Vendor')\n location_id = fields.Many2one('stock.location', 'Location')\n po_line_ids = fields.One2many('goods.transit.line', 'goods_transit_id')\n\n @api.onchange('partner_id')\n def onchange_partner_id(self):\n domain = [('id', 'in', self.partner_id.location_ids.ids)]\n return {'domain': {'location_id': domain}}\n\n def action_stock_move(self):\n purchase_order_obj = self.po_line_ids.mapped('po_line_id.order_id')\n destination_location_obj = self.po_line_ids.mapped('destination_location_id')\n move_lst = []\n res = []\n for purchase in purchase_order_obj:\n print(\"purchase\", purchase)\n for destination in destination_location_obj:\n print(\"destination\", destination)\n for gnt in self.po_line_ids:\n if gnt.po_line_id.order_id.id == purchase.id \\\n and gnt.destination_location_id.id == destination.id:\n print(\"GNT:::::::::::\", gnt)\n values = {\n 'partner_id': gnt.partner_id.id,\n 'product_id': gnt.po_line_id.product_id.id,\n 'purchase_line_id': gnt.po_line_id.id,\n 'product_uom': gnt.po_line_id.product_uom.id,\n 'product_uom_qty': gnt.po_line_id.product_qty,\n 'name': gnt.po_line_id.name,\n 'location_id': gnt.location_id.id,\n 'location_dest_id': gnt.destination_location_id.id,\n 'origin': gnt.po_line_id.order_id.name,\n 'picking_type_id': gnt.po_line_id.order_id.picking_type_id.id,\n }\n\n\n if gnt.po_line_id.product_id.type not in ['product', 'consu']:\n print(\"nooooooooooooooooooooooooooooooooo\")\n return res\n qty = 0.0\n price_unit = gnt.po_line_id._get_stock_move_price_unit()\n for move in gnt.po_line_id.move_ids.filtered(\n lambda x: x.state != 'cancel' and not x.location_dest_id.usage == \"supplier\"):\n qty += move.product_uom._compute_quantity(gnt.received_qty, gnt.po_line_id.product_uom,\n rounding_method='HALF-UP')\n\n values = {\n # truncate to 2000 to avoid triggering index limit error\n # TODO: remove index in master?\n 'name': (gnt.po_line_id.name or '')[:2000],\n 'product_id': gnt.po_line_id.product_id.id,\n 'product_uom': gnt.po_line_id.product_uom.id,\n 'date': gnt.po_line_id.order_id.date_order,\n 'date_expected': gnt.po_line_id.date_planned,\n 'location_id': gnt.location_id.id,\n 'location_dest_id': gnt.destination_location_id.id,\n 'product_uom_qty': gnt.received_qty,\n 'picking_id': False,\n 'partner_id': gnt.partner_id.id,\n 'move_dest_ids': [(4, x) for x in gnt.po_line_id.move_dest_ids.ids],\n 'state': 'draft',\n 'purchase_line_id': gnt.po_line_id.id,\n 'company_id': gnt.po_line_id.order_id.company_id.id,\n 'price_unit': price_unit,\n 'picking_type_id': gnt.po_line_id.order_id.picking_type_id.id,\n 'group_id': gnt.po_line_id.order_id.group_id.id,\n 'origin': gnt.po_line_id.order_id.name,\n 'propagate_date': gnt.po_line_id.propagate_date,\n 'propagate_date_minimum_delta': gnt.po_line_id.propagate_date_minimum_delta,\n 'description_picking': gnt.po_line_id.product_id._get_description(gnt.po_line_id.order_id.picking_type_id),\n 'propagate_cancel': gnt.po_line_id.propagate_cancel,\n 'route_ids': gnt.po_line_id.order_id.picking_type_id.warehouse_id and [\n (6, 0, [x.id for x in gnt.po_line_id.order_id.picking_type_id.warehouse_id.route_ids])] or [],\n 'warehouse_id': gnt.po_line_id.order_id.picking_type_id.warehouse_id.id,\n }\n diff_quantity = gnt.po_line_id.product_qty - qty\n if float_compare(diff_quantity, 0.0, precision_rounding=gnt.po_line_id.product_uom.rounding) > 0:\n po_line_uom = gnt.po_line_id.product_uom\n quant_uom = gnt.po_line_id.product_id.uom_id\n product_uom_qty, product_uom = po_line_uom._adjust_uom_quantities(diff_quantity, quant_uom)\n values['product_uom_qty'] = gnt.received_qty\n values['product_uom'] = product_uom.id\n res.append(values)\n move_lst.append(values)\n print(\">>>>>>>>>>>>>>>>>>>>\", res)\n print(move_lst)\n if move_lst:\n stock = self.env['stock.picking']\n stock_move_obj = self.env['stock.move']\n stock_obj = stock.create({\n 'partner_id': move_lst[0]['partner_id'],\n 'picking_type_id': move_lst[0]['picking_type_id'],\n 'goods_in_transit_id': self.id,\n 'location_id': move_lst[0]['location_id'],\n 'location_dest_id': move_lst[0]['location_dest_id'],\n 'origin': move_lst[0]['origin'],\n })\n print(\"SSSSSSSSSSSSS\", stock_obj)\n for move in move_lst:\n print(\"moveeeeeeeeeeeeeeeeeeeeeee\", move)\n move['picking_id'] = stock_obj.id\n print(\"move edit\", move)\n stock_move_obj.create(move)._action_confirm()._action_assign()\n # {\n # 'picking_id': stock_obj.id,\n # 'product_id': move['product_id'],\n # 'purchase_line_id': move['purchase_line_id'],\n # 'product_uom': move['product_uom'],\n # 'location_id': move['location_id'],\n # 'location_dest_id': move['location_dest_id'],\n # 'product_uom_qty': move['product_uom_qty'],\n # 'name': move['name'],\n # })\n move_lst.clear()\n\n def get_stock_moves_related_to_gnt(self):\n return {\n 'type': 'ir.actions.act_window',\n 'name': 'All Transfers',\n 'res_model': 'stock.picking',\n 'view_type': 'form',\n 'view_mode': 'tree,form',\n 'domain': [('goods_in_transit_id', '=', self.id)],\n 'target': 'current',\n }\n\n\nclass CustodyRequestLine(models.Model):\n _name = 'goods.transit.line'\n _inherit = ['mail.thread', 'mail.activity.mixin']\n\n def get_partner_related_locations(self):\n for record in self:\n if record.partner_id and record.location_id:\n domain = [('partner_id.id', '=', record.partner_id.id),\n ('location_id.id', '=', record.location_id.id),\n ('qty_remaining', '>', 0.0),\n ('id', 'not in', self.goods_transit_id.po_line_ids.mapped('po_line_id').ids)\n ]\n return domain\n\n goods_transit_id = fields.Many2one('goods.transit')\n po_line_id = fields.Many2one('purchase.order.line',\n domain=get_partner_related_locations,\n string='purchase order line')\n purchase_order_id = fields.Many2one('purchase.order',\n related='po_line_id.order_id',\n string='purchase order')\n partner_id = fields.Many2one('res.partner', 'Vendor',)\n location_id = fields.Many2one('stock.location', 'source Location')\n destination_location_id = fields.Many2one('stock.location', 'Destination Location')\n remaining_qty = fields.Float(related='po_line_id.qty_remaining')\n received_qty = fields.Float()\n container_id = fields.Many2one('goods.container')\n\n @api.onchange('partner_id', 'location_id')\n def onchange_partner_id(self):\n domain = [('partner_id.id', '=', self.partner_id.id),\n ('location_id.id', '=', self.location_id.id),\n ('qty_remaining', '>', 0.0),\n ('id', 'not in', self.goods_transit_id.po_line_ids.mapped('po_line_id').ids),\n ]\n return {'domain': {'po_line_id': domain}}\n\n\nclass PurchaseOrderLine(models.Model):\n _inherit = 'purchase.order.line'\n\n def get_partner_related_locations(self):\n domain = [('id', 'in', self.partner_id.location_ids.ids if self.partner_id else self.order_id.partner_id.location_ids.ids)]\n return domain\n\n qty_remaining = fields.Float(compute=\"compute_qty_remaining\", store=True)\n goods_transit_id = fields.Many2one('goods.transit')\n location_id = fields.Many2one('stock.location', 'Location', domain=get_partner_related_locations)\n\n @api.onchange('partner_id', 'location_id')\n def onchange_partner_id(self):\n domain = [('id', 'in', self.partner_id.location_ids.ids)]\n return {'domain': {'location_id': domain}}\n\n @api.depends('product_qty', 'qty_received')\n def compute_qty_remaining(self):\n for record in self:\n record.qty_remaining = record.product_qty - record.qty_received\n\n # def _prepare_stock_moves(self, picking):\n # \"\"\" Prepare the stock moves data for one order line. This function returns a list of\n # dictionary ready to be used in stock.move's create()\n # \"\"\"\n # print(\"moveeeeeeeeeeeeeeeeeeee\")\n # self.ensure_one()\n # res = []\n # if self.product_id.type not in ['product', 'consu']:\n # return res\n # qty = 0.0\n # price_unit = self._get_stock_move_price_unit()\n # for move in self.move_ids.filtered(lambda x: x.state != 'cancel' and not x.location_dest_id.usage == \"supplier\"):\n # qty += move.product_uom._compute_quantity(move.product_uom_qty, self.product_uom, rounding_method='HALF-UP')\n # template = {\n # # truncate to 2000 to avoid triggering index limit error\n # # TODO: remove index in master?\n # 'name': (self.name or '')[:2000],\n # 'product_id': self.product_id.id,\n # 'product_uom': self.product_uom.id,\n # 'date': self.order_id.date_order,\n # 'date_expected': self.date_planned,\n # 'location_id': self.order_id.partner_id.property_stock_supplier.id,\n # 'location_dest_id': self.order_id._get_destination_location(),\n # 'picking_id': picking.id,\n # 'partner_id': self.order_id.dest_address_id.id,\n # 'move_dest_ids': [(4, x) for x in self.move_dest_ids.ids],\n # 'state': 'draft',\n # 'purchase_line_id': self.id,\n # 'company_id': self.order_id.company_id.id,\n # 'price_unit': price_unit,\n # 'picking_type_id': self.order_id.picking_type_id.id,\n # 'group_id': self.order_id.group_id.id,\n # 'origin': self.order_id.name,\n # 'propagate_date': self.propagate_date,\n # 'propagate_date_minimum_delta': self.propagate_date_minimum_delta,\n # 'description_picking': self.product_id._get_description(self.order_id.picking_type_id),\n # 'propagate_cancel': self.propagate_cancel,\n # 'route_ids': self.order_id.picking_type_id.warehouse_id and [(6, 0, [x.id for x in self.order_id.picking_type_id.warehouse_id.route_ids])] or [],\n # 'warehouse_id': self.order_id.picking_type_id.warehouse_id.id,\n # }\n # diff_quantity = self.product_qty - qty\n # if float_compare(diff_quantity, 0.0, precision_rounding=self.product_uom.rounding) > 0:\n # po_line_uom = self.product_uom\n # quant_uom = self.product_id.uom_id\n # product_uom_qty, product_uom = po_line_uom._adjust_uom_quantities(diff_quantity, quant_uom)\n # template['product_uom_qty'] = product_uom_qty\n # template['product_uom'] = product_uom.id\n # res.append(template)\n # return res\n #\n # def _create_or_update_picking(self):\n # print(\"OOOOOOOOOOOOOOOOOOOOOOOOOOO\")\n # for line in self:\n # if line.product_id and line.product_id.type in ('product', 'consu'):\n # # Prevent decreasing below received quantity\n # if float_compare(line.product_qty, line.qty_received, line.product_uom.rounding) < 0:\n # raise UserError(_('You cannot decrease the ordered quantity below the received quantity.\\n'\n # 'Create a return first.'))\n #\n # if float_compare(line.product_qty, line.qty_invoiced, line.product_uom.rounding) == -1:\n # # If the quantity is now below the invoiced quantity, create an activity on the vendor bill\n # # inviting the user to create a refund.\n # activity = self.env['mail.activity'].sudo().create({\n # 'activity_type_id': self.env.ref('mail.mail_activity_data_warning').id,\n # 'note': _('The quantities on your purchase order indicate less than billed. You should ask for a refund. '),\n # 'res_id': line.invoice_lines[0].invoice_id.id,\n # 'res_model_id': self.env.ref('account.model_account_move').id,\n # })\n # activity._onchange_activity_type_id()\n #\n # # If the user increased quantity of existing line or created a new line\n # pickings = line.order_id.picking_ids.filtered(lambda x: x.state not in ('done', 'cancel') and x.location_dest_id.usage in ('internal', 'transit'))\n # picking = pickings and pickings[0] or False\n # if not picking:\n # res = line.order_id._prepare_picking()\n # picking = self.env['stock.picking'].create(res)\n # move_vals = line._prepare_stock_moves(picking)\n # for move_val in move_vals:\n # self.env['stock.move']\\\n # .create(move_val)\\\n # ._action_confirm()\\\n # ._action_assign()\n\n\nclass ResPartner(models.Model):\n _inherit = 'res.partner'\n location_id = fields.Many2one('stock.location', 'Location')\n location_ids = fields.Many2many('stock.location', store=True)\n\n\nclass StockPicking(models.Model):\n _inherit = 'stock.picking'\n goods_in_transit_id = fields.Many2one('goods.transit')\n\n\nclass PurchaseOrder(models.Model):\n _inherit = 'purchase.order'\n\n def button_approve(self, force=False):\n print(\"approve\")\n self.write({'state': 'purchase', 'date_approve': fields.Date.context_today(self)})\n self.filtered(lambda p: p.company_id.po_lock == 'lock').write({'state': 'done'})\n return {}\n\n def button_confirm(self):\n for order in self:\n if order.state not in ['draft', 'sent']:\n continue\n print(order)\n print(order._add_supplier_to_product)\n order._add_supplier_to_product()\n # Deal with double validation process\n if order.company_id.po_double_validation == 'one_step' \\\n or (order.company_id.po_double_validation == 'two_step' \\\n and order.amount_total < self.env.company.currency_id._convert(\n order.company_id.po_double_validation_amount, order.currency_id, order.company_id,\n order.date_order or fields.Date.today())) \\\n or order.user_has_groups('purchase.group_purchase_manager'):\n order.button_approve()\n print(order.button_approve())\n else:\n order.write({'state': 'to approve'})\n return True\n","sub_path":"goods_in_transit/models/goods_transit.py","file_name":"goods_transit.py","file_ext":"py","file_size_in_byte":17308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"331527426","text":"\nfrom assign2_support import *\nimport tkinter as tk\nimport os.path\nfrom tkinter import filedialog\nfrom tkinter import messagebox\n\n\nclass TemperatureData(object):\n \"\"\"Class for holding the temperature data for each loaded station.\"\"\"\n \n def __init__(self):\n \"\"\"Initialises the internal data.\n\n Constructor: TemperatureData()\n \"\"\"\n \n self._data_dict = {}\n self._station_names = []\n self._flags = []\n \n def load_data(self, filename):\n \"\"\"Loads instances of the Station class.\n\n TemperatureData.load_data() -> None\n \"\"\"\n \n self._station_names.append(Station(filename).get_name())\n self._data_dict[Station(filename).get_name()] = Station(filename)\n self._flags.append(True)\n \n def get_data(self):\n \"\"\"Returns a dictionary of each loaded station.\n\n TemperatureData.get_data() -> dict(str : Station(filename))\n \"\"\"\n \n return self._data_dict\n \n def get_stations(self):\n \"\"\"Returns an ordered list of loaded station names\n\n TemperatureData.get_stations() -> list(str)\n \"\"\"\n \n return self._station_names\n \n def toggle_selected(self, i):\n \"\"\"Toggles the flag for displaying the station at index i.\n\n TemperatureData.toggle_selected(i) -> None\n \"\"\"\n \n self._flags[i] = not self._flags[i]\n\n def is_selected(self, i):\n \"\"\"Returns a boolean used to determine if the data for the station at\n index i is to be displayed.\n\n TemperatureData.is_selected(i) -> Boolean\n \"\"\"\n \n return self._flags[i]\n\n def get_ranges(self):\n \"\"\"Returns a 4-tuple of the form (min_year, max_year, min_temp, max_temp).\n\n TemperatureData.get_ranges() -> tuple(int, int, int, int)\n \"\"\"\n \n dates = []\n temps = []\n data = []\n \n for station in self._station_names:\n data = self._data_dict[station].get_data_points()\n \n for i in data:\n dates.append(i[0])\n temps.append(i[1])\n \n return (min(dates), max(dates), min(temps), max(temps))\n\n\nclass Plotter(tk.Canvas):\n \"\"\"A class that handles the plotting of Temperature data\"\"\"\n \n def __init__(self, parent, tempdata):\n \"\"\"Initialises the Plotter\n\n Constructor: Plotter(tk.Canvas, TemperatureData())\n \"\"\"\n \n super().__init__(parent, width=800, height=300)\n \n self._tempdata = tempdata\n \n self.bind(\"\", self.draw_templine, add=\"+\")\n self.bind(\"\", self.draw_templine, add=\"+\")\n \n self._line = None\n self._line_coords = None\n \n def draw_templine(self, click):\n \"\"\"Draws a vertical line, upon mouse event, at cursor position\n\n Plotter.draw_templline(Event)\"\"\"\n\n # Ensures at least one data object is loaded\n if len(self._tempdata.get_stations())==0:\n return None\n else:\n ct = CoordinateTranslator(self.winfo_width(), self.winfo_height(), *self._tempdata.get_ranges())\n if self._line is not None:\n self.delete(self._line)\n self.delete(self._line_coords)\n self._line = None\n \n if 0 <= click.x < self.winfo_width():\n self._line_coords = [(click.x, 0), (click.x, self.winfo_height())]\n self._line = self.create_line(self._line_coords)\n \n def redraw(self):\n \"\"\"Remove all plotted lines and redraws them with updated parameters.\n\n Plotter.redraw() -> None\n \"\"\"\n \n ct = CoordinateTranslator(self.winfo_width(), self.winfo_height(), *self._tempdata.get_ranges())\n ct.resize(self.winfo_width(), self.winfo_height())\n self.delete(tk.ALL)\n\n # NOTE: Vertical line doesn't change upon resize. To delete line on resize, delete above 2 lines\n if self._line is not None:\n self._line = self.create_line(self._line_coords)\n \n for i in self._tempdata.get_stations():\n index = self._tempdata.get_stations().index(i)\n \n if self._tempdata.is_selected(index):\n colour = COLOURS[index]\n coords=[]\n \n for year,temp in self._tempdata.get_data()[i].get_data_points():\n coords.append(ct.temperature_coords(year,temp))\n \n self.create_line(coords, fill=colour)\n \n\nclass SelectionFrame(tk.Frame):\n \"\"\"A widget used for selecting which stations data is to\n be displayed.\n \"\"\"\n\n def __init__(self, parent, tempdata, plotter, dataframe):\n \"\"\"Initialises the SelectionFrame\n\n Constructor: SelectionFrame(tk.Frame, TemperatureData, Plotter, DataFrame)\n \"\"\"\n \n super().__init__(parent)\n\n self._tempdata = tempdata\n self._plotter = plotter\n self._data_frame = dataframe\n \n self._stations = self._tempdata.get_stations()\n self._sel_lbl= tk.Label(self, text = \"Station Selection:\")\n self._sel_lbl.pack(side=tk.LEFT)\n\n self._check_but = tk.Checkbutton(self, fg=\"red\")\n\n def create_button(self,i):\n \"\"\"Creates check button for a given station at index i\n\n SelectionFrame.create_button(i) -> None\n \"\"\"\n \n colour = COLOURS[i]\n self._check_but = tk.Checkbutton(self, fg=colour, text=self._stations[i],\n command = lambda: self.check(i))\n self._check_but.select()\n self._check_but.pack(side=tk.LEFT)\n\n def check(self,i):\n \"\"\"Command function for all station checkbuttons. Upon toggling the check button,\n the following is exectued.\n\n SelectionFrame.check(i) -> None\n \"\"\"\n \n self._tempdata.toggle_selected(i)\n self._plotter.redraw()\n self._data_frame.toggle_label(i)\n\n\nclass DataFrame(tk.Frame):\n \"\"\" A widget used for displaying the temperatures for a\n chosen year for each selected station.\n \"\"\"\n \n def __init__(self, parent, tempdata, plotter):\n \"\"\"Initialises the DataFrame\n\n Constuctor: DataFrame(tk.Frame, TemperatureData, Plotter)\n \"\"\"\n \n super().__init__(parent)\n \n self._tempdata = tempdata\n self._plotter = plotter\n \n self._plotter.bind(\"\", self.update, add=\"+\")\n self._plotter.bind(\"\", self.update, add=\"+\")\n \n self._lbl_list = []\n\n self._temp = None\n\n def update(self, click):\n \"\"\"Updates various label parameters based on user mouse events.\n\n DataFrame.update() -> None\n \"\"\"\n \n if len(self._tempdata.get_stations())==0:\n return \"\"\n else:\n self._ct = CoordinateTranslator(self._plotter.winfo_width(), self._plotter.winfo_height(), *self._tempdata.get_ranges())\n year = self._ct.get_year(click.x)\n station_names = self._tempdata.get_stations()\n \n #[0] element will always be title\n self._lbl_list[0].config(text=\"Data for {}:\".format(year)) \n \n for i,station_lbl in enumerate(self._lbl_list[1:]):\n self._temp = self._tempdata.get_data()[station_names[i]].get_temp(year)\n \n if self._temp == None:\n station_lbl.config(text = \" \")\n \n elif self._tempdata.is_selected(i):\n station_lbl.config(text = \"{}\".format(self._temp))\n \n else:\n station_lbl.config(text = \" \")\n \n def create_label(self, i):\n \"\"\"Creates label for a given station at index i that displays temperature data based on user mouse events.\n If no mouse event, or a station is deselected, an empty string is displayed.\n\n DataFrame.create_label(i) -> None\n \"\"\"\n \n colour = COLOURS[i]\n \n if len(self._lbl_list)==0:\n main_lbl = tk.Label(text=\"\")\n main_lbl.pack(side=tk.LEFT)\n \n station_lbl = tk.Label(text=\"\", fg=colour)\n station_lbl.pack(side=tk.LEFT, padx = (15, 20))\n\n self._lbl_list.append(main_lbl)\n self._lbl_list.append(station_lbl)\n else:\n station_lbl = tk.Label(text=\"\", fg=colour)\n station_lbl.pack(side=tk.LEFT, padx = 15) \n self._lbl_list.append(station_lbl)\n \n def toggle_label(self, i):\n \"\"\"Hides/shows label for station at index i if it is selected.\n\n DataFrame.hide_label(i) -> None\n \"\"\"\n \n if self._tempdata.is_selected(i):\n self._lbl_list[i+1].config(text = self._temp)\n else:\n self._lbl_list[i+1].config(text = \" \")\n\n\nclass TemperaturePlotApp(object):\n \"\"\"The Top-level class for the GUI.\"\"\"\n \n def __init__(self, master):\n \"\"\"Initialises TemperaturePlotApp.\n\n Constuctor: TemperaturePlotApp()\n \"\"\"\n \n self._master = master \n master.title(\"Max Temperature Plotter\")\n \n self._tempdata = TemperatureData()\n self._plotter = Plotter(master, self._tempdata)\n self._data_frame = DataFrame(master, self._tempdata, self._plotter)\n self._selection_frame = SelectionFrame(master, self._tempdata, self._plotter, self._data_frame)\n \n self._plotter.pack(expand=True, fill=tk.BOTH)\n self._data_frame.pack(side=tk.BOTTOM, fill=tk.X)\n self._selection_frame.pack(side=tk.BOTTOM, fill=tk.X)\n \n menubar = tk.Menu(master)\n master.config(menu=menubar)\n \n filemenu = tk.Menu(menubar)\n menubar.add_cascade(label=\"File\", menu=filemenu)\n filemenu.add_command(label=\"Open\", command=self.open_file)\n \n def open_file(self):\n \"\"\"Attempts to exectute necessary steps in order to load a file based on user selection\n\n TemperaturePlotApp.open_file() -> None\n \"\"\"\n \n try:\n fd = os.path.basename(tk.filedialog.askopenfilename(filetypes = ((\"Text file\", \"*.txt\"),\n (\"All files\", \"*.*\")))) #of form 'name.txt'\n if fd:\n self._tempdata.load_data(fd)\n file_index = self._tempdata.get_stations().index(fd[:-4])\n \n self._plotter.redraw()\n\n self._selection_frame.create_button(file_index)\n self._data_frame.create_label(file_index)\n self._data_frame.toggle_label(file_index)\n\n self._plotter.bind('', lambda x: self._plotter.redraw())\n \n except Exception:\n tk.messagebox.showerror(\"File Error\", \"%s is not a suitable data file.\" % open_file)\n pass\n \n def exit(self):\n \"\"\"Close the application.\n\n TemperaturePlotApp.exit() -> None\n\n \"\"\"\n self._master.destroy()\n \ndef main():\n root = tk.Tk()\n app = TemperaturePlotApp(root)\n root.geometry(\"800x400\")\n root.mainloop()\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":11485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"636582259","text":"import requests\n\n\nclass Endpoint:\n endpoint = NotImplemented\n data = None\n meta = None\n raw_response = None\n headers = {\n 'Content-Type': 'application/json'\n }\n context = {}\n\n def get(self, params=None):\n if params is None:\n params = {}\n params['yavin_secret'] = self.context['yavin_secret']\n return self._process_response(requests.get(self.context['url'], params, headers=self.headers))\n\n def _process_response(self, response):\n self.raw_response = response\n try:\n response.raise_for_status()\n self.data = response.json()['data'][self.endpoint]\n self.meta = response.json()['meta']\n except Exception as e:\n try:\n print(\"Error {} : {} at url : {}\".format(\n response.json()['meta']['code'],\n response.json()['meta']['message'],\n self.context['url']\n ))\n except:\n print(e)\n\n return self.data\n\n\nclass TransactionsEndpoint(Endpoint):\n endpoint = 'transactions'\n\n def __init__(self, client):\n self.context.update(client.context)\n self.context['endpoint'] = self.endpoint\n self.context['url'] = '/'.join([self.context['api_url'], self.context['version'], self.endpoint])\n","sub_path":"yavin/transactions.py","file_name":"transactions.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"142901426","text":"'''\nSome simple common functions\nAuthors: T.M.Perry, A.Levine, M.Cepeda, E.Friis UW Madison\n'''\nimport ROOT\nfrom ROOT import TH1D,TH2D\n\ndef hist(tree,var,cuts='[(2>1)]',binning=[10,-2,-2],xaxis='',title='',cal=1.,logg=None):\n ''' make a 1D histogram '''\n draw_string = \"%s * %0.2f\" %(var,cal)\n cut = cutString(cuts)\n htemp = TH1D('htemp','htemp',binning[0],binning[1],binning[2])\n tree.Draw(draw_string+'>>htemp',cut)\n htemp.GetXaxis().SetTitle(xaxis)\n htemp.SetTitle(title)\n print(draw_string)\n print(cut)\n if logg is not None:\n logg.write('Draw String: '+draw_string+'\\n')\n logg.write('Cut String: '+cut+'\\n')\n logg.write('Binning: %s \\n\\n'%(binning)) \n return htemp \n\ndef hist2D(tree,varA,varB,selA,selB,\nbinA,binB,style='COLZ',xaxis='',yaxis='',title='',calA=1.,calB=1.,logg=None):\n ''' make a 2D histogram '''\n draw_string = \"(%s * %0.2f):(%s * %0.2f)\" % (varA,calA,varB,calB)\n cut = cutString(selA+selB)\n htemp = TH2D(\"htemp\",\"htemp\",\n binA[0],binA[1],binA[2],\n binB[0],binB[1],binB[2])\n tree.Draw(draw_string+'>>htemp',cut,style)\n htemp.GetXaxis().SetTitle(xaxis)\n htemp.GetYaxis().SetTitle(yaxis)\n htemp.SetTitle(title)\n print(draw_string)\n print(cut)\n if logg is not None:\n logg.write('Draw String: '+draw_string+'\\n')\n logg.write('Cut String: '+cut+'\\n')\n logg.write('BinA: %s \\n'%(binA)) \n logg.write('BinB: %s \\n\\n'%(binB)) \n return htemp\n\ndef cutString(cuts=['cutA','cutB']):\n ''' take an array and turn it into a cut string '''\n string = '(%s' %(cuts.pop())\n while cuts:\n string+=' && %s' %(cuts.pop())\n string+=')'\n #print(string)\n return string\n\ndef efficiency(denom, num,color=ROOT.EColor.kBlue,marker=20):\n ''' make an efficiency graph from num,denom called by efficiency '''\n eff = ROOT.TGraphAsymmErrors(num, denom)\n eff.SetMarkerStyle(marker)\n eff.SetMarkerColor(color)\n eff.SetMarkerSize(1.5)\n eff.SetLineColor(color)\n return eff\n\n\n\n\ndef eGraph(ntuple,variable,cut,binning,denom,title,leg,color,marker,logg):\n ''' called by script, define parameters for efficiency plot '''\n num = hisogram(ntuple,variable,cut,binning)\n efi = eGraph(denom,num,color,marker)\n leg.AddEntry(efi,title)\n efi.Draw('p')\n logg.write(title+'\\n')\n logg.write(ntuple.GetDirectory().GetName()+'\\n')\n logg.write('Cut: '+cut+'\\n\\n')\n return efi\n\ndef hist2Dfriend(treeA,friendB,varA,varB,selA,selB,\nbinA,binB,style='COLZ',xaxis='',yaxis='',title='',calA=1.,calB=1.,logg=None):\n ''' make a 2D histogram, trees better be friends (: '''\n frVarB = friendInsert(friendB,varB)\n draw_string = \"(%s * %0.2f):(%s * %0.2f)\" % (varA,calA,frVarB,calB)\n cutB = friendCut(friendB,selB)\n cut = cutString(selA+cutB)\n htemp = TH2D(\"htemp\",\"htemp\",\n binA[0],binA[1],binA[2],\n binB[0],binB[1],binB[2])\n treeA.Draw(draw_string+'>>htemp',cut,style)\n htemp.GetXaxis().SetTitle(xaxis)\n htemp.GetYaxis().SetTitle(yaxis)\n htemp.SetTitle(title)\n #print(draw_string)\n #print(cut)\n if logg is not None:\n logg.write('Draw String: '+draw_string+'\\n')\n logg.write('Cut String: '+cut+'\\n\\n')\n return htemp\n\ndef friendCut(friend,cuts=['cutA','cutB']):\n ''' takes ['pt>5'] and makes it [friend.pt>5] '''\n cut = []\n while cuts:\n cut.append('%s.%s'%(friend,cuts.pop()))\n #print(cut)\n return cut\n\ndef friendInsert(friend='MY',stringIn='string'):\n ''' goes through string and adds to each word\n doesn't work if you have consecutive numbers in leafname '''\n stringOut = ''\n for i,c in enumerate(stringIn):\n if i == 0 and stringIn[i].isalpha:\n stringOut+=friend+'.'\n if stringIn[i].isalpha() and not stringIn[i-1].isalnum():\n stringOut+=friend+'.'\n stringOut+=stringIn[i]\n #print stringIn\n #print stringOut\n return stringOut\n\n","sub_path":"test/plotters/simpleMaker.py","file_name":"simpleMaker.py","file_ext":"py","file_size_in_byte":3634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"494259436","text":"from flask import Flask, request, jsonify\nfrom flask_restful import Resource, Api\nfrom flask_cors import cross_origin, CORS\nimport pickle\nimport json\n\napp = Flask(__name__)\napi = Api(app)\ncors = CORS(app, resources={r'/*':{\"origins\": 'http://localhost'}})\n\ndef match(recipe, pantry):\n\ttotal = len(recipe[\"ingredients\"])\n\tavailable = 0\n\tfor ingredient in recipe[\"ingredients\"]:\n\t\tif ingredient in pantry:\n\t\t\tavailable+=1\n\treturn available/total\n\nclass Recipes(Resource):\n\tdef get(self):\n\t\targs = request.form\n\t\tcuisine_query = args[\"cuisine\"]\n\t\ttype_query = args[\"type\"] \n\t\tpantry = args.getlist(\"Ingredients\")\n\n\t\tif pantry==None:\n\t\t\tpantry = []\n\n\t\tanswers = list(recipes.keys())\n\n\t\tif cuisine_query!=\"\":\n\t\t\ttemp_answers = []\n\t\t\tfor key in answers:\n\t\t\t\tif recipes[key][\"cuisine\"]==cuisine_query:\n\t\t\t\t\ttemp_answers.append(key)\n\t\t\tanswers = temp_answers\n\n\t\tif type_query!=\"\":\n\t\t\ttemp_answers = []\n\t\t\tfor key in answers:\n\t\t\t\tif recipes[key][\"type\"]==type_query:\n\t\t\t\t\ttemp_answers.append(key)\n\t\t\tanswers = temp_answers\n\n\t\tprobability = []\n\t\tfor key in answers:\t\t\t\n\t\t\tprobability.append((match(recipes[key], pantry), key))\n\t\tprobability.sort(reverse=True)\n\t\treturn [probability, [recipes[key] for _, key in probability]]\n\nclass RecipesId(Resource):\n\tdef get(self):\n\t\targs = request.form \n\t\tid_list = args.getlist(\"id\")\n\n\t\tanswer = []\n\n\t\tfor num in id_list:\n\t\t\tanswer.append(recipes[num])\n\t\treturn answer\n\nclass getIngredients(Resource):\n\tdef get(self, match_str):\n\t\ting_types = ingredients.keys()\n\n\t\tmatch_str = match_str.lower()\n\t\tanswers = []\n\t\tfor ing in ing_types:\n\t\t\ttemp = [i for i in ingredients[ing] if match_str==i[:len(match_str)]]\n\t\t\tanswers+=temp\n\n\t\tanswers = sorted(answers, key=lambda x:x.replace(' ', ''))\n\t\treturn jsonify(sorted(answers, key=lambda x: ''.join(x.split()), reverse=True))\n\nclass getCategory(Resource):\n\tdef get(self, match_str):\n\t\ting_types = ingredients.keys()\n\n\t\tmatch_str = match_str.lower()\n\t\tanswer = \"Other\"\n\t\tfor ing in ing_types:\n\t\t\tif match_str in ingredients[ing]:\n\t\t\t\tanswer = ing\n\t\t\t\tbreak\n\t\tprint(answer)\n\t\tif answer=='Condiment':\n\t\t\tanswer = \"Herbs and Spices\"\n\t\treturn jsonify(answer)\n\n\napi.add_resource(Recipes, '/cookease/recipes/')\napi.add_resource(RecipesId, '/cookease/recipes/id/')\napi.add_resource(getIngredients, '/cookease/ingredient/')\napi.add_resource(getCategory, '/cookease/category/')\n\nclass Test(Resource):\n\tdef get(self):\n\t\treturn \"hello world\"\napi.add_resource(Test, '/')\n\nclass GetCuisines(Resource):\n\tdef get(self):\n\t\t# images are located at ui/assets/images/cuisines/file_name.jpg\n\t\treturn jsonify({\n\t\t\t\"Mexican\":\"Mexican.jpg\",\n\t\t\t\"Italian\":\"Italian.jpg\",\n\t\t\t\"Indian\":\"Indian.jpg\",\n\t\t\t\"Thai\":\"Thai.jpg\"\n\t\t}\n\t\t)\napi.add_resource(GetCuisines, '/get_cuisines')\n\nif __name__ == '__main__':\n\twith open(\"../data/categorical_ingredients\", \"rb\") as file:\n\t\tingredients = pickle.load(file)\n\twith open(\"../data/id_recipes.pkl\", \"rb\") as file:\n\t\trecipes = pickle.load(file)\n\tapp.run(debug=True)\n","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"186914740","text":"import re\nimport collections\nfrom collections import Counter\nimport jieba\n \n\ndef stats_text_cn(text):\n cut_list = []\n cut_list = []\n word_list = []\n count_list = []\n\n cn_pattern = re.compile(r'[\\u4e00-\\u9fa5]')\n text_cn = re.findall(cn_pattern,text)\n text_cut = ''.join(text_cn)\n cut_list = jieba.cut(text_cut,cut_all=False) \n\n for word in cut_list:\n if len(word)>=2:\n word_list.append(word)\n\n count_list=Counter(word_list).most_common(100)\n return count_list\n \n","sub_path":"19100202/junyanwang77/mymodule_day12/stats_word.py","file_name":"stats_word.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"579220069","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\n\nfrom spider_51job.items import Spider51JobItem\n\n\nclass Spider51jobRegularSpider(CrawlSpider):\n name = 'spider_51job_regular'\n allowed_domains = ['51job.com']\n start_urls = ['https://search.51job.com/list/000000,000000,0000,00,9,99,python,2,1.html?lang=c&postchannel=0000&workyear=99&cotype=99°reefrom=99&jobterm=99&companysize=99&ord_field=0&dibiaoid=0&line=&welfare=']\n\n rules = (\n Rule(LinkExtractor(allow=r'https://search.51job.com/list/000000,000000,0000,00,9,99,python,2,\\d+.html.+lang=c&postchannel=0000&workyear=99&cotype=99°reefrom=99&jobterm=99&companysize=99&ord_field=0&dibiaoid=0&line=&welfare='), follow=True),\n Rule(LinkExtractor(allow=r'https://jobs.51job.com/\\w+-\\w+/\\d+\\.html.+'), callback='parse_detail', follow=False),\n Rule(LinkExtractor(allow=r'https://jobs.51job.com/\\w+/\\d+\\.html.+'), callback='parse_detail', follow=False),\n )\n\n def parse_detail(self, response):\n workname = response.xpath('//div[@class=\"in\"]//h1/@title').get()\n salary = response.xpath('//div[@class=\"in\"]//div[@class=\"cn\"]//strong/text()').get()\n company = response.xpath('//div[@class=\"in\"]//p[@class=\"cname\"]/a[1]/@title').get()\n cptype = response.xpath('//div[@class=\"com_tag\"]//p[@class=\"at\"]/@title').get()\n business = response.xpath('//div[@class=\"com_tag\"]//a/text()').getall()\n msg = response.xpath('//div[@class=\"in\"]//p[@class=\"msg ltype\"]/@title').get().split('  |  ')\n if len(msg) == 4:\n msg.insert(2, None)\n place, exp, edu, needNum, time = msg[0], msg[1], msg[2], msg[3], msg[4]\n msg1 = response.xpath('//div[@class=\"tBorderTop_box\"][1]//p/text()').getall()\n work_msg = ''.join(''.join(msg1).split())\n # print(workname, company, cptype, business, place, exp, edu, needNum, time, work_msg)\n item = Spider51JobItem(workname=workname, salary=salary, company=company, cptype=cptype, business=business, place=place, exp=exp, edu=edu, needNum=needNum, time=time, work_msg=work_msg)\n yield item\n","sub_path":"Jobs_spider/spider_51job/spider_51job/spiders/spider_51job_regular.py","file_name":"spider_51job_regular.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"588972392","text":"import os \nimport csv\nimport math\npath = os.path.join(\"Resources\",\"budget_data.csv\")\ncount = 0\ntotal = 0\nvalue = []\nmonths = []\nDict= {}\nwith open(path,mode = 'r',encoding = 'utf8') as csvfile:\n csvreader = csv.reader(csvfile,delimiter=\",\")\n csvheader = next(csvreader)\n previousRow = 0\n for row in csvreader:\n count = count + 1 #counting total no. of rows here\n total = float(total) + float(row[1]) #total amount\n difference = float(row[1]) - previousRow #calculating change in profit/loss \n previousRow = float(row[1]) #storing value of previous cell\n if count > 1:\n Dict[row[0]]= difference #Creating a dictionary for storing the values as Months:Difference pair \n print(\"Financial Analysis\")\n print(\"--------------------------\")\n max_change = max(Dict.values()) #calculating maximum change\n min_change = min(Dict.values()) #calculating minimum change\n \n average = sum(Dict.values())/len(Dict.values())\n \n print(f\"The total no. of months included in the data set are:{count}\")\n print(f\"The net total amount of Profit/Losses over the entire period is : {total}\")\n print(f\"The average of the changes in Profit/Losses over the entire period is: {average}\")\n \n for key,values in Dict.items(): #Method to find out key,value values\n if values == max_change:\n print(f\"Greatest Increase in Profits:{key} (${values})\")\n \n if values == min_change:\n print(f\"Greatest Decrease in Profits:{key} (${values})\")\n \n \n\noutpath = os.path.join(\"Analysis\",\"output.txt\")\nwith open(outpath,mode='w',encoding='utf8') as csvfile: #Exporting the output in a text file\n csvwriter = csv.writer(csvfile,delimiter = ',')\n \n max_change = max(Dict.values()) \n min_change = min(Dict.values()) \n \n average = sum(Dict.values())/len(Dict.values())\n print(\"Financial Analysis\",file=csvfile)\n print(\"--------------------------\",file=csvfile) \n print(f\"The total no. of months included in the data set are:{count}\",file= csvfile)\n print(f\"The net total amount of Profit/Losses over the entire period is : {total}\",file= csvfile)\n print(f\"The average of the changes in Profit/Losses over the entire period is: {average}\",file= csvfile)\n \n for key,values in Dict.items(): \n if values == max_change:\n print(f\"Greatest Increase in Profits:{key} (${values})\",file= csvfile)\n \n if values == min_change:\n print(f\"Greatest Decrease in Profits:{key} (${values})\" ,file= csvfile)\n \n \n #References:https://stackoverflow.com/questions/45461406/python-output-to-a-text-file\n #https://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"54418810","text":"#===============================================================================\n#\n# FLASH Test Libs\n#\n# GENERAL DESCRIPTION\n# build script\n#\n# Copyright (c) 2009 Qualcomm Incorporated. \n# All Rights Reserved.\n# Qualcomm Confidential and Proprietary\n#\n#-------------------------------------------------------------------------------\n#\n# $Header: //source/qcom/qct/core/bsp/config/msm7x30/main/latest/storage/flash/src/dal/build/SConscript#7 $\n# $DateTime: 2009/07/19 21:27:25 $\n# $Author: wduembeg $\n# $Change: 971778 $\n# EDIT HISTORY FOR FILE\n#\n# This section contains comments describing changes made to the module.\n# Notice that changes are listed in reverse chronological order.\n#\n# when who what, where, why\n# -------- --- ---------------------------------------------------------\n# 07/13/10 bb Added support for 6615\n# 11/09/09 mc Initial revision\n#===============================================================================\nImport('env')\nenv = env.Clone()\n\n#-------------------------------------------------------------------------------\n# Source PATH\n#-------------------------------------------------------------------------------\nSRCPATH = \"${BUILD_ROOT}/core/storage/flash/src/test\"\n\nif not env.SubstPathExists(SRCPATH):\n SRCPATH = \"${BUILD_ROOT}/drivers/flash/src/test\"\n\nenv.VariantDir('${BUILDPATH}', SRCPATH, duplicate=0)\n\n#-------------------------------------------------------------------------------\n# Internal depends within CoreBSP\n#-------------------------------------------------------------------------------\n# BOOT: needed for miparti.h header inclusion\n# HWENGINES: needed for DMOV header files \n# SERVICES: needed for identifiers like \"boolean\" defs etc...\n# MPROC: needed when building AMSS\n# SYSTEMDRIVERS: needed for hwio headers\nCBSP_API = [\n 'BOOT',\n 'DAL', \n 'HAL', \n 'HWENGINES',\n 'MPROC',\n 'SERVICES',\n 'STORAGE',\n 'SYSTEMDRIVERS',\n\n # needs to be last also contains wrong comdef.h\n 'KERNEL', \n]\n\nFLASH_TEST_USES_SPI_NOR_ONLY = True\n\nenv.RequirePublicApi(CBSP_API)\nenv.RequireRestrictedApi(CBSP_API)\n\n#-------------------------------------------------------------------------------\n# Sources, libraries\n#-------------------------------------------------------------------------------\n\nFLASH_DAL_TEST_SOURCES = [\n '${BUILDPATH}/flash_test_benchmark.c', \n '${BUILDPATH}/flash_test_wrapper.c'\n]\n\nif not FLASH_TEST_USES_SPI_NOR_ONLY:\n FLASH_DAL_TEST_SOURCES += [\n '${BUILDPATH}/flash_test_api.c',\n ]\nelse: \n FLASH_DAL_TEST_SOURCES += [\n '${BUILDPATH}/flash_test_api_nor.c',\n ]\n\nflash_dal_test_obj = env.Object(FLASH_DAL_TEST_SOURCES)\nflash_dal_test_lib = env.Library('${BUILDPATH}/DALflash_test', flash_dal_test_obj)\n\n#-------------------------------------------------------------------------------\n# Add Libraries to image\n#-------------------------------------------------------------------------------\nif env['MSM_ID'] in ['6195', '6295', '6695', '6615'] :\n env.AddLibsToImage(\n ['MODEM_IMAGE', 'CBSP_MODEM_IMAGE', 'APPS_IMAGE', \n 'CBSP_APPS_IMAGE', 'SINGLE_IMAGE', 'CBSP_SINGLE_IMAGE'],\n flash_dal_test_lib)\n","sub_path":"modem_proc/core/storage/flash/src/test/build/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":3154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"586455875","text":"from django import template\nimport re, math\n\nregister = template.Library()\n\ndef truncatewordsclean(value, arg):\n words = value.split(' ')\n n = 0\n truncated = ''\n for word in words:\n truncated = truncated + word\n n = n + 1\n if n == arg:\n break\n else:\n truncated = truncated + ' '\n return truncated\n\nregister.filter('truncatewordsclean', truncatewordsclean)\n\n\ndef div_roundtohalf(value, arg):\n half_arg = arg / 2\n result_double = math.ceil(value/half_arg)\n if (result_double % 2) == 0:\n return int(result_double/2)\n else:\n return result_double/2\n\nregister.filter('div_roundtohalf', div_roundtohalf)","sub_path":"propelproject/commons/custom_tags.py","file_name":"custom_tags.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"489165792","text":"from ctypes import *\nimport sys\nimport pickle\nfrom util import *\nfrom win_util import *\n\n'''for 32bit change this to 4'''\nif sys.argv[2] == '64':\n\tis_64 = 1\n\tgpointer = u64_pointer\n\tPTR_SZ = 8\nelse:\n\tPTR_SZ = 4\n\tgpointer = u32_pointer\n\nmodule_t_sz = 264\n\nMAX_COV_MODULE = 8\nMAP_SZ = 2**16\nfuzzer_id = sys.argv[1]\n\nmap_str = 'afl_shm_%s_MAP' % fuzzer_id\nvar_str = 'afl_shm_%s_VAR' % fuzzer_id\nvirgin_str = 'afl_shm_%s_VIRGIN' % fuzzer_id\nmodule_str = 'afl_shm_%s_MOD' % fuzzer_id\n\nMAP = map_shm(map_str, MAP_SZ*PTR_SZ)\nMOD_INFO = map_shm(module_str, module_t_sz*MAX_COV_MODULE)\nVIRGIN = map_shm(virgin_str, MAP_SZ)\nVAR = map_shm(var_str, MAP_SZ)\n\ndef get_module_info():\n\tmodules = []\n\n\tfor i in range(MAX_COV_MODULE):\n\t\tstart = gpointer(MOD_INFO)[module_t_sz//PTR_SZ*i]\n\t\tif start:\n\t\t\tmod = {}\n\t\t\tend = gpointer(MOD_INFO)[module_t_sz//PTR_SZ*i+1]\n\t\t\tj = 2*PTR_SZ + module_t_sz*i\n\t\t\tmodule_name = ''\n\t\t\twhile MOD_INFO[j] != 0:\n\t\t\t\tmodule_name += chr(MOD_INFO[j])\n\t\t\t\tj += 1\n\t\t\t\n\t\t\tmod['start'] = start\n\t\t\tmod['end'] = end\n\t\t\tmod['name'] = module_name\n\n\n\t\t\tprint (mod)\n\t\t\tmodules.append(mod)\n\t\telse:\n\t\t\tbreak\n\treturn modules\n\nmodules = get_module_info()\n\ndef get_map():\n\tr = []\n\n\tm = gpointer(MAP)\n\tfor blk_id in range(MAP_SZ):\n\t\taddr = m[blk_id]\n\t\tif (addr == 0):\n\t\t\tbreak\n\t\t# print (hex(addr))\n\t\tassert(addr not in r)\n\t\tfor mod in modules:\n\t\t\tif addr >= mod['start'] and addr <= mod['end']:\n\t\t\t\taddr -= mod['start']\n\t\t\t\tbreak\n\t\tr.append((addr, 1))\n\n\treturn r\n\ndef get_var():\n\tmp = get_map()\n\n\tprint ('nblock: ', len(mp))\n\tp = u8_pointer(VAR)\n\tvar = []\n\n\tfor blk_id in range(MAP_SZ):\n\t\tif p[blk_id] != 0:\n\t\t\ttry:\n\t\t\t\tvar.append(mp[blk_id])\n\t\t\texcept:\n\t\t\t\tprint (blk_id)\n\treturn var\n\ncov_dict = {\n\t'cov': get_var()\n}\n\nf = open('var_%s.pkl' % sys.argv[1], 'wb')\nf.write(pickle.dumps(cov_dict, protocol=2))\nf.close()\n\n\n","sub_path":"getvar.py","file_name":"getvar.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"252519866","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n# $NoKeywords: $ for Visual Sourcesafe, stop replacing tags\n__revision__ = \"$Revision: 1.5 $\"\n__revision_number__ = __revision__.split()[1]\n__url__ = \"https://newspipe.sourceforge.net\"\n__author__ = \"Ricardo M. Reyes \"\n__maintainer__ = \"Rui Carmo\"\n\nfrom pprint import pprint\nimport xml.dom.minidom\nfrom htmlentitydefs import *\nfrom datetime import datetime\n\ndef getText(nodelist):\n rc = \"\"\n for node in nodelist:\n if node.nodeType == node.TEXT_NODE:\n rc = rc + node.data\n return rc\n\ndef to_dict(root):\n result = {}\n\n if root.getElementsByTagName ('outline'):\n outline = True\n else:\n outline = False\n\n for attr, value in root.attributes.items():\n result[attr] = value\n\n if outline:\n result[u'childs'] = {}\n for child in [x for x in root.childNodes if x.nodeName == 'outline']:\n attribute = child.attributes.get('title', child.attributes.get('text', None))\n if attribute:\n name = attribute.value\n else:\n name = ''\n \n if name in result[u'childs'].keys():\n i = 1\n original = name\n name = original + str(i)\n while name in result[u'childs'].keys():\n i += 1\n name = original + str(i)\n # end while\n \n result[u'childs'][name] = to_dict(child)\n\n else:\n for node in root.childNodes:\n result[node.nodeName] = getText(node.childNodes)\n\n\n return result\n \n\ndef ParseOPML(data):\n\n result = {}\n\n dom = xml.dom.minidom.parse(data)\n\n node = dom.getElementsByTagName('opml')[0]\n result[u'opml'] = {u'head':to_dict(node.getElementsByTagName('head')[0]), \n u'body':to_dict(node.getElementsByTagName('body')[0])}\n\n #result = to_dict(dom)\n\n dom.unlink()\n\n return result\n \n\ndef handle_branch(rama, resultados, antecesores, valores_heredados):\n valores = {}\n for key in rama.keys():\n if key != 'childs':\n valores[key] = rama[key]\n \n\n for attr, value in valores_heredados.items():\n if not attr in valores.keys():\n valores[attr] = value\n\n\n if 'childs' in rama.keys():\n children = rama['childs']\n for child in children.keys():\n handle_branch (children[child], resultados, antecesores + [child,], valores)\n\n else:\n if antecesores.__len__() > 1:\n valores[u'path'] = '/' + u'/'.join(antecesores[:-1])\n else:\n valores[u'path'] = '/'\n\n resultados += [valores,]\n \n\ndef ListToDict(items):\n result = {}\n\n for attr, value in items:\n result[attr] = value.strip()\n\n return result\n \n\ndef flatten_tree(tree, defaults=None):\n items = []\n\n handle_branch(tree['opml']['body'], items, [], {})\n\n result = {'head':ListToDict(tree['opml']['head'].items()),\n 'body':items}\n \n # add an index value to each item \n for i, each in enumerate(items):\n each[u'index'] = unicode(str(i))\n \n # add the default values to those item that are not complete\n if defaults:\n for each in items:\n for key,value in defaults.items():\n if not isinstance(key, unicode):\n key = unicode(key)\n if not isinstance(value, unicode):\n value = unicode(value)\n if not key in each.keys():\n each[key] = value\n\n return result\n \n\nentities = {}\nfor key,value in entitydefs.items():\n entities[unicode(value, 'latin1')] = unicode(key)\n# end for\n\ndef escape (text):\n aux = []\n for each in text:\n if each in entities.keys():\n aux.append ('&'+entities[each]+';')\n else:\n aux.append (each)\n return ''.join(aux)\n\ndef generarOPML (feedList):\n doc = xml.dom.minidom.Document()\n \n opml = doc.createElement ('opml')\n opml.setAttribute ('version', '1.1')\n doc.appendChild(opml)\n \n head = doc.createElement ('head')\n opml.appendChild(head)\n \n for each, value in feedList['head'].items():\n if value.strip():\n if each != 'dateModified':\n attr = doc.createElement (each)\n ptext = doc.createTextNode (value)\n attr.appendChild (ptext)\n head.appendChild (attr)\n\n attr = doc.createElement ('dateModified')\n ptext = doc.createTextNode (str(datetime.now()))\n attr.appendChild (ptext)\n head.appendChild (attr)\n \n\n body = doc.createElement('body')\n opml.appendChild(body)\n for each in feedList['body']:\n outline = doc.createElement ('outline')\n for key, value in each.items():\n outline.setAttribute (key, value)\n body.appendChild (outline)\n\n return doc.toprettyxml(encoding='utf-8')\n\nif __name__ == '__main__':\n pprint (flatten_tree(ParseOPML('test.opml')))\n","sub_path":"lib/utils/opml.py","file_name":"opml.py","file_ext":"py","file_size_in_byte":5050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"357309741","text":"# -*- coding: utf-8 -*-\n# Programme faisant choisir à l'utilisateur un numéro d'exercice pour obtenir sa réponse, en utilisant la librairie maison procedure.py.\nfrom procedure import *\n\n\nchoix = 1 # on initialise la variable choix\n\nwhile choix!=5:\n choix=affichage_menu()\n if choix==1:\n carre()\n elif choix ==2:\n distance()\n elif choix==3:\n CUBE()\n elif choix==4:\n print(\"entrer les coefficients de votre équation ax^2+bx+c\")\n a=input(\"a= \")\n b=input(\"b= \")\n c=input(\"c= \")\n seconddegre(a,b,c)\n elif choix==5:\n temp()\n\n","sub_path":"TP2/TP2.py","file_name":"TP2.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"206889058","text":"import tensorflow as tf\r\nimport numpy as np\r\n\r\n\r\nclass DPPOMODEL(object):\r\n def __init__(self,\r\n GLOBAL_SHARE=None,\r\n PARAMETERS=None,\r\n SCHEDULE=None):\r\n if PARAMETERS is None:\r\n raise NotImplementedError\r\n # 導入模組\r\n self.GLOBAL_SHARE = GLOBAL_SHARE\r\n self.PARAMETERS = PARAMETERS\r\n self.SCHEDULE = SCHEDULE\r\n\r\n # 設定輸入的維度\r\n self.image_features, self.action_dim = 512, 1\r\n\r\n # 建立神經網路\r\n config = tf.ConfigProto()\r\n config.gpu_options.allow_growth = True\r\n self.sess = tf.Session(config=config)\r\n self.tfs = tf.placeholder(tf.float32, [None, 168, 168, 3], 'state')\r\n c0 = tf.cast(self.tfs, tf.float32) / 255.\r\n c1 = tf.nn.relu(self.conv(c0,\r\n 'c1',\r\n nf=32,\r\n rf=8,\r\n stride=4,\r\n init_scale=np.sqrt(2)))\r\n c2 = tf.nn.relu(\r\n self.conv(\r\n c1,\r\n 'c2',\r\n nf=64,\r\n rf=4,\r\n stride=2,\r\n init_scale=np.sqrt(2)))\r\n pool = tf.layers.max_pooling2d(\r\n c2,\r\n (2, 2),\r\n (1, 1),\r\n padding='valid',\r\n data_format='channels_last',\r\n name='pool'\r\n )\r\n c3 = tf.nn.relu(\r\n self.conv(\r\n pool,\r\n 'c3',\r\n nf=64,\r\n rf=3,\r\n stride=1,\r\n init_scale=np.sqrt(2)))\r\n\r\n nh = np.prod([v.value for v in c3.get_shape()[1:]])\r\n\r\n h3 = tf.reshape(c3, [-1, nh])\r\n fc1 = tf.nn.relu(self.fc(h3, 'fc1', nh=512, init_scale=np.sqrt(2)))\r\n pre_s = tf.nn.sigmoid(\r\n self.fc(\r\n fc1,\r\n 'fc2',\r\n nh=128,\r\n init_scale=np.sqrt(2)))\r\n # pre_s = tf.nn.relu(self.fc(h3, 'fc1', nh=512, init_scale=np.sqrt(2)))\r\n # Critic\r\n # 定義變數\r\n self.tfdc_r = tf.placeholder(tf.float32, [None, 1], 'discounted_r')\r\n # 建立網路層\r\n l1 = tf.layers.dense(\r\n inputs=pre_s,\r\n units=100, # number of hidden units\r\n activation=tf.nn.relu,\r\n name='l1'\r\n )\r\n self.v = tf.layers.dense(\r\n inputs=l1,\r\n units=1, # output units\r\n activation=None,\r\n name='V'\r\n )\r\n # 計算損益\r\n self.advantage = self.tfdc_r - self.v\r\n self.closs = tf.reduce_mean(tf.square(self.advantage))\r\n self.ctrain_op = tf.train.AdamOptimizer(\r\n self.PARAMETERS.C_LR).minimize(\r\n self.closs)\r\n\r\n # Actor\r\n # 建立網路\r\n action_op, action_op_params = self._build_anet(\r\n 'action_op', trainable=True)\r\n old_action_op, old_action_op_params = self._build_anet(\r\n 'old_action_op', trainable=False)\r\n\r\n # 定義輸出範例\r\n self.sample_op = tf.squeeze(\r\n action_op.sample(1),\r\n axis=0) # operation of choosing action\r\n # 更新\r\n self.update_old_action_op_op = [\r\n olda.assign(a) for a, olda in zip(\r\n action_op_params, old_action_op_params)]\r\n # 定義輸入變數\r\n self.tfa = tf.placeholder(\r\n tf.float32, [None, self.action_dim], 'action')\r\n self.tfadv = tf.placeholder(tf.float32, [None, 1], 'advantage')\r\n # 機率比較\r\n ratio = action_op.prob(self.tfa) / \\\r\n (old_action_op.prob(self.tfa) + 1e-5)\r\n # 替代損失\r\n surr = ratio * self.tfadv\r\n # 減少代理損失\r\n self.aloss = -tf.reduce_mean(tf.minimum(surr,\r\n tf.clip_by_value(ratio,\r\n 1. - self.PARAMETERS.EPSILON,\r\n 1. + self.PARAMETERS.EPSILON) * self.tfadv))\r\n self.atrain_op = tf.train.AdamOptimizer(\r\n self.PARAMETERS.A_LR).minimize(\r\n self.aloss)\r\n # log\r\n self.saver = tf.train.Saver()\r\n self.train_writer = tf.summary.FileWriter(self.SCHEDULE.LOG_PATH, self.sess.graph)\r\n self.sess.run(tf.global_variables_initializer())\r\n\r\n def update(self):\r\n while not self.GLOBAL_SHARE.COORD.should_stop():\r\n if self.GLOBAL_SHARE.EP < self.SCHEDULE.EP_MAX:\r\n # 等待收集資料\r\n self.GLOBAL_SHARE.UPDATE_EVENT.wait()\r\n # 用新的思考模式取代掉舊的模式\r\n self.sess.run(self.update_old_action_op_op) #\r\n # 從各個平台內收集資料\r\n # print(\"QUEUE in : \", QUEUE.qsize())\r\n data = [self.GLOBAL_SHARE.QUEUE.get() for _ in range(\r\n self.GLOBAL_SHARE.QUEUE.qsize())] # collect data from all workers\r\n data = np.vstack(data)\r\n s, a, r = data[:, :84672], data[:,\r\n 84672: 84672 + 1], data[:, -1:]\r\n s = s.reshape(-1, 168, 168, 3)\r\n adv = self.sess.run(\r\n self.advantage, {\r\n self.tfs: s, self.tfdc_r: r})\r\n # 更新AC\r\n [self.sess.run(\r\n self.atrain_op, {\r\n self.tfs: s, self.tfa: a, self.tfadv: adv}) for _ in range(\r\n self.PARAMETERS.UPDATE_STEP)]\r\n [self.sess.run(self.ctrain_op, {self.tfs: s, self.tfdc_r: r}) for _ in range(\r\n self.PARAMETERS.UPDATE_STEP)]\r\n # 完成更新作業\r\n self.GLOBAL_SHARE.UPDATE_EVENT.clear()\r\n # 重新計數\r\n self.GLOBAL_SHARE.UPDATE_COUNTER = 0\r\n # 設成可以使用\r\n self.GLOBAL_SHARE.ROLLING_EVENT.set()\r\n\r\n # from Open AI baseline\r\n # def cnn(self, s):\r\n\r\n # return tf.reshape(h, [-1]).eval()\r\n\r\n def conv(self,\r\n x,\r\n scope,\r\n *,\r\n nf,\r\n rf,\r\n stride,\r\n pad='VALID',\r\n init_scale=1.0,\r\n data_format='NHWC',\r\n one_dim_bias=False):\r\n channel_ax = 3\r\n strides = [1, stride, stride, 1]\r\n bshape = [1, 1, 1, nf]\r\n bias_var_shape = [nf] if one_dim_bias else [1, nf, 1, 1]\r\n nin = x.get_shape()[channel_ax].value\r\n wshape = [rf, rf, nin, nf]\r\n with tf.variable_scope(scope):\r\n w = tf.get_variable(\r\n \"w\", wshape, initializer=self.ortho_init(init_scale))\r\n b = tf.get_variable(\r\n \"b\",\r\n bias_var_shape,\r\n initializer=tf.constant_initializer(0.0))\r\n if not one_dim_bias and data_format == 'NHWC':\r\n b = tf.reshape(b, bshape)\r\n return tf.nn.conv2d(\r\n x,\r\n w,\r\n strides=strides,\r\n padding=pad,\r\n data_format=data_format) + b\r\n\r\n def fc(self, x, scope, nh, *, init_scale=1.0, init_bias=0.0):\r\n with tf.variable_scope(scope):\r\n nin = x.get_shape()[1].value\r\n w = tf.get_variable(\r\n \"w\", [nin, nh], initializer=self.ortho_init(init_scale))\r\n b = tf.get_variable(\r\n \"b\", [nh], initializer=tf.constant_initializer(init_bias))\r\n return tf.matmul(x, w) + b\r\n\r\n def ortho_init(self, scale=1.0):\r\n def _ortho_init(shape, dtype, partition_info=None):\r\n # lasagne ortho init for tf\r\n shape = tuple(shape)\r\n if len(shape) == 2:\r\n flat_shape = shape\r\n elif len(shape) == 4: # assumes NHWC\r\n flat_shape = (np.prod(shape[:-1]), shape[-1])\r\n else:\r\n raise NotImplementedError\r\n a = np.random.normal(0.0, 1.0, flat_shape)\r\n u, _, v = np.linalg.svd(a, full_matrices=False)\r\n q = u if u.shape == flat_shape else v # pick the one with the correct shape\r\n q = q.reshape(shape)\r\n return (scale * q[:shape[0], :shape[1]]).astype(np.float32)\r\n\r\n return _ortho_init\r\n ####################################################\r\n\r\n def _build_anet(self, name, trainable):\r\n # 定義Actor 新舊的網路模型\r\n with tf.variable_scope(name):\r\n c0 = tf.cast(self.tfs, tf.float32) / 255.\r\n c1 = tf.nn.relu(self.conv(c0,\r\n 'c1',\r\n nf=32,\r\n rf=8,\r\n stride=4,\r\n init_scale=np.sqrt(2)))\r\n c2 = tf.nn.relu(self.conv(c1,\r\n 'c2',\r\n nf=64,\r\n rf=4,\r\n stride=2,\r\n init_scale=np.sqrt(2)))\r\n c3 = tf.nn.relu(self.conv(c2,\r\n 'c3',\r\n nf=64,\r\n rf=3,\r\n stride=1,\r\n init_scale=np.sqrt(2)))\r\n nh = np.prod([v.value for v in c3.get_shape()[1:]])\r\n h3 = tf.reshape(c3, [-1, nh])\r\n pre_s = tf.nn.relu(self.fc(h3,\r\n 'fc1',\r\n nh=512,\r\n init_scale=np.sqrt(2)))\r\n l1 = tf.layers.dense(inputs=pre_s,\r\n units=200, # number of hidden units\r\n activation=tf.nn.relu,\r\n name='l1',\r\n trainable=trainable\r\n )\r\n mu = 2 * tf.layers.dense(inputs=l1,\r\n units=self.action_dim, # number of hidden units\r\n activation=tf.nn.tanh,\r\n name='mu',\r\n trainable=trainable\r\n )\r\n sigma = tf.layers.dense(inputs=l1,\r\n units=self.action_dim, # output units\r\n activation=tf.nn.softplus, # get action probabilities\r\n name='sigma',\r\n trainable=trainable\r\n )\r\n norm_dist = tf.distributions.Normal(loc=mu, scale=sigma)\r\n params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=name)\r\n return norm_dist, params\r\n\r\n def choose_action(self, s):\r\n # 決定下一步該怎麼做\r\n # s = s[np.newaxis, :]\r\n s = s.reshape(-1, 168, 168, 3)\r\n a = self.sess.run(self.sample_op, {self.tfs: s})[0]\r\n return np.clip(a,\r\n self.PARAMETERS.ACTION_BOUND[0],\r\n self.PARAMETERS.ACTION_BOUND[1])\r\n\r\n def get_v(self, s):\r\n if s.ndim < 4:\r\n s = s[np.newaxis, :]\r\n return self.sess.run(self.v, {self.tfs: s})[0, 0]\r\n\r\n def load(self):\r\n self.ckpt = tf.train.get_checkpoint_state(\r\n self.SCHEDULE.CHECKPOINT_PATH)\r\n if self.ckpt and self.ckpt.model_checkpoint_path:\r\n self.saver.restore(self.sess, self.ckpt.model_checkpoint_path)\r\n else:\r\n pass\r\n\r\n def save(self):\r\n self.saver.save(\r\n self.sess,\r\n self.SCHEDULE.CHECKPOINT_PATH +\r\n 'model.ckpt',\r\n self.GLOBAL_SHARE.EP,\r\n write_meta_graph=False)\r\n","sub_path":"keepitpossible/model/ex_dppo_model.py","file_name":"ex_dppo_model.py","file_ext":"py","file_size_in_byte":12138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"97354492","text":"#!/usr/bin/env python3\n\nimport itertools\nimport sys\nimport copy\nimport math\n\nfrom src.load_input import load_input\nfrom src.util import distance, find_closest_nonempty_warehouses\nfrom src.output import Output\n\nif len(sys.argv) != 3:\n print(\"invalid number of params\")\n print(\"run as: ./script input_file.in output_file.out\")\n sys.exit(1)\n\nworld, initial_state = load_input(sys.argv[1])\n\n# this is the function which is called anytime drone is idle and\n# it decides what the drone will do next\n#\n# the idea behind this implementation is to find closest non-empty\n# warehouse to drone which can deliver something for any order\n# and find order which can be ideally fully\n# delivered from this warehouse or order for which the drone can\n# be fully loaded\ndef find_drone_action(state, d):\n if len(state.warehouses) == 1:\n # optimalization for scenario when there is just one warehouse\n w = state.warehouses[0]\n return find_drone_action_for_single_warehouse(state, d, w)\n else:\n closest_warehouses = find_closest_nonempty_warehouses(state, d)\n\n for w in closest_warehouses:\n action = find_drone_action_for_warehouse(state, d, w)\n if action != None:\n return action\n\n return None\n\ndef group_items_by_pt_id(items):\n items.sort(key = lambda i: i.pt_id)\n\n grouped_items = {}\n for pt_id, items in itertools.groupby(items, lambda i: i.pt_id):\n grouped_items[pt_id] = list(items)\n\n return grouped_items\n\n# if there is just one warehouse, it is easy. we should already have the cost of\n# each order ready and we just deliver it by that cost function\ndef find_drone_action_for_single_warehouse(state, d, w):\n for o in state.open_orders:\n if len(o.items_chunks) == 0:\n continue\n\n # this gets the chunks and also removes it from the list of chunks\n chunk = o.items_chunks.pop(0)\n\n return (w, o, group_items_by_pt_id(chunk))\n\n\ndef find_drone_action_for_warehouse(state, d, w):\n o_deliverable_fully = []\n o_other = []\n\n for o in state.open_orders:\n if o.delivered():\n continue\n\n o_deliverable_weight = 0\n o_deliverable_items = []\n o_undeliverable_weight = 0\n\n # lets create copy of warehouse so we can check that the stock\n # is enough\n temp_w = copy.deepcopy(w)\n\n for item in o.items:\n if o.delivered():\n continue\n\n if item.delivered:\n continue\n\n pt_weight = world.pt_weights[item.pt_id]\n\n if temp_w.stock[item.pt_id] > 0:\n # item in warehouse stock\n temp_w.stock[item.pt_id] -= 1\n o_deliverable_weight += pt_weight\n o_deliverable_items.append(item)\n else:\n # item not in warehouse stock\n o_undeliverable_weight += pt_weight\n\n # print('@')\n # print(str(o.id))\n # print(str(o_deliverable_weight))\n # print((o_undeliverable_weight == 0 and o_deliverable_weight < world.d_max_payload))\n\n if o_deliverable_weight == 0:\n # nothing in this warehouse for the order\n pass\n elif o_undeliverable_weight == 0 and o_deliverable_weight < world.d_max_payload:\n # lets log orders which we can fully deliver from this warehouse\n # by just one drone flight\n o_deliverable_fully.append(o)\n else:\n o_other.append((o, o_deliverable_items, o_deliverable_weight, o_undeliverable_weight))\n\n # if there are some orders which can be delivered fully, do that!\n if len(o_deliverable_fully) > 0:\n o_deliverable_fully.sort(key = lambda o: distance(o.pos, d.pos))\n o = o_deliverable_fully[0]\n return (w, o, group_items_by_pt_id([i for i in o.items if not i.delivered]))\n\n if len(o_other) == 0:\n # there is no order, we got it all!\n return None\n\n # otherwise find the order with lowest deliverable weight and lowest distance\n o_other.sort(key = lambda x: x[2] * distance(x[0].pos, d.pos))\n o, o_deliverable_items, a, b = o_other[0]\n\n # sort the deliverable items by the heaviest first so we can get best use of\n # the max payload\n o_deliverable_items.sort(key = lambda i: world.pt_weights[i.pt_id], reverse=True)\n\n # and limit the number of items based on max payload\n deliver_items = []\n deliver_weight = 0\n for item in o_deliverable_items:\n pt_weight = world.pt_weights[item.pt_id]\n if (deliver_weight + pt_weight) <= world.d_max_payload:\n deliver_items.append(item)\n deliver_weight += pt_weight\n\n return (w, o, group_items_by_pt_id(deliver_items))\n\ndef prepare_for_single_warehouse_scenario(state):\n w = state.warehouses[0]\n\n # split each order into chunks of items by weight\n for o in state.open_orders:\n\n # give each item weight for easier manipulation later\n for i in o.items:\n i.weight = world.pt_weights[i.pt_id]\n\n chunks = []\n chunk = []\n chunk_weight = 0\n items_heaviest_first = sorted(o.items, key = lambda i: i.weight, reverse=True)\n\n # we are trying to make chunks as full as possible\n while True:\n for item in items_heaviest_first:\n if (chunk_weight + item.weight) > world.d_max_payload:\n continue\n\n chunk.append(item)\n chunk_weight += item.weight\n\n for item in chunk:\n items_heaviest_first.remove(item)\n\n chunks.append(chunk)\n chunk = []\n chunk_weight = 0\n\n if len(items_heaviest_first) == 0:\n break\n\n o.items_chunks = chunks\n\n # base cost is just the turns needed to go back and forth with the drone\n cost = len(chunks) * distance(w.pos, o.pos)\n\n # and to be more precise, we will also add the turns needed for loading\n # and unloading\n for chunk in chunks:\n chunk_product_types = {}\n for item in chunk:\n if item.pt_id not in chunk_product_types:\n chunk_product_types[item.pt_id] = 0\n chunk_product_types[item.pt_id] += 1\n\n turns_to_load_chunk = len(chunk_product_types)\n\n # multiplied by two because we need to load and then unload it\n cost += turns_to_load_chunk * 2\n\n o.cost = cost\n\n state.open_orders.sort(key = lambda o: o.cost)\n\noutput = Output(sys.argv[2])\nstate = copy.deepcopy(initial_state)\n\nif len(state.warehouses) == 1:\n prepare_for_single_warehouse_scenario(state)\n\nfor turn in range(world.turns):\n print(\"-- starting turn \" + str(turn))\n\n idle_drones = [d for d in state.drones if d.turns_to_pos == 0]\n\n for d in idle_drones:\n # find action to do\n action = find_drone_action(state, d)\n\n if action == None:\n continue\n\n w, o, items_to_deliver = action\n\n turns_till_idle_again = 0\n\n # drone has to get to the warehouse first\n turns_till_idle_again += distance(d.pos, w.pos)\n print(\" * sending drone \" + str(d.id) + \" to warehouse \" + str(w.id) + \" at \" + str(w.pos[0]) + \"-\" + str(w.pos[1]) + \" (distance: \" + str(distance(d.pos, w.pos)) + \")\")\n\n # load stuff from warehouse\n for pt_id, items in items_to_deliver.items():\n qty = len(items)\n\n output.load(d.id, w.id, pt_id, qty)\n print(\" * loading drone \" + str(d.id) + \" with product \" + str(pt_id) + \" of qty \" + str(qty))\n\n print(\" $ stock of \" + str(pt_id) + \" at warehouse \" + str(w.id) + \" was \" + str(w.stock[pt_id]) + \", is now \" + str(w.stock[pt_id] - qty))\n w.stock[pt_id] -= qty\n\n # every load command takes one turn\n turns_till_idle_again += 1\n\n # drone has to get to order\n turns_till_idle_again += distance(w.pos, o.pos)\n print(\" * sending drone \" + str(d.id) + \" to order \" + str(o.id) + \" pos \" + str(o.pos[0]) + \"-\" + str(o.pos[1]) + \" (distance: \" + str(distance(w.pos, o.pos)) + \")\")\n\n # drone has to unload\n for pt_id, items in items_to_deliver.items():\n qty = len(items)\n\n output.deliver(d.id, o.id, pt_id, qty)\n print(\" * unloading drone \" + str(d.id) + \" with product \" + str(pt_id) + \" of qty \" + str(qty))\n\n # every deliver command takes one turn\n turns_till_idle_again += 1\n\n for item in items:\n item.delivered = True\n\n if o.delivered():\n delivered_orders = [o for o in state.open_orders if o.delivered()]\n print(\" # delivered \" + str(len(delivered_orders)) + \" out of \" + str(len(state.open_orders)) + \" orders\")\n\n if len(delivered_orders) == len(state.open_orders):\n print(\"end, no more orders!\")\n output.write_to_file()\n sys.exit(0)\n\n d.pos = copy.deepcopy(o.pos)\n d.turns_to_pos = turns_till_idle_again\n\n for d in state.drones:\n if d.turns_to_pos > 0:\n d.turns_to_pos = d.turns_to_pos - 1\n\nprint(\"end, no more turns!\")\noutput.write_to_file()\nsys.exit(0)\n","sub_path":"3_closest_warehouse_v2.py","file_name":"3_closest_warehouse_v2.py","file_ext":"py","file_size_in_byte":9231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"85632375","text":"from qml.aglaia.aglaia import ARMP\nimport numpy as np\nimport h5py\nimport pickle\nfrom random import shuffle\nimport os\n\n# Creating output dir\nif not os.path.exists(\"../outputs/hc6sq_train_001/\"):\n os.makedirs(\"../outputs/hc6sq_train_001/\")\n\n# Getting the dataset\ndata_methane = h5py.File(\"../datasets/methane_cn_dft.hdf5\", \"r\")\ndata_isopentane = h5py.File(\"../datasets/isopentane_cn_dft.hdf5\", \"r\")\ndata_squal = h5py.File(\"../datasets/squalane_cn_dft.hdf5\", \"r\")\ndata_2isohex = h5py.File(\"../datasets/2isohexane_cn_dft.hdf5\")\ndata_3isohex = h5py.File(\"../datasets/3isohexane_cn_dft.hdf5\")\n\nref_ene = -133.1 * 2625.50\n\nn_samples_methane = 8000\nn_samples_isopentane = 4000\nn_samples_2isohex = 1500\nn_samples_3isohex = 1500\n\nzs_squal = np.array(data_squal.get(\"zs\"), dtype=np.int32)\nn_atoms_squal = len(zs_squal[0])\nprint(\"The number of squalane samples is: %i\" % len(zs_squal))\n\n# Data for methane\ntraj_idx_methane = np.asarray(data_methane.get('traj_idx'), dtype=int)\n\nidx_train_methane = np.where(traj_idx_methane != 14)[0]\nshuffle(idx_train_methane)\nidx_train_methane = idx_train_methane[:n_samples_methane]\n\nprint(\"The number of methane samples is: %i (train)\" % (len(idx_train_methane)))\n\nxyz_methane = np.array(data_methane.get(\"xyz\"))[idx_train_methane]\nzs_methane = np.array(data_methane.get(\"zs\"), dtype=np.int32)[idx_train_methane]\nene_methane = np.array(data_methane.get(\"ene\"))[idx_train_methane]* 2625.50 - ref_ene\n\npad_xyz_methane = np.concatenate((xyz_methane, np.zeros((xyz_methane.shape[0], n_atoms_squal - xyz_methane.shape[1], 3))), axis=1)\npad_zs_methane = np.concatenate((zs_methane, np.zeros((zs_methane.shape[0], n_atoms_squal - zs_methane.shape[1]), dtype=np.int32)), axis=1)\n\n# Data for isopentane\ntraj_idx_isopentane = np.asarray(data_isopentane.get('traj_idx'), dtype=int)\n\nidx_train_isopentane = np.where(traj_idx_isopentane != 22)[0]\nshuffle(idx_train_isopentane)\nidx_train_isopentane = idx_train_isopentane[:n_samples_isopentane]\n\nprint(\"The number of isopentane samples is: %i (train)\" % (len(idx_train_isopentane)))\n\nxyz_isopentane = np.array(data_isopentane.get(\"xyz\"))[idx_train_isopentane]\nzs_isopentane = np.array(data_isopentane.get(\"zs\"), dtype=np.int32)[idx_train_isopentane]\nene_isopentane = np.array(data_isopentane.get(\"ene\"))[idx_train_isopentane]* 2625.50 - ref_ene\n\npad_xyz_isopentane = np.concatenate((xyz_isopentane, np.zeros((xyz_isopentane.shape[0], n_atoms_squal - xyz_isopentane.shape[1], 3))), axis=1)\npad_zs_isopentane = np.concatenate((zs_isopentane, np.zeros((zs_isopentane.shape[0], n_atoms_squal - zs_isopentane.shape[1]), dtype=np.int32)), axis=1)\n\n# Data for 2-isohexane\ntraj_idx_2isohex = np.asarray(data_2isohex.get('traj_idx'), dtype=int)\n\nidx_train_2isohex = np.where(traj_idx_2isohex != 12)[0]\nshuffle(idx_train_2isohex)\nidx_train_2isohex = idx_train_2isohex[:n_samples_2isohex]\n\nprint(\"The number of 2-isohexane samples is: %i (train)\" % (len(idx_train_2isohex)))\n\nxyz_2isohex = np.array(data_2isohex.get(\"xyz\"))[idx_train_2isohex]\nzs_2isohex = np.array(data_2isohex.get(\"zs\"), dtype=np.int32)[idx_train_2isohex]\nene_2isohex = np.array(data_2isohex.get(\"ene\"))[idx_train_2isohex]* 2625.50 - ref_ene\n\npad_xyz_2isohex = np.concatenate((xyz_2isohex, np.zeros((xyz_2isohex.shape[0], n_atoms_squal - xyz_2isohex.shape[1], 3))), axis=1)\npad_zs_2isohex = np.concatenate((zs_2isohex, np.zeros((zs_2isohex.shape[0], n_atoms_squal - zs_2isohex.shape[1]), dtype=np.int32)), axis=1)\n\n# Data for 3-isohexane\ntraj_idx_3isohex = np.asarray(data_3isohex.get('traj_idx'), dtype=int)\n\nidx_train_3isohex = np.where(traj_idx_3isohex != 14)[0]\nshuffle(idx_train_3isohex)\nidx_train_3isohex = idx_train_3isohex[:n_samples_3isohex]\n\nprint(\"The number of 3-isohexane samples is: %i (train)\" % (len(idx_train_3isohex)))\n\nxyz_3isohex = np.array(data_3isohex.get(\"xyz\"))[idx_train_3isohex]\nzs_3isohex = np.array(data_3isohex.get(\"zs\"), dtype=np.int32)[idx_train_3isohex]\nene_3isohex = np.array(data_3isohex.get(\"ene\"))[idx_train_3isohex]* 2625.50 - ref_ene\n\npad_xyz_3isohex = np.concatenate((xyz_3isohex, np.zeros((xyz_3isohex.shape[0], n_atoms_squal - xyz_3isohex.shape[1], 3))), axis=1)\npad_zs_3isohex = np.concatenate((zs_3isohex, np.zeros((zs_3isohex.shape[0], n_atoms_squal - zs_3isohex.shape[1]), dtype=np.int32)), axis=1)\n\n\n# Concatenating all the data\nconcat_xyz = np.concatenate((pad_xyz_methane, pad_xyz_isopentane, pad_xyz_2isohex, pad_xyz_3isohex))\nconcat_ene = np.concatenate((ene_methane, ene_isopentane, ene_2isohex, ene_3isohex))\nconcat_zs = np.concatenate((pad_zs_methane, pad_zs_isopentane, pad_zs_2isohex, pad_zs_3isohex))\n\nzs_for_scaler = list(zs_methane) + list(zs_isopentane) + list(zs_2isohex) + list(zs_3isohex)\n\nscaling = pickle.load(open(\"../outputs/make_scaler_001/scaler.pickle\", \"rb\"))\nconcat_ene_scaled = scaling.transform(zs_for_scaler, concat_ene)\n\n# ACSF parameters\nn_basis = 16\nr_min = 0.8\nr_cut = 3.0959454963762645\ntau = 1.7612032005732925\neta = 4 * np.log(tau) * ((n_basis-1)/(r_cut - r_min))**2\nzeta = - np.log(tau) / (2*np.log(np.cos(np.pi/(4*n_basis-4))))\n\nacsf_params={\"nRs2\":n_basis, \"nRs3\":n_basis, \"nTs\":n_basis, \"rcut\":r_cut, \"acut\":r_cut, \"zeta\":zeta, \"eta\":eta}\n\n# Generate estimator\nestimator = ARMP(iterations=900, l1_reg=0.00018891702136509527, l2_reg=2.172308772374847e-08, learning_rate=0.001471842348676605, representation_name='acsf', representation_params=acsf_params, tensorboard=True, store_frequency=10, tensorboard_subdir=\"../outputs/hc6sq_train_001/tensorboard\", hidden_layer_sizes=(62,142,), batch_size=23)\n\nestimator.set_properties(concat_ene_scaled)\nestimator.generate_representation(concat_xyz, concat_zs, method='fortran')\n\n# Training and testing\nidx_training = list(range(len(concat_ene_scaled)))\nshuffle(idx_training)\n\nestimator.fit(idx_training)\n\nestimator.save_nn(\"../outputs/hc6sq_train_001/saved_model\")\n","sub_path":"inputs/hc6sq_train_001.py","file_name":"hc6sq_train_001.py","file_ext":"py","file_size_in_byte":5811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"415504715","text":"# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0\n# For details: https://github.com/gaogaotiantian/viztracer/blob/master/NOTICE.txt\n\ntry:\n import orjson as json # type: ignore\nexcept ImportError:\n import json # type: ignore\nimport bisect\nimport os\n\nfrom . import __version__\nfrom .functree import FuncTree\nfrom .util import color_print\n\n\nclass Frame:\n def __init__(self, parent, node):\n self.parent = parent\n self.node = node\n self.curr_children_idx = 0\n self.next = None\n self.code_string = None\n if parent:\n parent.next = self\n\n @property\n def curr_children_idx(self):\n return self.__curr_children_idx\n\n @curr_children_idx.setter\n def curr_children_idx(self, idx):\n self.code_string = None\n self.__curr_children_idx = idx\n\n def show(self, p):\n if self.code_string:\n p(self.code_string)\n return\n\n node = self.node\n firstlineno = node.lineno\n if node.filename:\n if not os.path.exists(node.filename):\n p(\"> Not able to locate the source\")\n return\n\n with open(node.filename, encoding=\"utf-8\") as f:\n lst = f.readlines()\n\n start = firstlineno - 1\n line = lst[start]\n stripped_line = line.lstrip()\n code_indent = len(line) - len(stripped_line)\n\n if node.funcname != \"\":\n end = firstlineno\n indented = False\n while end < len(lst):\n line = lst[end]\n stripped_line = line.lstrip()\n indent = len(line) - len(stripped_line)\n if indent > code_indent:\n indented = True\n elif indented:\n if len(stripped_line) > 0 and \\\n not stripped_line.startswith(\"#\"):\n break\n end += 1\n\n # clear the ending spaces\n while lst[end - 1].strip() == \"\":\n end -= 1\n else:\n end = len(lst)\n\n if self.curr_children_idx >= len(self.node.children):\n currline = end\n else:\n currline = self.node.children[self.curr_children_idx].caller_lineno - 1\n\n for idx in range(start, end):\n if len(lst[idx].strip()) > 0:\n if idx == currline:\n lst[idx] = \"> \" + lst[idx]\n else:\n lst[idx] = \" \" + lst[idx]\n\n if currline == end:\n self.code_string = \"\".join(lst[start:end] + [\"> \\n\"])\n else:\n self.code_string = \"\".join(lst[start:end] + [\" \\n\"])\n else:\n self.code_string = \"> \" + self.node.fullname\n p(self.code_string)\n\n\nclass CounterEvents:\n def __init__(self):\n self._events = []\n\n def add_event(self, event):\n # The events have to be added in order\n if self._events:\n args = self._events[-1][\"args\"].copy()\n else:\n args = {}\n args.update(event[\"args\"])\n self._events.append({\n \"ts\": event[\"ts\"],\n \"args\": args\n })\n\n def normalize(self, first_ts):\n for event in self._events:\n event[\"ts\"] -= first_ts\n\n def get_args(self, ts):\n ts_lst = [event[\"ts\"] for event in self._events]\n idx = bisect.bisect(ts_lst, ts)\n if idx == 0:\n return {}\n else:\n return self._events[idx - 1][\"args\"]\n\n\nclass ObjectEvents:\n def __init__(self):\n self._objects = {}\n\n def add_event(self, event):\n if event[\"id\"] not in self._objects:\n entry = {\n \"id\": event[\"id\"],\n \"name\": event[\"name\"],\n \"snapshots\": [\n ]\n }\n self._objects[event[\"id\"]] = entry\n\n entry = self._objects[event[\"id\"]]\n\n if event[\"ph\"] in [\"N\", \"D\"]:\n entry[\"snapshots\"].append({\n \"ts\": event[\"ts\"],\n \"args\": None\n })\n elif event[\"ph\"] == \"O\":\n entry[\"snapshots\"].append({\n \"ts\": event[\"ts\"],\n \"args\": event[\"args\"][\"snapshot\"]\n })\n else: # pragma: no cover\n raise ValueError(\"Unexpected type for object event\")\n\n def normalize(self, first_ts):\n for entry in self._objects.values():\n for snapshot in entry[\"snapshots\"]:\n snapshot[\"ts\"] -= first_ts\n\n def get_args(self, ts):\n ret = {}\n for entry in self._objects.values():\n ts_lst = [snapshot[\"ts\"] for snapshot in entry[\"snapshots\"]]\n idx = bisect.bisect(ts_lst, ts)\n if idx != 0:\n snapshot = entry[\"snapshots\"][idx - 1]\n if snapshot[\"args\"] is not None:\n ret[entry[\"name\"]] = snapshot[\"args\"]\n return ret\n\n\nclass ProgSnapshot:\n compatible_version = \"0.9.5\"\n\n def __init__(self, json_string=None, p=print):\n self.func_trees = {}\n self.curr_node = None\n self.curr_frame = None\n self.first_tree = None\n self.curr_tree = None\n self.counter_events = CounterEvents()\n self.object_events = ObjectEvents()\n if json_string:\n if not self.load(json_string):\n self.valid = False\n return\n self.p = p\n self.valid = True\n\n def load(self, json_string):\n self.func_trees = {}\n raw_data = json.loads(json_string)\n if \"viztracer_metadata\" not in raw_data.keys():\n color_print(\"FAIL\", \"Error, json file version too old.\")\n return False\n else:\n if not self.check_version(raw_data[\"viztracer_metadata\"][\"version\"]):\n return False\n trace_events = raw_data[\"traceEvents\"]\n for event in trace_events:\n self.load_event(event)\n self.first_tree = min([tree for tree in self.get_trees()], key=lambda x: x.first_ts())\n first_ts = self.first_tree.first_ts()\n self.curr_tree = self.first_tree\n self.curr_frame = Frame(None, self.first_tree.first_node())\n for tree in self.get_trees():\n tree.normalize(first_ts)\n self.counter_events.normalize(first_ts)\n self.object_events.normalize(first_ts)\n return True\n\n def load_event(self, event):\n # event is a chrome trace format event object\n try:\n ph = event[\"ph\"]\n pid = event[\"pid\"]\n tid = event[\"tid\"]\n except Exception:\n raise ValueError(\"Error when loading event data: {}\", event)\n\n if ph == \"X\":\n if pid not in self.func_trees:\n self.func_trees[pid] = {}\n if tid not in self.func_trees[pid]:\n self.func_trees[pid][tid] = FuncTree(pid, tid)\n\n self.func_trees[pid][tid].add_event(event)\n elif ph == \"C\":\n self.counter_events.add_event(event)\n elif ph in [\"N\", \"D\", \"O\"]:\n self.object_events.add_event(event)\n elif ph == \"M\":\n return\n else:\n print(\"Unsupported event type: {}\".format(ph))\n return\n\n def check_version(self, version):\n def get_version_tuple(v):\n return tuple([int(elem) for elem in v.split(\".\")])\n if get_version_tuple(version) < get_version_tuple(self.compatible_version):\n color_print(\"FAIL\", \"Error, json file version too old.\")\n return False\n elif get_version_tuple(version) > get_version_tuple(__version__):\n color_print(\"WARNING\", \"Warning, json file version is newer than vdb! Not sure if it's compatible\")\n return True\n\n def get_trees(self):\n for pid in self.func_trees:\n for tid in self.func_trees[pid]:\n yield self.func_trees[pid][tid]\n return\n\n def show(self):\n self.curr_frame.show(self.p)\n\n def up(self):\n # Inspect previous frame\n if not self.curr_frame.parent:\n return False, \"No outer frame anymore\"\n self.curr_frame = self.curr_frame.parent\n return True, None\n\n def down(self):\n if not self.curr_frame.next:\n return False, \"Already at current frame\"\n self.curr_frame = self.curr_frame.next\n return True, None\n\n def _goto_inner_frame(self):\n while self.curr_frame.next:\n self.curr_frame = self.curr_frame.next\n\n def step(self):\n self._goto_inner_frame()\n curr_frame = self.curr_frame\n if curr_frame.curr_children_idx < len(curr_frame.node.children):\n child = curr_frame.node.children[curr_frame.curr_children_idx]\n new_frame = Frame(curr_frame, child)\n self.curr_frame = new_frame\n else:\n # go out of the function\n success, _ = self.func_return()\n if not success:\n return False, \"at the end of the trace\"\n return True, None\n\n def step_back(self):\n self._goto_inner_frame()\n curr_frame = self.curr_frame\n if curr_frame.curr_children_idx > 0:\n curr_frame.curr_children_idx -= 1\n child = curr_frame.node.children[curr_frame.curr_children_idx]\n new_frame = Frame(curr_frame, child)\n new_frame.curr_children_idx = len(new_frame.node.children)\n self.curr_frame = new_frame\n else:\n # go out of the function\n success, _ = self.func_return_back()\n if not success:\n return False, \"at the beginning of the trace\"\n return True, None\n\n def next(self):\n self._goto_inner_frame()\n curr_frame = self.curr_frame\n if curr_frame.curr_children_idx < len(curr_frame.node.children):\n curr_frame.curr_children_idx += 1\n else:\n # go out of the function\n success, _ = self.func_return()\n if not success:\n return False, \"at the end of the trace\"\n return True, None\n\n def next_back(self):\n self._goto_inner_frame()\n curr_frame = self.curr_frame\n if curr_frame.curr_children_idx > 0:\n curr_frame.curr_children_idx -= 1\n else:\n # go out of the function\n success, _ = self.func_return_back()\n if not success:\n return False, \"at the beginning of the trace\"\n return True, None\n\n def func_return(self):\n self._goto_inner_frame()\n curr_frame = self.curr_frame\n if not curr_frame.parent:\n # Check if there's a sibling\n node = curr_frame.node\n idx = node.parent.children.index(node)\n if idx < len(node.parent.children) - 1:\n self.curr_frame = Frame(None, node.parent.children[idx + 1])\n return True, None\n return False, \"No callers available\"\n curr_frame = curr_frame.parent\n curr_frame.curr_children_idx += 1\n curr_frame.next = None\n self.curr_frame = curr_frame\n\n return True, None\n\n def func_return_back(self):\n self._goto_inner_frame()\n curr_frame = self.curr_frame\n if not curr_frame.parent:\n # Check if there's a sibling\n node = curr_frame.node\n idx = node.parent.children.index(node)\n if idx > 0:\n self.curr_frame = Frame(None, node.parent.children[idx - 1])\n return True, None\n return False, \"No callers available\"\n curr_frame = curr_frame.parent\n curr_frame.next = None\n self.curr_frame = curr_frame\n\n return True, None\n\n def where(self):\n tmp_frame = self.curr_frame\n while tmp_frame.parent:\n tmp_frame = tmp_frame.parent\n while True:\n if tmp_frame == self.curr_frame:\n self.p(\"> \" + tmp_frame.node.fullname)\n else:\n self.p(\" \" + tmp_frame.node.fullname)\n if tmp_frame.next:\n tmp_frame = tmp_frame.next\n else:\n break\n\n return True, None\n\n def goto_timestamp(self, ts):\n frame = Frame(None, self.curr_tree.node_by_timestamp(ts))\n while True:\n if frame.node.children:\n starts = [child.start for child in frame.node.children]\n idx = bisect.bisect_left(starts, ts)\n if idx == 0:\n frame.curr_children_idx = 0\n break\n else:\n idx -= 1\n if frame.node.children[idx].end <= ts:\n # here's what we need!\n frame.curr_children_idx = idx + 1\n break\n else:\n new_frame = Frame(frame, frame.node.children[idx])\n frame = new_frame\n else:\n break\n self.curr_frame = frame\n\n return True, None\n\n def get_timestamp(self):\n tmp_frame = self.curr_frame\n while tmp_frame.next:\n tmp_frame = tmp_frame.next\n if not tmp_frame.node.children:\n return tmp_frame.node.start\n if tmp_frame.curr_children_idx >= len(tmp_frame.node.children):\n return tmp_frame.node.children[-1].end\n else:\n return tmp_frame.node.children[tmp_frame.curr_children_idx].start\n\n def print_timestamp(self):\n self.p(str(self.get_timestamp()))\n\n return True, None\n\n def print_counter(self):\n self.p(str(self.counter_events.get_args(self.get_timestamp())))\n\n return True, None\n\n def print_object(self):\n object_dict = self.object_events.get_args(self.get_timestamp())\n for k, v in object_dict.items():\n self.p(str(k) + \":\")\n self.p(str(v))\n\n return True, None\n\n def list_tid(self):\n curr_tree = self.curr_tree\n forest = self.func_trees[curr_tree.pid]\n for tid in forest:\n if tid == curr_tree.tid:\n self.p(\"> {}\".format(tid))\n else:\n self.p(\" {}\".format(tid))\n\n return True, None\n\n def list_pid(self):\n curr_tree = self.curr_tree\n for pid in self.func_trees:\n if pid == curr_tree.pid:\n self.p(\"> {}\".format(pid))\n else:\n self.p(\" {}\".format(pid))\n\n return True, None\n\n def goto_tid(self, tid):\n assert(type(tid) is int)\n forest = self.func_trees[self.curr_tree.pid]\n if tid not in forest:\n return False, \"No such tid\"\n else:\n ts = self.get_timestamp()\n self.curr_tree = forest[tid]\n self.goto_timestamp(ts)\n\n return True, None\n\n def goto_pid(self, pid):\n assert(type(pid) is int)\n if pid not in self.func_trees:\n return False, \"No such pid\"\n else:\n ts = self.get_timestamp()\n forest = self.func_trees[pid]\n for tid in forest:\n self.curr_tree = forest[tid]\n break\n self.goto_timestamp(ts)\n\n return True, None\n\n def print_args(self):\n self.p(str(self.curr_frame.node.event.get(\"args\", \"\")))\n\n return True, None\n","sub_path":"src/viztracer/prog_snapshot.py","file_name":"prog_snapshot.py","file_ext":"py","file_size_in_byte":15532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"179794480","text":"from django.conf.urls import url,include\nfrom .views import *\n\nadminpatterns =[\n\n\t]\napp_name=\"jaga\"\nurlpatterns = [\n url(r'',include(adminpatterns)),\n url(r'^home/$',index,name='index'),\n url(r'^aboutme/$',aboutme,name='aboutme'),\n\n]\n","sub_path":"scr/image/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"564931593","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport pandas as pd\nimport tensorflow as tf\nimport json\nimport os\n\nfrom lib.utils import get_logger\nfrom lib import preprocessing2 as prep\nfrom model.mgrnn_supervisor_all import MGRNNSupervisor\n\n# flags\nflags = tf.app.flags\nFLAGS = flags.FLAGS\n\nflags.DEFINE_integer('batch_size', 20, 'Batch size')\nflags.DEFINE_integer('cl_decay_steps', 100,\n 'Parameter to control the decay speed of probability of feeding groundth instead of model output.')\nflags.DEFINE_integer('epochs', 200, 'Maximum number of epochs to train.')\nflags.DEFINE_string('filter_type', 'laplacian', 'laplacian/random_walk/dual_random_walk.')\nflags.DEFINE_string('activate_func', 'tanh', 'tanh/sigmoid/relu.')\n\nflags.DEFINE_string('pool_type', '_mpool', '_mpool/_apool.')\nflags.DEFINE_integer('horizon', 1, 'Maximum number of timestamps to prediction.')\nflags.DEFINE_float('l1_decay', -1.0, 'L1 Regularization')\nflags.DEFINE_float('lr_decay', -1.0, 'Learning rate decay.')\nflags.DEFINE_integer('lr_decay_epoch', -1, 'The epoch that starting decaying the parameter.')\nflags.DEFINE_integer('lr_decay_interval', -1, 'Interval beteween each deacy.')\nflags.DEFINE_float('learning_rate', 0.001, 'Learning rate. -1: select by hyperopt tuning.')\nflags.DEFINE_float('drop_out', 0.0, 'drop_out 0.0: select by hyperopt tuning.')\nflags.DEFINE_bool('shuffle_training', False, 'shuffle_training False: select by hyperopt tuning.')\nflags.DEFINE_string('log_dir', None, 'Log directory for restoring the model from a checkpoint.')\nflags.DEFINE_string('loss_func', 'L2Norm', 'KL/L2/EMD: loss function.')\nflags.DEFINE_string('optimizer', 'adam', 'adam/sgd/ada.')\nflags.DEFINE_float('min_learning_rate', -1, 'Minimum learning rate')\nflags.DEFINE_integer('nb_weeks', 17, 'How many week\\'s data should be used for train/test.')\nflags.DEFINE_integer('patience', -1,\n 'Maximum number of epochs allowed for non-improving validation error before early stopping.')\nflags.DEFINE_integer('seq_len', 3, 'Sequence length.')\nflags.DEFINE_integer('test_every_n_epochs', 10, 'Run model on the testing dataset every n epochs.')\nflags.DEFINE_bool('coarsen', True, 'Apply coarsen on input data.')\nflags.DEFINE_integer('coarsening_levels', 4, 'Number of coarsened graph.')\nflags.DEFINE_integer('num_gpus', 2, 'How many GPUs to use.')\nflags.DEFINE_bool('use_cpu_only', False, 'Set to true to only use cpu.')\nflags.DEFINE_bool('use_curriculum_learning', None, 'Set to true to use Curriculum learning in decoding stage.')\nflags.DEFINE_integer('verbose', -1, '1: to log individual sensor information.')\n\n# flags for data related\nflags.DEFINE_string('server_name', 'nyc', 'The name of dataset to be processed')\nflags.DEFINE_string('borough', 'Manhattan', 'Selected area')\nflags.DEFINE_string('zone', 'taxi_zone', 'map partition method')\nflags.DEFINE_integer('sample_rate', 20, 'Sample rate to condense the data')\nflags.DEFINE_string('mode', 'hist', 'avg: for single value, hist: for multi values')\nflags.DEFINE_string('data_format', 'speed', 'speed or duration')\nflags.DEFINE_bool('duration_log', False, 'Apply log10 to the data, True when data_form is duration')\nflags.DEFINE_bool('fill_mean', False, 'Fill HA to the data, True when need to fill in mean values')\nflags.DEFINE_bool('sparse_removal', False, 'Apply sparse removal to the data, True when need to remove sparse regions')\nflags.DEFINE_string('scaler', 'maxmin', 'maxmin: MaxMinScaler, std: Standard scaler')\n\nflags.DEFINE_string('config_filename', './conf/base_config.json', 'Configuration filename for restoring the model.')\nflags.DEFINE_string('graph_pkl_filename', 'data/sensor_graph/adj_mx.pkl',\n 'Pickle file containing: sensor_ids, sensor_id_to_ind_map, dist_matrix')\nflags.DEFINE_string('traffic_df_filename', 'data/df_highway_2012_4mon_sample.h5',\n 'Path to hdf5 pandas.DataFrame.')\nflags.DEFINE_string('model_filename', None, 'model file name to restore.')\nflags.DEFINE_string('model_dir', None, 'model dir to restore.')\n# flags for the graph construction\nflags.DEFINE_integer('hopk', 4, 'Hopk to construct the adjacent matrix')\nflags.DEFINE_integer('sigma', 12, 'sigma used to construct the adj matrix')\n\nflags.DEFINE_float('trace_ratio', 0.0001, 'Trace ratio in loss')\nflags.DEFINE_bool('is_restore', False, 'Whether in training or test model directly')\n\ndef main(_):\n # Reads graph data.\n with open(FLAGS.config_filename) as f:\n # load configuration\n data_model_config = json.load(f)\n data_config = data_model_config['data']\n # load data: include graph and data array\n for name in ['server_name', 'hopk', 'sigma', 'mode', 'zone', 'coarsen',\n 'coarsening_levels', 'borough', 'data_format', 'duration_log',\n 'sample_rate']:\n data_config[name] = getattr(FLAGS, name)\n data_config['window_size'] = getattr(FLAGS, 'seq_len')\n data_config['predict_size'] = getattr(FLAGS, 'horizon')\n data_config['base_dir'] = os.path.join(data_config['base_dir'],\n data_config['server_name'],\n data_config['borough'],\n data_config['zone'])\n data_config['data_dir'] = os.path.join(data_config['base_dir'],\n 'S{}'.format(data_config['sample_rate']),\n data_config['data_format'],\n data_config['mode'],\n 'W{}_P{}'.format(data_config['window_size'],\n data_config['predict_size']),\n 'rm{}'.format(data_config['data_rm_ratio'])\n )\n logger = get_logger('./logs/', 'info.log')\n\n logger.info('Loading graph...')\n dataset = prep.NYCData(**data_config)\n logger.info('Loading graph tensor data with {} Mean-Fill...'.format(FLAGS.fill_mean))\n dataset_f = dataset.gcnn_lstm_data_construction(sparse_removal=FLAGS.sparse_removal)\n adj_mx = dataset.adj_matrix\n dist_mx = dataset.dist_matrix\n logger.info('Construct model and train...')\n nodes = dataset.nodes\n print(\"Number of edges is \", len(nodes))\n print(\"Shape of adjacency matrix is \", adj_mx.shape)\n supervisor_config = data_model_config['model']\n supervisor_config['output_dim'] = dataset.output_dim\n supervisor_config['start_date'] = data_config['start_date']\n # setting for training\n supervisor_config['use_cpu_only'] = FLAGS.use_cpu_only\n if FLAGS.log_dir:\n supervisor_config['log_dir'] = FLAGS.log_dir\n if FLAGS.use_curriculum_learning is not None:\n supervisor_config['use_curriculum_learning'] = FLAGS.use_curriculum_learning\n if FLAGS.loss_func:\n supervisor_config['loss_func'] = FLAGS.loss_func\n if FLAGS.filter_type:\n supervisor_config['filter_type'] = FLAGS.filter_type\n # Overwrites space with specified parameters.\n for name in ['batch_size', 'cl_decay_steps', 'epochs', 'horizon', 'learning_rate', 'l1_decay',\n 'lr_decay', 'lr_decay_epoch', 'lr_decay_interval', 'sample_rate', 'min_learning_rate',\n 'patience', 'seq_len', 'test_every_n_epochs', 'verbose', 'coarsen', 'coarsening_levels',\n 'zone', 'scaler', 'data_format', 'num_gpus', 'mode', 'fill_mean', 'activate_func',\n 'hopk', 'sigma', 'drop_out', 'shuffle_training', 'optimizer', 'pool_type',\n 'trace_ratio']:\n if type(getattr(FLAGS, name)) == str or getattr(FLAGS, name) >= 0:\n supervisor_config[name] = getattr(FLAGS, name)\n\n tf_config = tf.ConfigProto(allow_soft_placement=True)\n if FLAGS.use_cpu_only:\n tf_config = tf.ConfigProto(device_count={'GPU': 0})\n tf_config.gpu_options.allow_growth = True\n with tf.Session(config=tf_config) as sess:\n supervisor = MGRNNSupervisor(traffic_reading_df=dataset_f, adj_mx=adj_mx,\n config=supervisor_config,\n origin_df_file=dataset.origin_df_file,\n nodes=nodes,\n coarsed_dict=dataset.coarsed_dict)\n if not FLAGS.is_restore:\n supervisor.train(sess=sess)\n else:\n supervisor.test_and_write_results(\n sess=sess, model_filename=FLAGS.model_filename,\n model_dir=FLAGS.model_dir, dist_mx=dist_mx)\n\n\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"mura_train_hist.py","file_name":"mura_train_hist.py","file_ext":"py","file_size_in_byte":8966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"134169555","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport tensorflow as tf\n# Fetch\ninput1 = tf.constant(3.0)\ninput2 = tf.constant(2.0)\ninput3 = tf.constant(5.0)\n\nadd = tf.add(input2, input3)\nmul = tf.multiply(input1,add)\n\nwith tf.Session() as sess:\n # Fetch: run multiple operation \n result = sess.run([mul,add])\n print(result)\n\n\n# In[3]:\n\n\n# Feed: feed data when running \ninput1 = tf.placeholder(tf.float32)\ninput2 = tf.placeholder(tf.float32)\noutput = tf.multiply(input1,input2)\n\nwith tf.Session() as sess:\n print(sess.run(output, feed_dict={input1:[7.0],input2:[2.0]}))\n \n\n","sub_path":"src/02_3_fetch_feed.py","file_name":"02_3_fetch_feed.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"596864799","text":"#!/usr/bin/python\n\nimport time\nfrom Adafruit_I2C import Adafruit_I2C\nimport logging\n\n\n# ===========================================================================\n# BMP085 Class\n# ===========================================================================\n\nclass BMP085:\n i2c = None # type: Adafruit_I2C\n\n # Operating Modes\n __BMP085_ULTRALOWPOWER = 0\n __BMP085_STANDARD = 1\n __BMP085_HIGHRES = 2\n __BMP085_ULTRAHIGHRES = 3\n\n # BMP085 Registers\n __BMP085_CAL_AC1 = 0xAA # R Calibration data (16 bits)\n __BMP085_CAL_AC2 = 0xAC # R Calibration data (16 bits)\n __BMP085_CAL_AC3 = 0xAE # R Calibration data (16 bits)\n __BMP085_CAL_AC4 = 0xB0 # R Calibration data (16 bits)\n __BMP085_CAL_AC5 = 0xB2 # R Calibration data (16 bits)\n __BMP085_CAL_AC6 = 0xB4 # R Calibration data (16 bits)\n __BMP085_CAL_B1 = 0xB6 # R Calibration data (16 bits)\n __BMP085_CAL_B2 = 0xB8 # R Calibration data (16 bits)\n __BMP085_CAL_MB = 0xBA # R Calibration data (16 bits)\n __BMP085_CAL_MC = 0xBC # R Calibration data (16 bits)\n __BMP085_CAL_MD = 0xBE # R Calibration data (16 bits)\n __BMP085_CONTROL = 0xF4\n __BMP085_TEMPDATA = 0xF6\n __BMP085_PRESSUREDATA = 0xF6\n __BMP085_READTEMPCMD = 0x2E\n __BMP085_READPRESSURECMD = 0x34\n\n # Private Fields\n _cal_AC1 = 0\n _cal_AC2 = 0\n _cal_AC3 = 0\n _cal_AC4 = 0\n _cal_AC5 = 0\n _cal_AC6 = 0\n _cal_B1 = 0\n _cal_B2 = 0\n _cal_MB = 0\n _cal_MC = 0\n _cal_MD = 0\n\n def __init__(self, address: int=0x77, mode: int=1, debug: bool=False) -> None:\n self.i2c = Adafruit_I2C(address)\n\n self.address = address\n self.debug = debug\n\n # Make sure the specified mode is in the appropriate range\n if mode < 0 or mode > 3:\n if self.debug:\n logger = logging.getLogger(__name__)\n logger.debug(\"Invalid Mode: Using STANDARD by default\")\n self.mode = self.__BMP085_STANDARD\n else:\n self.mode = mode\n\n self.read_calibration_data()\n\n def read_s16(self, register: int) -> int:\n \"Reads a signed 16-bit value\"\n hi = self.i2c.readS8(register)\n lo = self.i2c.readU8(register+1)\n return (hi << 8) + lo\n\n def read_u16(self, register: int) -> int:\n \"Reads an unsigned 16-bit value\"\n hi = self.i2c.readU8(register)\n lo = self.i2c.readU8(register+1)\n return (hi << 8) + lo\n\n def read_calibration_data(self) -> None:\n \"Reads the calibration data from the IC\"\n self._cal_AC1 = self.read_s16(self.__BMP085_CAL_AC1) # INT16\n self._cal_AC2 = self.read_s16(self.__BMP085_CAL_AC2) # INT16\n self._cal_AC3 = self.read_s16(self.__BMP085_CAL_AC3) # INT16\n self._cal_AC4 = self.read_u16(self.__BMP085_CAL_AC4) # UINT16\n self._cal_AC5 = self.read_u16(self.__BMP085_CAL_AC5) # UINT16\n self._cal_AC6 = self.read_u16(self.__BMP085_CAL_AC6) # UINT16\n self._cal_B1 = self.read_s16(self.__BMP085_CAL_B1) # INT16\n self._cal_B2 = self.read_s16(self.__BMP085_CAL_B2) # INT16\n self._cal_MB = self.read_s16(self.__BMP085_CAL_MB) # INT16\n self._cal_MC = self.read_s16(self.__BMP085_CAL_MC) # INT16\n self._cal_MD = self.read_s16(self.__BMP085_CAL_MD) # INT16\n if self.debug:\n self.show_calibration_data()\n\n def show_calibration_data(self) -> None:\n \"Displays the calibration values for debugging purposes\"\n logger = logging.getLogger(__name__)\n logger.debug(\"DBG: AC1 = %6d\" % (self._cal_AC1))\n logger.debug(\"DBG: AC2 = %6d\" % (self._cal_AC2))\n logger.debug(\"DBG: AC3 = %6d\" % (self._cal_AC3))\n logger.debug(\"DBG: AC4 = %6d\" % (self._cal_AC4))\n logger.debug(\"DBG: AC5 = %6d\" % (self._cal_AC5))\n logger.debug(\"DBG: AC6 = %6d\" % (self._cal_AC6))\n logger.debug(\"DBG: B1 = %6d\" % (self._cal_B1))\n logger.debug(\"DBG: B2 = %6d\" % (self._cal_B2))\n logger.debug(\"DBG: MB = %6d\" % (self._cal_MB))\n logger.debug(\"DBG: MC = %6d\" % (self._cal_MC))\n logger.debug(\"DBG: MD = %6d\" % (self._cal_MD))\n\n def read_raw_temperature(self) -> int:\n \"Reads the raw (uncompensated) temperature from the sensor\"\n self.i2c.write8(self.__BMP085_CONTROL, self.__BMP085_READTEMPCMD)\n time.sleep(0.005) # Wait 5ms\n raw = self.read_u16(self.__BMP085_TEMPDATA)\n if self.debug:\n logger = logging.getLogger(__name__)\n logger.debug(\"DBG: Raw Temp: 0x%04X (%d)\" % (raw & 0xFFFF, raw))\n return raw\n\n def read_raw_pressure(self) -> int:\n \"Reads the raw (uncompensated) pressure level from the sensor\"\n self.i2c.write8(self.__BMP085_CONTROL, self.__BMP085_READPRESSURECMD + (self.mode << 6))\n if self.mode == self.__BMP085_ULTRALOWPOWER:\n time.sleep(0.005)\n elif self.mode == self.__BMP085_HIGHRES:\n time.sleep(0.014)\n elif self.mode == self.__BMP085_ULTRAHIGHRES:\n time.sleep(0.026)\n else:\n time.sleep(0.008)\n msb = self.i2c.readU8(self.__BMP085_PRESSUREDATA)\n lsb = self.i2c.readU8(self.__BMP085_PRESSUREDATA+1)\n xlsb = self.i2c.readU8(self.__BMP085_PRESSUREDATA+2)\n raw = ((msb << 16) + (lsb << 8) + xlsb) >> (8 - self.mode)\n if self.debug:\n logger = logging.getLogger(__name__)\n logger.debug(\"DBG: Raw Pressure: 0x%04X (%d)\" % (raw & 0xFFFF, raw))\n return raw\n\n def read_temperature(self) -> float:\n \"Gets the compensated temperature in degrees celcius\"\n UT = 0\n X1 = 0\n X2 = 0\n B5 = 0\n temp = 0.0\n\n # Read raw temp before aligning it with the calibration values\n UT = self.read_raw_temperature()\n X1 = ((UT - self._cal_AC6) * self._cal_AC5) >> 15\n X2 = (self._cal_MC << 11) // (X1 + self._cal_MD)\n B5 = X1 + X2\n temp = ((B5 + 8) >> 4) / 10.0\n if self.debug:\n logger = logging.getLogger(__name__)\n logger.debug(\"DBG: Calibrated temperature = %f C\" % temp)\n return temp\n\n def read_pressure(self) -> float:\n \"Gets the compensated pressure in pascal\"\n UT = 0\n UP = 0\n B3 = 0\n B5 = 0\n B6 = 0\n X1 = 0\n X2 = 0\n X3 = 0\n p = 0\n B4 = 0\n B7 = 0\n\n UT = self.read_raw_temperature()\n UP = self.read_raw_pressure()\n\n # You can use the datasheet values to test the conversion results\n # dsValues = True\n dsValues = False\n\n if dsValues:\n UT = 27898\n UP = 23843\n self._cal_AC6 = 23153\n self._cal_AC5 = 32757\n self._cal_MB = -32768\n self._cal_MC = -8711\n self._cal_MD = 2868\n self._cal_B1 = 6190\n self._cal_B2 = 4\n self._cal_AC3 = -14383\n self._cal_AC2 = -72\n self._cal_AC1 = 408\n self._cal_AC4 = 32741\n self.mode = self.__BMP085_ULTRALOWPOWER\n if self.debug:\n self.show_calibration_data()\n\n # True Temperature Calculations\n X1 = ((UT - self._cal_AC6) * self._cal_AC5) >> 15\n X2 = (self._cal_MC << 11) // (X1 + self._cal_MD)\n B5 = X1 + X2\n if self.debug:\n logger = logging.getLogger(__name__)\n logger.debug(\"DBG: X1 = %d\" % (X1))\n logger.debug(\"DBG: X2 = %d\" % (X2))\n logger.debug(\"DBG: B5 = %d\" % (B5))\n logger.debug(\"DBG: True Temperature = %.2f C\" % (((B5 + 8) >> 4) / 10.0))\n\n # Pressure Calculations\n B6 = B5 - 4000\n X1 = (self._cal_B2 * (B6 * B6) >> 12) >> 11\n X2 = (self._cal_AC2 * B6) >> 11\n X3 = X1 + X2\n B3 = (((self._cal_AC1 * 4 + X3) << self.mode) + 2) // 4\n if self.debug:\n logger = logging.getLogger(__name__)\n logger.debug(\"DBG: B6 = %d\" % (B6))\n logger.debug(\"DBG: X1 = %d\" % (X1))\n logger.debug(\"DBG: X2 = %d\" % (X2))\n logger.debug(\"DBG: X3 = %d\" % (X3))\n logger.debug(\"DBG: B3 = %d\" % (B3))\n\n X1 = (self._cal_AC3 * B6) >> 13\n X2 = (self._cal_B1 * ((B6 * B6) >> 12)) >> 16\n X3 = ((X1 + X2) + 2) >> 2\n B4 = (self._cal_AC4 * (X3 + 32768)) >> 15\n B7 = (UP - B3) * (50000 >> self.mode)\n if self.debug:\n logger = logging.getLogger(__name__)\n logger.debug(\"DBG: X1 = %d\" % (X1))\n logger.debug(\"DBG: X2 = %d\" % (X2))\n logger.debug(\"DBG: X3 = %d\" % (X3))\n logger.debug(\"DBG: B4 = %d\" % (B4))\n logger.debug(\"DBG: B7 = %d\" % (B7))\n\n if (B7 < 0x80000000):\n p = (B7 * 2) // B4\n else:\n p = (B7 // B4) * 2\n\n if self.debug:\n logger = logging.getLogger(__name__)\n logger.debug(\"DBG: X1 = %d\" % (X1))\n\n X1 = (p >> 8) * (p >> 8)\n X1 = (X1 * 3038) >> 16\n X2 = (-7357 * p) >> 16\n if self.debug:\n logger = logging.getLogger(__name__)\n logger.debug(\"DBG: p = %d\" % (p))\n logger.debug(\"DBG: X1 = %d\" % (X1))\n logger.debug(\"DBG: X2 = %d\" % (X2))\n\n p = p + ((X1 + X2 + 3791) >> 4)\n if self.debug:\n logger = logging.getLogger(__name__)\n logger.debug(\"DBG: Pressure = %d Pa\" % (p))\n\n return float(p)\n\n def read_altitude(self, sea_level_pressure: float=101325) -> float:\n \"Calculates the altitude in meters\"\n altitude = 0.0\n pressure = float(self.read_pressure())\n altitude = 44330.0 * (1.0 - pow(pressure / sea_level_pressure, 0.1903))\n if self.debug:\n logger = logging.getLogger(__name__)\n logger.debug(\"DBG: Altitude = %d\" % (altitude))\n return altitude\n","sub_path":"sensors/Adafruit_BMP085.py","file_name":"Adafruit_BMP085.py","file_ext":"py","file_size_in_byte":9887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"419522918","text":"\"\"\"Monkey and Banana Example.\n2010, Tobias Kuester\n\nA Planning Problem with a (relatively) large number of different actions to\nchoose from. Monkey wants Banana. Ook!\n\"\"\"\n\nfrom knowledge import *\nfrom reasoning import *\nfrom planning import *\n\n\n# define shortcuts for expressing common beliefs\nMonkey = lambda subj: Belief(\"Monkey\", subj)\nBanana = lambda subj: Belief(\"Banana\", subj)\nCrate = lambda subj: Belief(\"Crate\", subj)\nRoom = lambda subj: Belief(\"Room\", subj)\nAt = lambda subj, obj: Belief(\"at\", subj, obj)\nHas = lambda subj, obj: Belief(\"has\", subj, obj)\nLow = lambda subj: Belief(\"low\", subj)\nHigh = lambda subj: Belief(\"high\", subj)\nHappy = lambda subj: Belief(\"happy\", subj)\n\n\n# define shortcuts for some variables\nx, y, z, _ = \"x\", \"y\", \"z\", \"*\"\n\n\n# define available actions\ngo_to = Action(\"Go To\",\n\t\t\t\t\tpre=And(Monkey(x), At(x, y), Low(x), Room(z)),\n\t\t\t\t\teff=And(At(x, z), Not(At(x, y))))\ntake = Action(\"Take\",\n\t\t\t\t\tpre=And(Monkey(x), At(x, y), At(z, y), \n\t\t\t\t\t Or(And(Low(x), Low(z)), And(High(x), High(z)))),\n\t\t\t\t\teff=And(Has(x, z), Not(And(At(z, y), High(z), Low(z)))))\ndrop = Action(\"Drop\",\n\t\t\t\t\tpre=And(Monkey(x), At(x, y), Has(x, z)),\n\t\t\t\t\teff=And(At(z, y), Low(z), Not(Has(x, z))))\nclimb_up = Action(\"Climb Up\",\n\t\t\t\t\tpre=And(Monkey(x), Crate(z), At(x, y), At(z, y), Low(x)),\n\t\t\t\t\teff=And(High(x), Not(Low(x))))\nclimb_down = Action(\"Climb Down\",\n\t\t\t\t\tpre=And(Monkey(x), Crate(z), At(x, y), At(z, y), High(x)),\n\t\t\t\t\teff=And(Low(x), Not(High(x))))\neat = Action(\"Eat\",\n\t\t\t\t\tpre=And(Monkey(x), Banana(y), Has(x, y)),\n\t\t\t\t\teff=And(Happy(x), Not(Has(x, y))))\nactions = [go_to, take, drop, climb_up, climb_down, eat]\n\n\nif __name__ == \"__main__\":\n\n\tfrom test import *\n\n\t# abbreviations for objects\n\tM, B, C, R1, R2, R3 = \"Monkey\", \"Banana\", \"Crate\", \"Room 1\", \"Room 2\", \"Room 3\"\n\n\t# create initial beliefs\n\tbeliefs = (\n\t\tMonkey(M), Banana(B), Crate(C),\n\t\tLow(M), Low(C), High(B),\n\t\tRoom(R1), Room(R2), Room(R3),\n\t\tAt(M, R1), At(B, R2), At(C, R3)\n\t)\n\tprint_all(\"Initial Beliefs\", beliefs)\n\t\n\t# Monkey wants Banana. Plan length 9\n\t# Iterative Deepening: 13498 steps, w/ pruning 289\n\t# Serial Decomposition: 1775 steps, w/ pruning 259\n\t# Breadth-First Search: ? steps, w/ pruning 30\n\t# SD-Breadth-First Search: ? steps, w/ pruning 23\n\tgoal = And(Happy(M), At(M, R1))\n\tplan = search_plan(goal, beliefs, actions, False, True)\n\tif plan != None:\n\t\tprint_all(\"Plan sequence for goal %s\" % goal, [ (a.name, m) for (a, m) in plan])\n\t\tfor (action, match) in plan:\n\t\t\tbeliefs = update(beliefs, action.eff, match)\n\t\tprint_all(\"After plan execution\", beliefs)\n\telse:\n\t\tprint(\"No Plan Sequence found for goal %s\" % goal)\n\n","sub_path":"Planner/banana.py","file_name":"banana.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"50173256","text":"import unittest, os\nfrom average_degree import AverageDegree\nfrom tweets_cleaned import CleanTweet\n\nclass TestCase(unittest.TestCase):\n\tdef setUp(self):\n\t\tself.clean_tweet = CleanTweet()\n\t\tself.avg_deg = AverageDegree()\n\t\tself.base_dir = \"/home/sesha/Interests/insightDataFella/coding-challenge/\"\n\n\tdef test_if_unicode_removed(self):\n\t\ttweet = \"Spark \\u009FSummit East this week! #Spark #Apache\"\n\t\tclean_tweet = \"Spark Summit East this week! #Spark #Apache\"\n\t\tself.failUnlessEqual(clean_tweet, self.clean_tweet.get_clean_tweet(tweet))\n\n\tdef test_if_unicode_spared(self):\n\t\t# Spare unicode between 0000 and 007F\n\t\ttweet = \"Spark \\u003cSummit East this week! #Spark #Apache\"\n\t\tclean_tweet = \"Spark .\n\"\"\"\nfrom glob import glob\nfrom json import load\nfrom os import path\nfrom time import time\n\nfrom gi.repository import Gio\n\nfrom src.const import CONFIG_FILE, DB_FOLDER, DESKTOP_ENV\nfrom src.enum import Action, ConversionTools\nfrom src.modules.log import Logger\nfrom src.modules.parser import Parser\nfrom src.modules.svg import *\nfrom src.modules.theme import Theme\nfrom src.utils import get_scaling_factor, progress, replace_to_6hex\n\n\nclass App:\n \"\"\"\n Main application.\n \"\"\"\n _args = None # Arguments Parser\n _config = None # Config file (json)\n _theme = None # Theme object\n _size = None # Icon size\n _scaling_factor = -1 # Scaling factor\n _action = None # Action.APPLY/Action.REVERT/Action.CLEAR_CACHE\n _only = [] # Fix only list of apps\n _path = None # App path to use with fix only\n _colors = [] # Colors\n _svgtopng = None\n\n _app = None # App Object\n\n def __init__(self, args):\n App._args = args\n\n @staticmethod\n def get_default(args=None):\n \"\"\"Return the default instance of App.\"\"\"\n if App._app is None:\n App._app = App(args)\n return App._app\n\n @staticmethod\n def get_supported_apps():\n \"\"\"Get a list of dict, a dict for each supported application.\"\"\"\n database_files = []\n if App.only():\n for db_file in App.only():\n db_file = \"{0}{1}.json\".format(DB_FOLDER, db_file)\n if path.exists(db_file):\n database_files.append(db_file)\n else:\n blacklist = App.config().get(\"blacklist\", [])\n files = glob(\"{0}*.json\".format(path.join(DB_FOLDER, \"\")))\n\n for file_ in files:\n if path.splitext(path.basename(file_))[0] not in blacklist:\n database_files.append(file_)\n\n database_files.sort()\n supported_apps = []\n\n for db_file in database_files:\n application_data = Parser(db_file)\n if application_data.is_installed():\n supported_apps.append(application_data.get_application())\n\n return supported_apps\n\n @staticmethod\n def execute(action):\n \"\"\"Fix Hardcoded Tray icons.\n Args:\n action(Action):\n APPLY: To apply the modifications\n REVERT: To revert it.\n CLEAR_CACHE : To clear backup files cache.\n \"\"\"\n apps = App.get_supported_apps()\n done = []\n total_time = 0\n if apps:\n cnt = 0\n counter_total = sum(app.parser.total_icons for app in apps)\n for app in apps:\n app_name = app.name\n start_time = time()\n\n if action == Action.APPLY:\n app.install()\n elif action == Action.REVERT:\n app.reinstall()\n elif action == Action.CLEAR_CACHE:\n app.clear_cache()\n\n delta = time() - start_time\n total_time += delta\n\n if app.is_done:\n cnt += app.parser.total_icons\n if app_name not in done:\n progress(cnt, counter_total, delta, app_name)\n done.append(app_name)\n else:\n counter_total -= app.parser.total_icons\n print(\"Failed to fix {0}\".format(app_name))\n\n print(\"Took {0}s to finish the tasks\".format(round(total_time, 2)))\n\n else:\n if action == Action.APPLY:\n exit(\"No apps to fix! Please report on GitHub if this is not the case\")\n else:\n exit(\"No apps to revert!\")\n\n @staticmethod\n def args():\n \"\"\"\n Application arguments\n \"\"\"\n return App._args\n\n @staticmethod\n def config():\n \"\"\"\n json config file content.\n \"\"\"\n if App._config is None:\n config = {}\n if path.isfile(CONFIG_FILE):\n with open(CONFIG_FILE, 'r') as data:\n try:\n config = load(data)\n except ValueError:\n Logger.warning(\n \"The config file is not a valid json file.\")\n App._config = config\n return App._config\n\n @staticmethod\n def svg():\n \"\"\"\n Return an instance of a conversion tool\n \"\"\"\n if App._svgtopng is None:\n conversion_tool = None\n # Read default config/arguments parser\n if App.args().conversion_tool:\n conversion_tool = App.args().conversion_tool\n elif App.config().get(\"conversion-tool\"):\n conversion_tool = App.config().get(\"conversion-tool\")\n\n if conversion_tool:\n try:\n App._svgtopng = globals()[conversion_tool](App.colors())\n except SVGNotInstalled:\n exit(\"The selected conversion tool is not installed.\")\n else:\n svgtool_found = False\n for conversion_tool in ConversionTools.choices():\n try:\n App._svgtopng = globals()[conversion_tool](\n App.colors())\n svgtool_found = True\n break\n except SVGNotInstalled:\n svgtool_found = False\n\n if not svgtool_found:\n raise SVGNotInstalled\n return App._svgtopng\n\n @staticmethod\n def icon_size():\n \"\"\"\n Return the icon size.\n \"\"\"\n if App._size is None:\n if App.args().size:\n App._size = App.args().size\n else:\n App._size = int(App.config().get(\"icons\", {}).get(\"size\", 0))\n if App._size not in [16, 22, 24]:\n if DESKTOP_ENV in (\"pantheon\", \"xfce\"):\n App._size = 24\n else:\n App._size = 22\n Logger.debug(\"Icon size in the config file is wrong.\"\n \"Falling back to the detected one...\")\n return App._size\n\n @staticmethod\n def scaling_factor():\n \"\"\"\n Returns the scaling factor.\n \"\"\"\n if App._scaling_factor == -1:\n scaling_factor = get_scaling_factor(DESKTOP_ENV)\n App._scaling_factor = scaling_factor\n if scaling_factor > 1:\n # Change icon size by * it by the scaling factor\n App._size = round(App.icon_size() * scaling_factor, 0)\n Logger.debug(\n \"Icon size was changed to : {0}\".format(App.icon_size()))\n return App._scaling_factor\n\n @staticmethod\n def theme(dark_theme=None):\n \"\"\"\n Theme instance.\n \"\"\"\n if App._theme is None:\n # If the theme was sepecified on args\n if App.args().theme:\n App._theme = Theme(App.args().theme)\n elif App.args().light_theme and App.args().dark_theme:\n App._theme = {\n \"dark\": Theme(App.args().dark_theme),\n \"light\": Theme(App.args().light_theme)\n }\n\n # Or on the config file\n elif App.config().get(\"icons\"):\n theme = App.config()[\"icons\"].get(\"theme\", {})\n if isinstance(theme, str):\n App._theme = Theme(theme)\n else:\n if theme.get(\"light\") and theme.get(\"dark\"):\n App._theme = {\n \"dark\": Theme(theme[\"dark\"]),\n \"light\": Theme(theme[\"light\"])\n }\n\n # Fallback to system theme\n if not App._theme:\n source = Gio.SettingsSchemaSource.get_default()\n if source.lookup(\"org.gnome.desktop.interface\", True):\n gsettings = Gio.Settings.new(\"org.gnome.desktop.interface\")\n theme_name = gsettings.get_string(\"icon-theme\")\n App._theme = Theme(theme_name)\n\n if dark_theme and isinstance(App._theme, dict):\n return App._theme[dark_theme]\n return App._theme\n\n @staticmethod\n def colors():\n \"\"\"\n List of colors to be replaced with new ones.\n \"\"\"\n if App.args().change_color and not App._colors:\n colors = []\n for color in App.args().change_color:\n color = color.strip().split(\" \")\n to_replace = replace_to_6hex(color[0])\n for_replace = replace_to_6hex(color[1])\n colors.append([to_replace, for_replace])\n App._colors = colors\n return App._colors\n\n @staticmethod\n def action():\n \"\"\"\n Which action should be done?\n \"\"\"\n if App._action is None:\n # Can't use apply and revert action on the same time\n if App.args().apply and App.args().revert:\n raise ValueError\n # Can't apply/revert and clear cache on the same time\n elif (App.args().apply or App.args().revert) and App.args().clear_cache:\n raise ValueError\n else:\n if App.args().apply:\n App._action = Action.APPLY\n elif App.args().revert:\n App._action = Action.REVERT\n elif App.args().clear_cache:\n App._action = Action.CLEAR_CACHE\n return App._action\n\n @staticmethod\n def only():\n \"\"\"\n List of applications to be fixed.\n \"\"\"\n if not App._only and App.args().only:\n only = App.args().only.lower().strip().split(\",\")\n for bfile in App.config().get(\"blacklist\", []):\n only.remove(bfile)\n App._only = only\n return App._only\n\n @staticmethod\n def path():\n \"\"\"\n The icons path, specified per application.\n \"\"\"\n if App.args().path and App.only():\n proposed_path = App.args().path\n if path.exists(proposed_path) and path.isdir(proposed_path):\n App._path = proposed_path\n else:\n raise FileNotFoundError(\"Please select a valid --path\")\n if len(App.only()) > 1 and App._path:\n exit(\"You can't use --path with more than application at once.\")\n return App._path\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":11612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"499808567","text":"#!/usr/bin/env python\nimport numpy as np\nimport pandas as pd\n\n# load the data\nif 'dataframe' not in globals():\n print('loading TYS.h5')\n dataframe = pd.read_hdf('TYS.h5', 'everything')\n print('total rows', len(dataframe))\n\n# delete the columns we aren't using\ndataframe = dataframe.drop(['wind_angle'], 1)#, 'precip2', 'precip3', 'precip4'], 1) # 1=column\n# set nan to zero\ndataframe.precip1 = dataframe.precip1.fillna(0.)\ndataframe.snow = dataframe.snow.fillna(0.)\ndataframe.water_equiv = dataframe.water_equiv.fillna(0.)\n# set the index\ndataframe = dataframe.set_index('datetime')\nprint('before rain1', dataframe['precip1'].fillna(0.).sum())\nprint('before rain2', dataframe['precip2'].fillna(0.).sum())\nprint('before rain3', dataframe['precip3'].fillna(0.).sum())\nprint('before rain4', dataframe['precip4'].fillna(0.).sum())\nprint('before snow', dataframe['snow'].fillna(0.).sum())\nprint('before depth', dataframe['water_equiv'].fillna(0.).sum())\n\n#cols = ('datetime', 'wind_speed' - avg, 'temperature' - min/max, 'dewpoint' min/max,\n# 'pressure' avg, 'precip1' sum, 'snow' sum, 'water_equiv' sum)\n\ndf_mean = dataframe[['wind_speed', 'pressure']].dropna().resample('D').mean()\ndf_sum = dataframe[['precip1', 'precip2', 'precip3', 'precip4', 'snow', 'water_equiv']].fillna(0.).resample('D').sum()\ndf_min = dataframe[['temperature', 'dewpoint']].resample('D').min().rename(columns={'temperature':'temp_min',\n 'dewpoint':'dew_min'})\ndf_max = dataframe[['temperature', 'dewpoint']].resample('D').max().rename(columns={'temperature':'temp_max',\n 'dewpoint':'dew_max'})\ndataframe = pd.concat([df_mean, df_sum, df_min, df_max], axis=1)\ndel df_mean\ndel df_sum\ndel df_min\ndel df_max\nprint('after rain ', dataframe['precip1'].fillna(0.).sum())\nprint('after snow ', dataframe['snow'].fillna(0.).sum())\nwillrain = dataframe.precip1.values > 0. \nwillsnow = dataframe.snow.values > 0. \npressure_change = dataframe.pressure.values[1:]-dataframe.pressure.values[:-1]\ndataframe = dataframe.drop(dataframe.index[-1])\ndataframe['willrain'] = willrain[1:]\ndataframe['willsnow'] = willsnow[1:]\ndataframe['press_change'] = pressure_change\n\ndataframe.to_hdf('TYS_daily.h5', 'everything', format='table')\n","sub_path":"create_daily.py","file_name":"create_daily.py","file_ext":"py","file_size_in_byte":2342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"391162040","text":"from functools import reduce\n\n__author__ = 'Victor'\nimport cv2\nimport numpy as np\n\nclass FlowImage:\n def __init__(self, image):\n self.image = cv2.imread(image)\n self.GrayImage = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)\n self.getGrid()\n self.getColors()\n\n\n def getColors(self):\n circles = cv2.HoughCircles(self.GrayImage, cv2.cv.CV_HOUGH_GRADIENT, 1, 25, param1=70, param2=50, minRadius=30, maxRadius=80)\n circles = np.uint16(np.around(circles))\n centers = []\n sorted = []\n groups = []\n\n for circle in circles[0,:]:\n groups.append(self.image[circle[1], circle[0]])\n centers.append((circle[1], circle[0]))\n\n for circle1, (b1, g1, r1) in enumerate(groups):\n for circle2, (b2, g2, r2) in enumerate(groups):\n\n difference = abs(abs(int(r1) - int(r2)) + abs(int(g1) - int(g2)) + abs(int(b1) - int(b2)))\n if difference < 25 and difference is not 0:\n groups[circle1] = groups[circle2]\n\n for circle1, (b1,g1,r1) in enumerate(groups):\n for circle2, (b2,g2,r2) in enumerate(groups):\n if b1 == b2 and g1 == g2 and r1 == r2 and circle2 > circle1:\n color1 = (centers[circle1][0]/self.cell_spacing,centers[circle1][1]/self.cell_spacing)\n color2 = (centers[circle2][0]/self.cell_spacing,centers[circle2][1]/self.cell_spacing)\n sorted.append([color1,color2])\n self.colors = sorted\n\n\n def getGrid(self):\n edges = cv2.Canny(self.GrayImage, 200, 250, apertureSize=3)\n lines = cv2.HoughLinesP(edges, 1, np.pi/180, 325, minLine=560, maxGap=120)[0].tolist()\n\n for x1, y1, x2, y2 in lines:\n for i, (x3, y3, x4, y4) in enumerate(lines):\n if y1 == y2 and y3 == y4:\n difference = abs(y1-y3)\n elif x1 == x2 and x3 == x4:\n difference = abs(x1-x3)\n else:\n difference = 0\n if difference < 15 and difference is not 0:\n del lines[i]\n\n self.gridSize = (len(lines) - 2) / 2\n spaceForCells = [(L[0]) for L in lines if L[0] == L[2]]\n spaceForCells = sorted(spaceForCells)\n spaceForCells = spaceForCells[0:2]\n self.cell_spacing = reduce(lambda a, b: b-a, spaceForCells)","sub_path":"FlowImage.py","file_name":"FlowImage.py","file_ext":"py","file_size_in_byte":2402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"589371070","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jul 3 20:31:09 2015\r\n\r\n@author: Jackson\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plot\r\n\r\ndef funcao_constante(k):\r\n print(\"Funcao Constante do tipo y = k\")\r\n x_vet = []\r\n y_vet = [] \r\n for x in range(-10,10):\r\n x_vet.append(x)\r\n y_vet.append(k)\r\n plot.plot(x_vet, y_vet, linestyle='-')\r\n plot.ylabel(\"Eixo y\")\r\n plot.xlabel(\"Eixo x\")\r\n plot.title(\"Função Constante\")\r\n plot.show()\r\n\r\ndef funcao_linear(A,x):\r\n print(\"Funcao Linear do tipo y = Ax\")\r\n x_vet = []\r\n y_vet = [] \r\n for contador in range(-10,10):\r\n x_vet.append(contador)\r\n y_vet.append(int(A) * int(contador))\r\n plot.plot(x_vet, y_vet, linestyle='-')\r\n plot.ylabel(\"Eixo y\")\r\n plot.xlabel(\"Eixo x\")\r\n plot.title(\"Função Constante\")\r\n plot.show()\r\n\r\ndef funcao_linear_afim():\r\n return print(\"FOO\")\r\n\r\ndef funcao_quadratica():\r\n return print(\"FOO\")\r\n","sub_path":"variados/dicionarioFuncoes.py","file_name":"dicionarioFuncoes.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"508132681","text":"from helper import Helper\n\n\nclass ThreatExpert(object):\n\n def __init__(self, hash):\n '''\n Initialzes ThreatExpert website module with\n the required config\n '''\n self.helper = Helper()\n self.name = 'threatexpert'\n self.hash = hash\n self.base_url = 'http://www.threatexpert.com'\n self.search_url = '{}/report.aspx?md5={}'.format(\n self.base_url,\n self.hash\n )\n self.search_match = 'Submission Summary:'\n self.http_header = self.build_http_header()\n self.helper.search_sample(self)\n\n def build_http_header(self):\n '''\n Builds a specific HTTP header for the requested\n website\n\n Returns:\n requests_header (dict) containing specific HTTP header\n options set for the requested website\n '''\n\n requests_header = {}\n\n requests_header['Accept'] = 'text/html'\n requests_header['Accept-Language'] = 'en-US, en;'\n requests_header['Accept-Encoding'] = 'gzip, deflate'\n requests_header['User-Agent'] = self.helper.get_random_user_agent()\n requests_header['Referer'] = self.base_url\n\n return requests_header\n","sub_path":"websites/threatexpert.py","file_name":"threatexpert.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"588272916","text":"import cv2\nimport numpy as np\nimport time\nimport AlbertFunctions as AF\nimport imutils\n#name = sys.argv[1]\n\n#name = 'ball_track.mp4'\npath_to_video = r\"C:\\Users\\JAlbe\\OneDrive\\Drone projekt\\Data\"\nname = \"flight4_red.mp4\"\n#name = '358_ball_lost.mp4'\nminDist = 500 # 500\nparam1 = 200 #500\nparam2 = 5 #was #12\nminRadius = 15 # was 5\nmaxRadius = 80 # was 50\n\n\ncap = cv2.VideoCapture((path_to_video+r\"/\"+name))\n \n\n# Raspicam\n#camMatrix = np.array( [[633.06058204 , 0.0 , 330.28981083], [ 0.0, 631.01252673 ,226.42308878], [ 0.0, 0.0,1. ]])\n#distCoefs = np.array([ 5.03468649e-02 ,-4.38421987e-02 ,-2.52895273e-04 , 1.91361583e-03, -4.90955908e-01])\n\n#ananda phone\n#camMatrix = np.array( [[630.029356, 0 , 317.89685204], [ 0. , 631.62683668 ,242.01760626], [ 0. , 0., 1. ]] )\n#distCoefs = np.array([ 0.318628685 ,-2.22790350 ,-0.00156275882 ,-0.00149764901, 4.84589387])\n\ncircles = []\nframes = 0\n\nwhile cap.isOpened() :\n\n start_time = time.time()\n\n ret, cimg = cap.read()\n cimg = AF.rotateImage(cimg,180)\n \n if not ret:\n break\n \n if cimg.shape[0] != 480:\n# cimg = cv2.resize(cimg, (640,480))\n cimg = imutils.resize(cimg,width = cimg.shape[0],height = cimg.shape[1])\n \n img = cv2.cvtColor(cimg,cv2.COLOR_BGR2GRAY)\n img2= cv2.Canny(img,100,200)\n img2 = cv2.GaussianBlur(img2,(3,3),0)\n img = cv2.GaussianBlur(img,(3,3),0)\n #img = cv2.erode(img, None, iterations=1)\n #img = cv2.dilate(img, None, iterations=1)\n\n #Find circles\n circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,minDist=minDist,param1=param1,param2=param2,minRadius=minRadius,maxRadius=maxRadius)\n\n try:\n circles = np.uint16(np.around(circles))\n for i in circles[0,:]:\n # draw the outer circle\n cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)\n cv2.circle(img,(i[0],i[1]),i[2],(255,255,255),2)\n cv2.circle(img2,(i[0],i[1]),i[2],(255,255,255),2)\n # draw the center of the circle\n cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)\n cv2.circle(img,(i[0],i[1]),2,(255,255,255),3)\n cv2.circle(img2,(i[0],i[1]),2,(255,255,255),3)\n except:\n print('No circles found in image: ')\n flag_BallFound = False \n\n \n \n frames += 1\n \n \n \n #Show er ikke talt med i computational tid, da de ikke skal bruges når\n #det køres på dronen\n end_time = time.time()\n print(\"Time per frame: \" + str(end_time-start_time))\n \n #Freq virker ikke, da der ikke er noget computational tid i øjeblikket,\n #Så den prøver at dividere med 0\n #print(\"Freq = \" + str( 1/(time.time() - start_time) ))\n \n #show_1 = np.hstack( ( orig_im, track_im ) )\n #show_2 = np.hstack( ( gray_show, hsv_range_show ) )\n \n #Hvis i vil vise flere forskellige typer frames på samme tid. Kan også\n #gøres med flere imshows, men her hænger billedet sammen og skygger\n #ikke for hinanden\n img_show=cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)\n img2_show = cv2.cvtColor(img2,cv2.COLOR_GRAY2BGR)\n show_1 = np.hstack( ( cimg, cimg ) )\n show_2 = np.hstack( ( img_show, img2_show ) )\n\n show_f = np.vstack( (show_1, show_2) )\n \n #0,0,0 Indsæt koordinaterne for bolden\n text = \"( {:.2f} | {:.2f} | {:.2f} )\".format(0,0,0)\n cv2.putText(show_f, text, (640,480), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255))\n \n\n cv2.imshow('Result', show_f)\n\n if( cv2.waitKey( 1 ) & 0xFF == ord('q') ):\n break;\n\nprint(\"Number of frames in the video: \" + str(frames))\n \ncap.release() \ncv2.destroyAllWindows()\n","sub_path":"fælles/RunningWithVideo.py","file_name":"RunningWithVideo.py","file_ext":"py","file_size_in_byte":3597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"294592616","text":"from pacai.agents.learning.value import ValueEstimationAgent\r\nfrom pacai.util import counter\r\n\r\nclass ValueIterationAgent(ValueEstimationAgent):\r\n \"\"\"\r\n A value iteration agent.\r\n\r\n Make sure to read `pacai.agents.learning` before working on this class.\r\n\r\n A `ValueIterationAgent` takes a `pacai.core.mdp.MarkovDecisionProcess` on initialization,\r\n and runs value iteration for a given number of iterations using the supplied discount factor.\r\n\r\n Some useful mdp methods you will use:\r\n `pacai.core.mdp.MarkovDecisionProcess.getStates`,\r\n `pacai.core.mdp.MarkovDecisionProcess.getPossibleActions`,\r\n `pacai.core.mdp.MarkovDecisionProcess.getTransitionStatesAndProbs`,\r\n `pacai.core.mdp.MarkovDecisionProcess.getReward`.\r\n\r\n Additional methods to implement:\r\n\r\n `pacai.agents.learning.value.ValueEstimationAgent.getQValue`:\r\n The q-value of the state action pair (after the indicated number of value iteration passes).\r\n Note that value iteration does not necessarily create this quantity,\r\n and you may have to derive it on the fly.\r\n\r\n `pacai.agents.learning.value.ValueEstimationAgent.getPolicy`:\r\n The policy is the best action in the given state\r\n according to the values computed by value iteration.\r\n You may break ties any way you see fit.\r\n Note that if there are no legal actions, which is the case at the terminal state,\r\n you should return None.\r\n \"\"\"\r\n\r\n def __init__(self, index, mdp, discountRate = 0.9, iters = 100, **kwargs):\r\n super().__init__(index, **kwargs)\r\n\r\n self.mdp = mdp\r\n self.discountRate = discountRate\r\n self.iters = iters\r\n self.values = counter.Counter() # A Counter is a dict with default 0\r\n\r\n # Compute the values here.\r\n states = self.mdp.getStates()\r\n\r\n # repeat iter # of times\r\n for i in range(self.iters):\r\n # copy vi, loop through every state, update vi's\r\n valuesCopy = self.values.copy()\r\n for state in states:\r\n actions = self.mdp.getPossibleActions(state)\r\n # find best action from state\r\n newValues = []\r\n for action in actions:\r\n qValue = self.getQValue(state, action)\r\n newValues.append(qValue)\r\n valuesCopy[state] = max(newValues, default=valuesCopy[state])\r\n # initialize values to vi+1\r\n self.values = valuesCopy\r\n\r\n def getQValue(self, state, action):\r\n outcomes = self.mdp.getTransitionStatesAndProbs(state, action)\r\n sumOutcomes = 0\r\n # sum of every possible action based on alg\r\n for nextState, prob in outcomes:\r\n reward = self.mdp.getReward(state, action, nextState)\r\n sumOutcomes += (prob * (reward + (self.discountRate * self.values[nextState])))\r\n return sumOutcomes\r\n\r\n def getPolicy(self, state):\r\n bestAction = None\r\n bestQValue = float('-inf')\r\n actions = self.mdp.getPossibleActions(state)\r\n # find best action corres. to best val\r\n # if none returns None\r\n for action in actions:\r\n qValue = self.getQValue(state, action)\r\n if qValue > bestQValue:\r\n bestQValue = qValue\r\n bestAction = action\r\n return bestAction\r\n\r\n def getValue(self, state):\r\n \"\"\"\r\n Return the value of the state (computed in __init__).\r\n \"\"\"\r\n\r\n return self.values[state]\r\n\r\n def getAction(self, state):\r\n \"\"\"\r\n Returns the policy at the state (no exploration).\r\n \"\"\"\r\n\r\n return self.getPolicy(state)\r\n","sub_path":"pacman/pacai/student/valueIterationAgent.py","file_name":"valueIterationAgent.py","file_ext":"py","file_size_in_byte":3664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"419918354","text":"from flask import Blueprint, request, render_template, flash, g, session, redirect, url_for\nfrom flask_login import login_required\nfrom werkzeug.urls import url_parse\nfrom app import db, socketio\nfrom app import events\nfrom app.module_task.forms import TaskForm\nfrom app.module_base.controllers import check_admin\nfrom app.module_task.models import Task\n\nmodule_task = Blueprint('task', __name__, url_prefix='/task')\n\n\n@module_task.route('/', methods=['GET'])\n@login_required\ndef index():\n task_list = Task.query.all()\n\n return render_template('module_task/index.html', title='Task', task_list=task_list)\n\n\n@module_task.route('/create/', methods=['GET', 'POST'])\ndef create():\n check_admin()\n\n add_task = True\n\n form = TaskForm()\n if form.validate_on_submit():\n task = Task(\n task_code=form.task_code.data,\n task_name=form.task_name.data,\n task_type=form.task_type.data,\n man_days_quoted=form.man_days_quoted.data,\n man_days_dev=form.man_days_dev.data,\n main_sa=form.main_sa.data,\n status=form.status.data,\n assigned_by=form.assigned_by.data,\n assigned_date=form.assigned_date.data,\n dev_code=form.dev_code.data,\n est_start_date_dev=form.est_start_date_dev.data,\n est_end_date_dev=form.est_end_date_dev.data,\n qa_code=form.qa_code.data.id,\n est_start_date_qa=form.est_start_date_qa.data,\n est_end_date_qa=form.est_end_date_qa.data,\n description=form.description.data,\n parent_task_id=form.parent_task_id.data.id,\n project_id=form.project_id.data,\n priority=form.priority.data\n )\n\n try:\n db.session.add(task)\n db.session.commit()\n flash('Add Task success')\n except Exception as e:\n print(e)\n flash('Error when add task')\n\n return redirect(url_for('task.index'))\n return render_template('module_task/task.html', title='Task | Create New Task',\n add_task=add_task, form=form)\n\n\n@module_task.route('/edit/', methods=['GET', 'POST'])\n@login_required\ndef edit(id):\n check_admin()\n add_task = False\n\n task = Task.query.get_or_404(id)\n form = TaskForm(obj=task)\n if form.validate_on_submit():\n task.task_name = form.task_name.data\n task.task_type = form.task_type.data\n task.man_days_quoted = form.man_days_quoted.data\n task.man_days_dev = form.man_days_dev.data\n task.main_sa = form.main_sa.data\n task.status = form.status.data\n task.assigned_by = form.assigned_by.data\n task.assigned_date = form.assigned_date.data\n task.dev_code = form.dev_code.data.id\n task.est_start_date_dev = form.est_start_date_dev.data\n task.est_end_date_dev = form.est_end_date_dev.data\n task.qa_code = form.qa_code.data\n task.est_start_date_qa = form.est_start_date_qa.data\n task.est_end_date_qa = form.est_end_date_qa.data\n task.description = form.description.data\n task.priority = form.priority.data\n task.parent_task_id = form.parent_task_id.data.id\n task.project_id = form.project_id.data\n\n db.session.commit()\n socketio.emit('message', {'msg': session.get('username') + ':' + 'ok'}, room=form.dev_code.data.username)\n flash('Edit task success')\n return redirect(url_for('task.index'))\n\n form.task_name.data = task.task_name\n form.task_type.data = task.task_type\n form.man_days_quoted.data = task.man_days_quoted\n form.man_days_dev.data = task.man_days_dev\n form.main_sa.data = task.main_sa\n form.status.data = task.status\n form.assigned_by.data = task.assigned_by\n form.assigned_date.data = task.assigned_date\n form.dev_code.data = task.dev_code\n form.est_start_date_dev.data = task.est_start_date_dev\n form.est_end_date_dev.data = task.est_end_date_dev\n form.qa_code.data = task.qa_code\n form.est_start_date_qa.data = task.est_start_date_qa\n form.est_end_date_qa.data = task.est_end_date_qa\n form.description.data = task.description\n form.priority.data = task.priority\n form.parent_task_id.data = task.parent_task_id\n form.project_id.data = task.project_id\n\n return render_template('module_task/task.html', title='Task | Edit Task',\n add_task=add_task, form=form, task=task)\n\n\n@module_task.route('/delete/', methods=['GET', 'POST'])\ndef delete(id):\n check_admin()\n task = Task.query.get_or_404(id)\n task.is_active = False\n\n db.session.commit()\n flash('Delete successs')\n\n return redirect(url_for('task.index'))\n\n","sub_path":"app/module_task/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":4720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"594427806","text":"from .base_classifier import BaseClassifier\nfrom regex.handlers import RegexHandler\nfrom util.string_functions import split_string_into_sentences\nimport numpy as np\n\nclass TemporalRegexClassifier(BaseClassifier):\n\n def __init__(self, classifier_name=\"TemporalRegexClassifier\", regexes=None, data=None, labels=None, ids=None,\n biases=None, handler=RegexHandler(), negative_label=\"None\"):\n\n super().__init__(classifier_name=classifier_name, data=data, labels=labels, ids=ids)\n self.DEBUG = False\n self.regexes = regexes\n self.biases = {class_name: 0 for class_name in self.regexes}\n self.negative_label = negative_label\n self.handler = handler\n\n #TODO: Think about this... I don't think we need a separate regex key or bias for None. Negative label bias idea is encapsulated by threshold anyway\n\n self.biases.update({negative_label: 0})\n self.regexes.update({negative_label: []})\n\n if biases:\n self.set_biases(biases)\n\n def set_biases(self, bias_dict={}):\n self.biases.update(bias_dict)\n\n def classify(self, class_to_scores, threshold=0):\n \"\"\"Given a dictionary of classes_to_scores, returns a tuple containing the class with the highest_score and its score\n\n Arguments:\n class_to_scores {dictionary} -- dictionary which class_name to a score\n\n Keyword Arguments:\n threshold {int} -- threshold value used to determine whether to return negative_label or classified label (default: {0})\n negative_label {str} -- [description] (default: {\"None\"})\n\n Returns:\n label {String} -- Assigned label\n score {int} -- Assigned score\n \"\"\"\n label, score = max(class_to_scores.items(), key=lambda i: i[1])\n if self.DEBUG:\n print(class_to_scores.items())\n #Return negative label if less than threshold\n if score > threshold:\n return label, score\n else:\n return self.negative_label, score\n\n def _get_case_lengths(self, datum):\n\n sentence_start_list = [0]*len(datum)\n\n for i in range(1, len(datum)):\n sentence_start_list[i] = sentence_start_list[i-1] + len(split_string_into_sentences(datum[i-1]))\n\n return sentence_start_list\n\n def run_classifier(self, sets=[\"train\", \"valid\"], class_threshold=0, pwds=None, label_func=None,\n classify_func=None, **kwargs):\n\n print(\"\\nRunning Classifier\", self.name)\n\n for data_set in sets:\n assert data_set in self.dataset, \"%s not in dataset\" % data_set\n print(\"Currently classifying {} with {} datapoints\".format(data_set, len(self.dataset[data_set][\"data\"])))\n\n preds = []\n\n data = self.dataset[data_set][\"data\"]\n self.dataset[data_set][\"matches\"] = []\n self.dataset[data_set][\"scores\"] = []\n\n for data_index, datum in enumerate(data):\n if self.DEBUG:\n print(\"-\"*100)\n print(\"Classifying id: \", self.dataset[data_set][\"ids\"][data_index])\n print(\"Label: \", self.dataset[data_set][\"labels\"][data_index])\n #Regex -> list of list of matches? - probably want one match in each sublist\n\n class_matches = [{class_name: {} for class_name in self.regexes} for _ in range(len(datum))]\n class_scores = [{class_name: 0 for class_name in self.regexes} for _ in range(len(datum))]\n\n unrolled_class_matches = {class_name: {} for class_name in self.regexes}\n\n latest_index_w_matches = 0\n\n case_lengths = self._get_case_lengths(datum)\n if self.DEBUG:\n print(case_lengths)\n\n for i, case in enumerate(datum):\n index_start = case_lengths[i]\n\n for class_name in self.regexes:\n if len(self.regexes[class_name]) > 0:\n\n case_matches, case_score = self.handler.score_data(case, self.regexes[class_name],\n pwds=pwds, index_start=index_start)\n\n class_scores[i][class_name] = self.biases[class_name] + case_score if \\\n class_name != self.negative_label else self.biases[class_name]\n\n #storing matches for that class\n class_matches[i][class_name] = case_matches\n\n if (case_score > 0 or case_score < 0):\n latest_index_w_matches = i\n\n unrolled_class_matches[class_name].update(case_matches)\n\n if not classify_func:\n classification, score = self.classify(class_scores[latest_index_w_matches],\n class_threshold)\n else:\n classification = classify_func(class_matches[latest_index_w_matches], None,\n class_scores[latest_index_w_matches],\n negative_label=self.negative_label, **kwargs)\n\n self.dataset[data_set][\"matches\"].append(unrolled_class_matches)\n self.dataset[data_set][\"scores\"].append(class_scores[latest_index_w_matches])\n\n preds.append(classification)\n\n if self.DEBUG:\n print(self.dataset[data_set][\"matches\"])\n\n preds = np.array(preds)\n self.dataset[data_set][\"preds\"] = preds\n","sub_path":"RegexNLP-py/classifier/simple_regex_classifier_t.py","file_name":"simple_regex_classifier_t.py","file_ext":"py","file_size_in_byte":5654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"95663395","text":"import numpy as np\nimport random\nimport cv2\nimport math\nimport matplotlib.image as mpimg\nfrom matplotlib import pyplot as plt\n\nimage = cv2.imread('/home/iiitb/Desktop/road4.jpg') \nheight = image.shape[0]\nwidth = image.shape[1]\n\ndef region_of_interest(img, vertices):\n # Define a blank matrix that matches the image height/width.\n mask = np.zeros_like(img)\n # Retrieve the number of color channels of the image.\n # Create a match color with the same color channel counts.\n #match_mask_color = (255,) * channel_count\n match_mask_color = 255\n \n # Fill inside the polygon\n cv2.fillPoly(mask, vertices, match_mask_color)\n \n # Returning the image only where mask pixels match\n masked_image = cv2.bitwise_and(img, mask)\n return masked_image\n\n\ndef draw_lines(img, lines, color=[255, 0, 0], thickness=2):\n # If there are no lines to draw, exit.\n if lines is None:\n return img\n # Make a copy of the original image.\n img = np.copy(img)\n # Create a blank image that matches the original in size.\n line_img = np.zeros(\n (\n img.shape[0],\n img.shape[1],\n 3\n ),\n dtype=np.uint8,\n )\n # Loop over all lines and draw them on the blank image.\n for line in lines:\n for x1, y1, x2, y2 in line:\n cv2.line(line_img, (x1, y1), (x2, y2), color, thickness)\n # Merge the image with the lines onto the original.\n img = cv2.addWeighted(img, 0.8, line_img, 1.0, 0.0)\n # Return the modified image.\n return img\n\n\n\nregion_of_interest_vertices = [(0, height), (width / 2, height / 2), (width, height),]\n\n# Convert to grayscale here.\ngray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\ncannyed_image = cv2.Canny(gray_image, 100, 200)\ncropped_image = region_of_interest(\n cannyed_image,\n np.array(\n [region_of_interest_vertices],\n np.int32\n ),\n)\n\nlines = cv2.HoughLinesP(\n cropped_image,\n rho=6,\n theta=np.pi / 60,\n threshold=160,\n lines=np.array([]),\n minLineLength=40,\n maxLineGap=25\n)\n\nleft_line_x = []\nleft_line_y = []\nright_line_x = []\nright_line_y = []\n\nleft_line_x = []\nleft_line_y = []\nright_line_x = []\nright_line_y = []\n\nif lines is not None:\n\tfor line in lines:\n\t for x1, y1, x2, y2 in line:\n\t slope = (y2 - y1) / (x2 - x1) # <-- Calculating the slope.\n\t if math.fabs(slope) < 0.5: # <-- Only consider extreme slope\n\t continue\n\t if slope <= 0: # <-- If the slope is negative, left group.\n\t left_line_x.extend([x1, x2])\n\t left_line_y.extend([y1, y2])\n\t else: # <-- Otherwise, right group.\n\t right_line_x.extend([x1, x2])\n\t right_line_y.extend([y1, y2])\nmin_y = image.shape[0] * (3 / 5) # <-- Just below the horizon\nmax_y = image.shape[0] # <-- The bottom of the image\npoly_left = np.poly1d(np.polyfit(\n left_line_y,\n left_line_x,\n deg=1, rcond=None, full=False, w=None, cov=False\n))\nleft_x_start = int(poly_left(max_y))\nleft_x_end = int(poly_left(min_y))\npoly_right = np.poly1d(np.polyfit(\n right_line_y,\n right_line_x,\n deg=1, rcond=None, full=False, w=None, cov=False\n))\nright_x_start = int(poly_right(max_y))\nright_x_end = int(poly_right(min_y))\n\nline_image = draw_lines(\n image,\n [[\n [int(left_x_start), int(max_y), int(left_x_end), int(min_y)],\n [int(right_x_start), int(max_y), int(right_x_end), int(min_y)],\n ]], \n color = [255,0,0],\n thickness=5\n)\nplt.figure()\nplt.imshow(line_image)\nplt.show()\n\n","sub_path":"Assignment_1/8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":3514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"199103340","text":"# Copyright 2015 Michael DeHaan \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\nimport strider.utils.logger\nfrom strider.common.commands import invoke\nfrom strider.common.instance_data import InstanceData\nimport os\nimport socket\nimport time\n\nclass Shell(object):\n\n def __init__(self, copy_from=None, copy_to=None, commands=None):\n\n self.log = strider.utils.logger.get_logger('SHELL')\n self.copy_from = copy_from\n self.copy_to = copy_to\n self.commands = commands\n if self.commands is None:\n self.commands = []\n\n # --------------------------------------------------------------------------\n # PROVISIONER PUBLIC API\n # --------------------------------------------------------------------------\n\n # FIXME: reimplement by just calling SSH\n def wait_for_ready(self, instance_data, extra_sleep=10):\n\n (host, port) = (instance_data.ssh.host, instance_data.ssh.port)\n self.log(\"checking for SSH availability on %s:%s\" % (host, port))\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n s.connect((host, port))\n except socket.error as e:\n self.log(\"SSH not ready, waiting 10 seconds\")\n time.sleep(10)\n self.log(\"SSH ready\")\n s.close()\n # socket start isn't enough for SSH-ready sometimes\n if extra_sleep:\n time.sleep(extra_sleep)\n\n def ssh(self, instance_data):\n \"\"\" open a shell into a box \"\"\"\n\n self.wait_for_ready(instance_data, extra_sleep=0)\n return invoke(self._build_ssh_cmd(instance_data,\"\"))\n\n def converge(self, instance_data):\n \"\"\" rsync if needed, then run the shell commands \"\"\"\n\n self.wait_for_ready(instance_data)\n if self.copy_from:\n invoke(self._build_rsync_cmd(instance_data))\n for pc in self.commands:\n invoke(self._build_ssh_cmd(instance_data, \" %s\" % pc))\n\n # --------------------------------------------------------------------------\n # PRIVATE FUNCTIONS\n # --------------------------------------------------------------------------\n\n def _ssh_params(self, instance_data):\n \"\"\" builds common SSH params used by both normal commands and rsync \"\"\"\n\n return \"-o Port=%s -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no\" % instance_data.ssh.port\n\n def _build_ssh_cmd(self, instance_data, what):\n \"\"\" builds a shell command line \"\"\"\n\n base = \"ssh %s -i %s %s@%s -p %s\" % (\n self._ssh_params(instance_data),\n instance_data.ssh.keyfile,\n instance_data.ssh.user,\n instance_data.ssh.host,\n instance_data.ssh.port\n )\n if what is None or what == \"\":\n return base\n return \"%s %s\" % (base, what)\n\n def _build_rsync_cmd(self, instance_data):\n \"\"\" builds a rsync command line \"\"\"\n\n return \"rsync -avze 'ssh %s -i %s' %s %s@%s:%s\" % (\n self._ssh_params(instance_data),\n instance_data.ssh.keyfile,\n self.copy_from,\n instance_data.ssh.user,\n instance_data.ssh.host,\n self.copy_to\n )\n","sub_path":"lib/strider/provisioners/shell.py","file_name":"shell.py","file_ext":"py","file_size_in_byte":3709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"613470866","text":"import sys\n\nwith open(sys.argv[1], 'r') as f:\n nums = [int(x) for x in f.readline().strip().split()]\nf.close()\n\nn_months = nums[0]\nn_litter = nums[1]\n\nf0=1\nf1=1\n\nif(n_months <= 2):\n f2 = 1\nelse:\n i = 3\n while i <= n_months:\n f2 = n_litter*f0 + f1\n f0 = f1\n f1 = f2\n i += 1\n\nprint(f2)\n\n","sub_path":"bioinformatics_stronghold/fib/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"397678281","text":"'''\nThis function calculates the kinetic energy of the structure controlled by a direct velocity feedback.\n'''\nfrom dtApp.dtData.soton_twin import Soton_twin_data\nimport numpy as np\nimport scipy.linalg as la\nimport control.matlab as ctrmat\nfrom plotly.subplots import make_subplots\n\n\ndef keVFC(nfs, mb, mp, kp, cp, Bl, Ze, h):\n fs = 1e2\n freq = np.arange(1, 1e2+1/fs, 1/fs) # frequency vector\n ns = len(freq)\n ga = float(1) # amplifier gain\n\n # import geometric and physical data\n m = Soton_twin_data['structure']['mass']['value'] # mass of each storey\n b = Soton_twin_data['structure']['legWidth']['value']\n ht = Soton_twin_data['structure']['legThickness']['value']\n l = Soton_twin_data['structure']['legLength']['value']\n E = Soton_twin_data['structure']['elasticityModulus']['value']\n J = b*pow(ht,3)/12\n k = 4*12*E*J/pow(l,3) # stiffness between each floor\n xi = Soton_twin_data['structure']['dampRatio']['value'] # damp ratio of first 2 modes\n\n # generate system matrices M, Ks\n Ms = np.diag([m,m,m])\n Ks = np.zeros((3,3))\n for ii in range(0,3):\n if ii==0:\n Ks[0][0]=k\n else:\n Ks[ii-1:ii+1,ii-1:ii+1] = Ks[ii-1:ii+1,ii-1:ii+1] + np.array([[k, -k], [-k, k]])\n\n # calculate eigenvalues and eigenvectors\n Wn, Xn = la.eig(Ks,Ms)\n Wn = Wn[::-1] # vector of eigenvalues\n Xn = Xn[:,::-1]/np.sqrt(m) # matrix of eigenvectors (mass normalised)\n\n\n # generate damping matrix C\n w1 = np.sqrt(Wn[0])\n w2 = np.sqrt(Wn[1])\n ray = (2*xi/(w1+w2))*np.array([[w1*w2], [1]]) # Rayleigh damping coefficients\n Cs = ray[0]*Ms + ray[1]*Ks\n\n # forcing matrices\n phip = np.zeros((1,3))\n phip[0][0] = 1\n phiptmd = np.block([phip, np.array([0])])\n\n phis = np.zeros((1,3))\n phis[0][nfs-1] = 1\n phistmd = np.block([phis, np.array([-1])])\n phiss = np.block([phis, np.array([0])])\n\n # system matrices - structure + TMD\n Msstar = Ms\n Msstar[nfs-1][nfs-1] += mb\n Mstmd = np.block([\n [Msstar, 0*phis.transpose()],\n [0*phis, np.array([mp])]\n ])\n\n Kstmd = np.block([\n [Ks+kp*phis.transpose()@phis, -kp*phis.transpose()],\n [-kp*phis, np.array([kp])]\n ])\n\n Cstmd = np.block([\n [Cs+cp*phis.transpose()@phis, -cp*phis.transpose()],\n [-cp*phis, np.array([cp])]\n ])\n\n Hvfc = np.zeros((1,4))\n Hvfc[0][nfs-1] = h\n\n Zvfc = ga*Bl*phistmd.transpose()@Hvfc\n\n # create state-space form\n A = np.block([\n [np.zeros((4,4)), np.eye(4)],\n [-la.inv(Mstmd)@Kstmd, -la.inv(Mstmd)@Cstmd]\n ])\n\n Bu = np.block([\n [np.zeros((4,4))],\n [la.inv(Mstmd)]\n ])@phistmd.transpose()\n\n Cvfc = np.zeros((1,8))\n Cvfc[0][2+nfs] = 1\n\n BLDGc_VFC = ctrmat.ss(A, Bu, Cvfc, 0)\n\n BLDGc_VFCtf = ctrmat.tf(BLDGc_VFC)\n\n syscontr = ctrmat.tf([h*Bl*ga],[1])\n sysvfc = ctrmat.series(BLDGc_VFCtf, syscontr)\n\n gm, pm, wg, wp = ctrmat.margin(sysvfc)\n\n T = np.zeros((ns),dtype=complex)\n L = np.zeros((ns),dtype=complex)\n P = np.zeros((ns),dtype=complex)\n for ii in range(0,ns):\n w = 2*np.pi*freq[ii]\n Z = 1j*w*Mstmd+Cstmd+Zvfc+Kstmd/(1j*w)\n dotX = la.inv(Z)@phiptmd.transpose()\n F = -Zvfc@dotX\n dotXs = np.delete(dotX, 3)\n T[ii] = (1/4)*dotXs.conjugate().transpose()@Msstar@dotXs\n\n Zol = 1j*w*Mstmd+Cstmd+Kstmd/(1j*w)\n L[ii] = h*ga*Bl*(phiss@la.inv(Zol)@phistmd.transpose())\n\n P[ii] = F.conjugate().transpose()@F\n \n ITsvfc = np.trapz(T.real, x=2*np.pi*freq)\n IPvfc = np.trapz(P.real, x=2*np.pi*freq)\n T = ctrmat.mag2db(abs(T))\n return {'freq': freq, 'ke': T, 'ol':L, 'IntKE': ITsvfc, 'IntCE': IPvfc, 'Gm': gm}","sub_path":"dtLib/control/activeControlVFC.py","file_name":"activeControlVFC.py","file_ext":"py","file_size_in_byte":3726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"458666073","text":"\n\nimport argparse\nimport os\n\nimport project.agents.diayn_enc as diayn_enc\n\n\n\nvariants = dict(\n point=dict(\n env='PointMaze-v3',\n policy_hidden_size=32,\n clf_hidden_size=32,\n critic_hidden_size=32,\n min_buffer_size=100,\n num_samples_per_epoch=100,\n num_train_steps_per_epoch=100,\n max_path_length_train=100,\n max_path_length_eval=100,\n eval_size=100,\n num_skills=10,\n\n\n ),\n cheetah=dict(\n env='HalfCheetah-v2',\n ),\n hopper=dict(\n env='Hopper-v2',\n ),\n ant=dict(\n env='Ant-v2'\n )\n)\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('variant', choices=list(variants))\nparser.add_argument('--path')\nparser.add_argument('--encode', type=int)\nparser.add_argument('--gpu-id', default=0, type=int)\nparser.add_argument('--data')\n\nargs = parser.parse_args()\n\nif args.path is None:\n path = None\nelse:\n path = os.path.join(args.path, args.variant)\n if args.encode:\n path += f'_enc{args.encode}'\n\nif args.data is None:\n data = None\nelse:\n if os.path.isdir(args.data):\n data = os.path.join(args.data, 'expert_data.pkl')\n else:\n data = args.data\n\nif args.encode:\n enc_enable = True\n enc_dim = args.encode\nelse:\n enc_enable = False\n enc_dim = 0\n\nvariant_cfg = variants[args.variant]\ncfg = diayn_enc.DIAYN.Config(\n path=path,\n clf_enc_enable=enc_enable,\n clf_enc_dim=enc_dim,\n gpu_id=args.gpu_id,\n expert_data=data,\n **variant_cfg\n)\n\ndiayn_enc.DIAYN.run(cfg)\n","sub_path":"scripts/run_diayn_enc.py","file_name":"run_diayn_enc.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"367665725","text":"# coding: utf-8\nfrom flask_socketio import SocketIO, send, emit\nfrom main import app\n\napp.config[\"SECRET_KEY\"] = \"mysecretkey\"\napp.debug = True\nsocket = SocketIO(app)\n\n\n@socket.on('message')\ndef handle_message(msg):\n send(msg, broadcast=True)\n\n\nif __name__ == '__main__':\n socket.run(app, host=\"127.1.1.1\", port=8888)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"277606522","text":"import tensorflow as tf\nimport tensorflow_datasets as tfds\nfrom tensorflow import keras\nimport numpy as np\n\n# 1. Load data from tfds\n\nimdb, info = tfds.load('imdb_reviews', as_supervised=True, with_info=True)\n\n# 2. Prepare Data\n\ntrain, test = imdb['train'], imdb['test']\n\ntraining_sentences = []\ntraining_labels = []\n\ntesting_sentences = []\ntesting_labels = []\n\nfor s, l in train:\n training_sentences.append(s.numpy().decode('utf8'))\n training_labels.append(l.numpy())\n\nfor s, l in test:\n testing_sentences.append(s.numpy().decode('utf8'))\n testing_labels.append(l.numpy())\n\ntraining_labels_final = np.array(training_labels)\ntesting_labels_final = np.array(testing_labels)\n\n# 3. Tokenizing and padding\n\nvocab_size = 1000\nembedding_dim = 16\nmax_len = 120\ntrun_type = 'post'\noov_tok = ''\n\ntokenizer = keras.preprocessing.text.Tokenizer(num_words=vocab_size,\n oov_token=oov_tok)\ntokenizer.fit_on_texts(training_sentences)\n\nsequences = tokenizer.texts_to_sequences(training_sentences)\npadded_seq = keras.preprocessing.sequence.pad_sequences(sequences,\n maxlen=max_len,\n truncating=trun_type)\n\ntest_sequences = tokenizer.texts_to_sequences(testing_sentences)\ntest_padded_seq = keras.preprocessing.sequence.pad_sequences(test_sequences,\n maxlen=max_len,\n truncating=trun_type)\n\ntokenizer.index_word.get(12)\nsequences[0]\n\n\ndef decode_padded(sentence):\n tokens = 0\n for i in sentence:\n tokens = tokens +1\n print(tokenizer.index_word.get(i), end=' ')\n print('\\nNo of tokens =',tokens)\n\nprint(decode_padded(sequences[0]))\nprint(decode_padded(padded_seq[0]))\n\n# 4. Model Building and Fitting\nmodel = keras.Sequential([\n keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_len ),\n keras.layers.Dense(6, activation='relu'),\n keras.layers.Dense(1, activation='sigmoid')\n])\n\nmodel.compile(\n loss='binary_crossentropy',\n optimizer='adam',\n metrics=[keras.metrics.binary_accuracy, 'accuracy']\n)\n\nhistory = model.fit(\n padded_seq, training_labels_final,\n validation_data=(test_padded_seq, testing_labels_final),\n epochs=10\n)\n\nprint(type(training_labels),\n type(training_labels_final)\n )\n\n# 5.Embedding Layer Viz\n\nembedding_layer = model.layers[0]\n#dir(embedding_layer)\nembedding_weights = embedding_layer.get_weights()[0]\n\nimport io\n\nout_v = io.open('./files/vectors.tsv', 'w', encoding='utf-8')\nout_m = io.open('./files/meta_data.tsv', 'w', encoding='utf-8')\nfor word_num in range(1, vocab_size):\n word = tokenizer.index_word.get(word_num)\n embeddings = embedding_weights[word_num]\n #print(word)\n #print(embeddings.shape)\n #break\n out_m.write(word + \"\\n\")\n out_v.write('\\t'.join([str(x) for x in embeddings]) + \"\\n\")\nout_v.close()\nout_m.close()\n","sub_path":"handy_snippets/embedding_layers.py","file_name":"embedding_layers.py","file_ext":"py","file_size_in_byte":3017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"264372259","text":"#\n# @lc app=leetcode id=19 lang=python3\n#\n# [19] Remove Nth Node From End of List\n#\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n if not head.next:\n return None\n dummy = ListNode(None)\n dummy.next = head\n p = dummy\n q = p\n for i in range(n):\n q = q.next\n while q and q.next:\n p = p.next\n q = q.next\n p.next = p.next.next\n return dummy.next\n\n","sub_path":"Yifan/week-2/19.remove-nth-node-from-end-of-list.py","file_name":"19.remove-nth-node-from-end-of-list.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"647804721","text":"from __future__ import print_function\n\n\ndef createNumStr(N):\n s = \"\"\n for i in range(1, N+1):\n s += str(i)\n\n return s\n\n\ndef print1ToN(N):\n num_str = createNumStr(N)\n print(num_str)\n\n\nif __name__ == '__main__':\n n = int(raw_input())\n print1ToN(n)","sub_path":"Python/Introduction/PrintFunction/challenge.py","file_name":"challenge.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"645320545","text":"from Image import ImageObject\nfrom Histogram import gray_histogram\nfrom copy import deepcopy\nimport matplotlib.pylab as plt\n\npath = \"images/\"\nimage = ImageObject(path + \"greyscale.png\")\nimage.load_image()\nimage.set_size(512, 512)\nimage.set_image_to_gray()\nimage.save_image(path + \"pb.png\")\nold_image = deepcopy(image)\n\nimage.transformation()\nimage.save_image(path + \"linears/transformed.png\")\n\nold_image.show_image()\ngray_histogram(old_image, 'r')\n\nimage.show_image()\ngray_histogram(image, 'gray')\n\nplt.show()","sub_path":"Transformed_Example.py","file_name":"Transformed_Example.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"392292312","text":"class Record(dict):\n \"\"\"\n Enable dot access to members of a dictionary.\n \"\"\"\n sep = '.'\n\n def __call__(self, *args):\n if len(args) == 0: \n return self\n return Record((key, self[key]) for key in args)\n\n def __getattr__(self, name):\n try:\n return self[name]\n except KeyError: \n raise AttributeError(name)\n\n def __delattr__(self, name):\n del self[name]\n\n def __setattr__(self, name, value):\n self[name] = value\n\n @staticmethod\n def fromkv(k, v):\n result = record()\n result[k] = v\n return result\n\n def __getitem__(self, key):\n if key in self:\n return dict.__getitem__(self, key)\n key += self.sep\n result = record()\n for k,v in iter(self.items()):\n if not k.startswith(key):\n continue\n suffix = k[len(key):]\n if '.' in suffix:\n ks = suffix.split(self.sep)\n z = result\n for x in ks[:-1]:\n if x not in z:\n z[x] = record()\n z = z[x]\n z[ks[-1]] = v\n else:\n result[suffix] = v\n if len(result) == 0:\n raise KeyError(\"No key or prefix: %s\" % key)\n return result\n \n\ndef record(value=None): \n \"\"\"\n Return a :class:`Record` instance with value provided.\n :param `value`: An initial record value. type ``dict``\n \"\"\"\n if value is None: \n value = {}\n return Record(value)","sub_path":"pdr_python_sdk/pdr_python_sdk/storage/record.py","file_name":"record.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"341394149","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport matplotlib.animation as animation\nfrom mpl_toolkits.mplot3d import Axes3D\n\nwave_0 = np.load(\"../data/2d_homogeneous_membrane.npy\")\nx_int = np.linspace(0, 2, wave_0.shape[0])\ny_int = np.linspace(0, 3, wave_0.shape[1])\nims = []\n\nX, Y = np.meshgrid(x_int, y_int)\nfps = 10\nfig, ax = plt.subplots(subplot_kw={\"projection\": \"3d\"})\nfor i in range(0, wave_0.shape[2]):\n surf = ax.plot_surface(X, Y, wave_0[:, :, i].T, linewidth=0, antialiased=False,\n shade=True, alpha=0.5, color='black')\n ims.append([surf])\n print(i)\n\nax.set_zlim(-2.5, 2.5)\nani = animation.ArtistAnimation(fig, ims, interval=1000/fps, blit=True)\n\nplt.show()\n","sub_path":"Thesis/waves/plotWaves.py","file_name":"plotWaves.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"328962092","text":"from Processor import Processor\nimport sys\nfrom collections import deque\nfrom datetime import *\nfrom scipy import stats as stats\nfrom numpy import *\nimport time\n\n\nclass ConcordanceDataOutputProcessor(Processor):\n\n def __init__(self):\n Processor.__init__(self,\"ConcordanceDataOutputProcessor\", [(\"Avg16\",\"Average ROC for 16\"),(\"Avg19\",\"Average ROC for 19\"),(\"ConcordanceP\",\"Concordance pValue\"),(\"Concordance\",\"Concordance\")], [],[(\"Output Filename\",\"Name of the file to output to\")]) \n self.totalPositive = 0\n self.totalNegative = 0\n self.rollingSSI = 0\n self.dominantQ = None\n self.run()\n\n # process initial arguments\n def processArguments(self,initialTime):\n filename = self.argumentValues[0] \n self.f = open(filename, 'w')\n self.f.write(\"Date Time,EDASlopeAverage1,EDASlopeAverage2,P-value,Concordance,SSI\\n\")\n \n # main data processing function\n def process(self,timeStamp,values,queueNo):\n if self.dominantQ == None:\n self.dominantQ = queueNo\n elif self.dominantQ == queueNo:\n curVal = float(values[3])\n if curVal > 0:\n self.totalPositive += curVal\n else:\n self.totalNegative += curVal\n \n if self.totalNegative != 0:\n result = self.totalPositive/abs(self.totalNegative)\n else:\n result = \"Null\"\n #self.addProcessedValues(str(result))\n timestr=datetime.fromtimestamp(timeStamp).strftime(\"%Y-%m-%d %H:%M:%S.%f\")\n timestr=timestr[:-4]\n self.f.write(timestr+\",\"+str(values[0])+\",\"+str(values[1])+\",\"+str(values[2])+\",\"+str(values[3])+\",\"+str(result)+\"\\n\") \n \nif __name__ == '__main__': ConcordanceDataOutputProcessor()\n","sub_path":"legacy/legacy-processors/ConcordanceDataOutputProcessor.py","file_name":"ConcordanceDataOutputProcessor.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"367000957","text":"import os\nimport ipaddress\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter import filedialog\n\n\ndef askdir():\n direc = filedialog.askdirectory(parent=top_frame, initialdir=os.getcwd())\n print(direc)\n var.set(direc)\n source_folder.configure(state=DISABLED)\n\n\ndef ip_check(key):\n # check = ip.get()\n # print(ip.get())\n check = ip_ssa.get()\n print(check)\n try:\n ipaddress.ip_address(check)\n label_top_ip_invalid['text'] = ''\n # print('aqui tá certo')\n except ValueError:\n label_top_ip_invalid['text'] = 'IP Inválido'\n # print('aqui tem erro')\n\n\nroot = Tk()\nroot.title('Super Series Agent')\nroot.geometry('800x650')\nroot.resizable(0, 0)\nmainframe = ttk.Frame(root)\nmainframe.grid(column=0, row=0, sticky=(N, W, E, S))\nmainframe.columnconfigure(0, weight=1)\nmainframe.rowconfigure(0, weight=1)\n\ntop_frame = ttk.LabelFrame(mainframe, text='Configurações', labelanchor='ns', height=100, width=790)\ntop_frame.grid(column=0, row=0, columnspan=2, padx=5, pady=5)\ntop_frame.grid_propagate(False)\nleft_frame = ttk.LabelFrame(mainframe, text='Leitura', labelanchor='ns', height=350, width=390)\nleft_frame.grid(column=0, row=1, padx=5, pady=5)\nleft_frame.grid_propagate(False)\nright_frame = ttk.LabelFrame(mainframe, text='Envio', labelanchor='ns', height=350, width=390)\nright_frame.grid(column=1, row=1, padx=5, pady=5)\nright_frame.grid_propagate(False)\nbottom_frame = ttk.LabelFrame(mainframe, text='Status', labelanchor='ns', height=150, width=790)\nbottom_frame.grid(column=0, row=2, columnspan=2, padx=5, pady=5)\nbottom_frame.grid_propagate(False)\n\nvar = StringVar()\nip = StringVar()\nip_invalid = StringVar()\n# ip_invalid.set('sim')\n\nlabel_top_folder_text = 'Informe o caminho da pasta para leitura pelo SSA'\nlabel_top_ip_text = 'Informe o IP do SSA'\n\nlabel_top_folder = ttk.Label(top_frame, text=label_top_folder_text)\nlabel_top_folder.grid(column=0, row=0, sticky='we', padx=5)\nsource_folder = ttk.Entry(top_frame, width=75, textvariable=var)\nsource_folder.grid(sticky='we', padx=5, pady=0, column=0, row=1)\nask_source = ttk.Button(top_frame, width=10, text='Selecione', command=askdir)\nask_source.grid(sticky='we', padx=5, pady=0, column=1, row=1)\n\nlabel_top_ip = ttk.Label(top_frame, text=label_top_ip_text)\nlabel_top_ip.grid(column=2, row=0, sticky='ns', padx=75)\n#ip_ssa = ttk.Entry(top_frame, width=5, textvariable=ip)\nip_ssa = ttk.Entry(top_frame, width=5)\nip_ssa.grid(sticky='we', padx=50, pady=0, column=2, row=1)\nlabel_top_ip_invalid = ttk.Label(top_frame, foreground='red', text=ip_invalid.get())\nlabel_top_ip_invalid.grid(sticky='ns', padx=50, pady=0, column=2, row=2)\n\nteste = False\nif teste:\n ask_source.configure(state=DISABLED)\n\n\n# for child in mainframe.winfo_children():\n# child.grid_configure(padx=5, pady=5)\n\n#ip_ssa.bind('', ip_check)\nip_ssa.bind('', ip_check)\nroot.mainloop()\n","sub_path":"ssa.py","file_name":"ssa.py","file_ext":"py","file_size_in_byte":2892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"510105182","text":"import sys\nimport os\nfrom ctypes import *\n\nclass MEMORY_BASIC_INFORMATION (Structure):\n\t_fields_ = [\n\t\t(\"BaseAddress\", c_ulong),\n\t\t(\"AllocationBase\", c_ulong),\n\t\t(\"AllocationProtect\", c_long),\n\t\t(\"RegionSize\", c_long),\n\t\t(\"State\", c_long),\n\t\t(\"Protect\", c_long),\n\t\t(\"Type\", c_long)]\n\nOpenProcess = windll.kernel32.OpenProcess\nReadProcessMemory = windll.kernel32.ReadProcessMemory\nGetLastError = windll.kernel32.GetLastError\nCloseHandle = windll.kernel32.CloseHandle\nVirtualQueryEx = windll.kernel32.VirtualQueryEx\nWaitForInputIdle = windll.user32.WaitForInputIdle\n\nPROCESS_ALL_ACCESS = 0x1F0FFF\nMEM_COMMIT = 0x00001000\nMEM_PRIVATE = 0x20000\nPAGE_EXECUTE_READWRITE = 0x40\n\nclass MemDumper(object):\n\tdef __init__(self, pid):\n\t\tself.work_folder = os.path.dirname(os.path.abspath(__file__))\n\t\tself.task_folder = 'memdump_{}'.format(pid)\n\t\tself.pid = pid\n\t\tself.current_task_path = os.path.join(self.work_folder, self.task_folder)\n\t\tif not os.path.exists(self.current_task_path):\n\t\t\tos.makedirs(self.current_task_path)\n\t\n\tdef dump(self):\n\t\thProcess = OpenProcess(PROCESS_ALL_ACCESS, False, self.pid)\n\t\tif hProcess == 0:\n\t\t\tprint('[!] Unable to OpenProcess: {}'.format(GetLastError()))\n\t\t\texit()\n\n\t\tmemlist = []\n\t\taddress = 0\n\t\twhile True:\n\t\t\tmbi = MEMORY_BASIC_INFORMATION()\n\t\t\tsize = c_int(sizeof(mbi))\n\t\t\tRetVal = VirtualQueryEx(hProcess, address, byref(mbi), size)\n\t\t\tif (RetVal == 0):\n\t\t\t\tbreak\n\n\t\t\tif (mbi.State == MEM_COMMIT and mbi.Type == MEM_PRIVATE and mbi.BaseAddress < 0x70000000):\n\t\t\t\tstart = mbi.BaseAddress\n\t\t\t\tmemlist.append(mbi)\n\t\t\t\n\t\t\taddress = c_long(mbi.BaseAddress + mbi.RegionSize)\n\n\t\tmatches = {}\n\t\tfor mbi in memlist:\n\t\t\tbuffer = create_string_buffer(mbi.RegionSize)\n\t\t\taddress = c_long(mbi.BaseAddress)\n\n\t\t\t#mbi.AllocationProtect == PAGE_EXECUTE_READWRITE\n\t\t\tbytesRead = c_ulong(0)\n\t\t\tReadProcessMemory(hProcess, address, buffer, mbi.RegionSize, bytesRead)\n\t\t\twith open(os.path.join(self.current_task_path, '%d_0x%x' % (self.pid, mbi.BaseAddress)), 'wb') as f:\n\t\t\t\tf.write(buffer.raw)\n\t\treturn None\n\nif __name__ == '__main__':\n\tif len(sys.argv) < 2:\n\t\tprint (\"Syntex : \\n\\t%s [pid]\" % sys.argv[0])\n\t\texit()\n\n\tdumper = MemDumper(int(sys.argv[1]))\n\tdumper.dump()\n","sub_path":"lib/memdumper.py","file_name":"memdumper.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"427350461","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n__author__ = \"Daniel Romero, Jhoan Villa\"\r\n__date__ = \"$20-jul-2015 18:52:55$\"\r\nimport wx, os, ConnSchema,ConnectionDataBase\r\nimport wx\r\nimport InterfazExamen.__init__\r\nimport wx.lib.scrolledpanel as scrolled\r\nimport HeadLow\r\nimport Componentes\r\n# Identificdores en el menu\r\nID_AGREGAR_EXAMEN = wx.NewId ()\r\n\r\nclass MenuPrincipalDocente(wx.Frame):\r\n def __init__(self,iddocente):\r\n 'contructor requiere de parent como interfaz contenedor y manipulador como clase que accedera a la informacion'\r\n \r\n self.conectordatabase = ConnectionDataBase.Connection(\"localhost\",\"examen\",\"adminexamen\",\"pasexamen\",\"5434\")#se rquerie de datos para conexion a motor\r\n self.conexion = ConnSchema.ConnSchema(self.conectordatabase)\r\n self.iddocente = iddocente\r\n app=wx.App(False)\r\n displaySize= wx.DisplaySize()\r\n wx.Frame.__init__(self, None, pos=(0, 0), size=(displaySize[0], displaySize[1]))\r\n displaySize= wx.DisplaySize()\r\n topPanel= scrolled.ScrolledPanel(self)\r\n topPanel.SetupScrolling(scroll_y=True)\r\n topPanel.SetBackgroundColour('3399FF')\r\n sizertopPanel=wx.BoxSizer(wx.VERTICAL)\r\n sizertopPanel.Add(HeadLow.Head(topPanel),0,wx.EXPAND|wx.ALL,border=10)\r\n sizertopPanel.Add(Body(topPanel,iddocente),0,wx.EXPAND|wx.ALL,border=10)\r\n sizertopPanel.Add(HeadLow.Low(topPanel),0,wx.EXPAND|wx.ALL,border=10)\r\n topPanel.SetSizer(sizertopPanel)\r\n self.sizer = sizertopPanel\r\n self.topPanel = topPanel\r\n self.topanel=topPanel\r\n self.Bind(wx.EVT_CLOSE, self.OnClose)\r\n #Genracion de menu Principal que controlara el interfaz\r\n menuBar = wx.MenuBar()\r\n menu = wx.Menu()\r\n m_exit = menu.Append(wx.ID_EXIT, \"&salir\\tAlt-X\", \"Close window and exit program.\")\r\n self.Bind(wx.EVT_MENU, self.OnClose, m_exit)\r\n menuBar.Append(menu, \"&Archivo\")\r\n menu = wx.Menu()\r\n m_agregartema = menu.Append(ID_AGREGAR_EXAMEN,\"&Agregar tema\", \"Agregar nuevo Examen\")\r\n self.Bind(wx.EVT_MENU, self.agregar, m_agregartema, id=ID_AGREGAR_EXAMEN)\r\n menu = wx.Menu()\r\n m_about = menu.Append(wx.ID_ABOUT, \"&Sobre nosotros\", \"Information about this program\")\r\n self.Bind(wx.EVT_MENU, self.OnAbout, m_about)\r\n menuBar.Append(menu, \"&Ayuda\")\r\n self.SetMenuBar(menuBar)\r\n self.Show()\r\n app.MainLoop()\r\n self.GetSizer().Layout()\r\n self.Fit()\r\n \r\n def OnClose(self, event):\r\n dlg = wx.MessageDialog(self, \r\n \"┐Realmente quiere salir?\",\r\n \"Confirmar Salida\", wx.OK|wx.CANCEL|wx.ICON_QUESTION)\r\n result = dlg.ShowModal()\r\n dlg.Destroy()\r\n if result == wx.ID_OK:\r\n self.Destroy()\r\n \r\n def OnAbout(self, event):\r\n dlg = AboutBox()\r\n dlg.ShowModal()\r\n dlg.Destroy()\r\n \r\n def agregar(self,event):\r\n parametro = event.GetId()\r\n if parametro == ID_AGREGAR_EXAMEN:\r\n panelagregar = admparametros.paneltema(self.topPanel,self,'agregar')\r\n \r\n self.cambiarpanel(panelagregar)\r\n \r\n def getconexion(self):\r\n \"\"\"consutlor que retorna la clase administradora de la base de datos\"\"\"\r\n return self.conexion.connection\r\n \r\n def regresarpanelprincipal(self):\r\n panel_original = Body(self.topPanel,self.iddocente)\r\n self.cambiarpanel(panel_original)\r\n \r\n def cambiarpanel(self,nuevopanel):\r\n \"\"\"Metodo usado para cambiar un panel en el que ya se\r\n registrˇ la informacion para el nuevo examen y se requiere\r\n que el siguiente paso en el registro de un nuevo examen se muestre\r\n requiere como parametro el nuevo panel \"nuevopanel\" en el que se va a\r\n reemplazar el ya utlizado\"\"\"\r\n #siempre se cambia en la poscion 2 ya que es la del body\r\n sizer = self.sizer\r\n sizer.Hide(0)\r\n sizer.Remove(0)\r\n sizer.Hide(0)\r\n sizer.Remove(0)\r\n sizer.Hide(0)\r\n sizer.Remove(0)\r\n sizer.Add(HeadLow.Head(self.topanel),0,wx.EXPAND|wx.ALL,border=10)\r\n sizer.Add(nuevopanel,0,wx.EXPAND|wx.ALL,border=10)\r\n sizer.Add(HeadLow.Low(self.topanel),0,wx.EXPAND|wx.ALL,border=10)\r\n self.topanel.SetSizer(self.sizer)\r\n self.SetSizer(sizer)\r\n self.GetSizer().Layout()\r\n self.Fit()\r\n \r\n## Body\r\n##-----------------------------------------------------------el):\r\nclass Body(wx.Panel):\r\n \"\"\" Una clase personalizada de frame donde el usuario que desee registrar un nuevo examen\r\n podra ingresar datos como el nombre del examen, la fecha del examen,\r\n el puntaje extra del examen, el tipo del examen y la cantidad de preguntas que este tendra.\"\"\"\r\n def __init__(self, parent, iddocente):\r\n 'contructor requiere de parent como interfaz contenedor y manipulador como clase que accedera a la informacion'\r\n wx.Panel.__init__(self,parent) # Inicializaciˇn Panel Padre\r\n self.SetBackgroundColour('3399FF')\r\n self.conectordatabase = ConnectionDataBase.Connection(\"localhost\",\"examen\",\"adminexamen\",\"pasexamen\",\"5434\")#se rquerie de datos para conexion a motor\r\n self.conexion = ConnSchema.ConnSchema(self.conectordatabase)\r\n queryidexamen = \"select (nom_pers||' '||apellido_pers) from persona where id_persona = \"+iddocente+\";\"\r\n self.nombre = self.conexion.connection.ExecuteQuery(queryidexamen)\r\n self.nombre = (self.nombre[0][0])\r\n self.quote = wx.StaticText(self, label=\"Bienvenido Admistrador: \"+self.nombre, pos=(140, 10))\r\n self.aparte = wx.StaticText(self, label=\"\", pos=(140, 10))\r\n gs = wx.GridSizer(1, 2, 1, 1) #Creacion grilla de tama├▒o\r\n #--------------Adici├│n de Paneles a la Grilla, esta grilla permite que los paneles se ajuste al tama├▒o de la pantalla\r\n gs.AddMany([(self.quote, 0, wx.ALIGN_CENTER),(self.aparte, 0, wx.ALIGN_CENTER),\r\n ])\r\n sizer = wx.BoxSizer(wx.VERTICAL) #Adici├│n de la grilla de tama├▒os al panel padre\r\n sizer.Add(gs, proportion=1, flag=wx.EXPAND)\r\n self.SetSizer(sizer)\r\n \r\niddocente = \"4\"\r\nMenuPrincipaladmin(iddocente)","sub_path":"NewPythonProject/src/Docente Interfaz/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"560968749","text":"from django.urls import path\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nfrom . import views\n\nurlpatterns = [\n path('home', views.product_list, name='home'),\n path('cart/', views.add_to_cart, name='cart'),\n # path('remove/', views.remove_from_cart, name='remove-cart'),\n path('cart_items', views.cartview, name='cart_items'),\n path('decrease-cart/', views.decreasecart, name='decrease-cart'),\n path('increase-cart/', views.increasecart, name='increase-cart'),\n # path('save-address/', views.checkoutview, name=\"save-address\"),\n path('signup', views.signup, name='signup'),\n path('login', views.user_login, name='login'),\n path('logout', views.logout_request, name='logout'),\n\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"products/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"472714041","text":"import labrad\nimport numpy\nimport matplotlib\n\nfrom matplotlib import pyplot\n#get access to servers\ncxn = labrad.connect()\ndv = cxn.data_vault\n\n#change directory\n#dv.cd(['','QuickMeasurements', 'Power Monitoring'])\ndv.cd(['','Experiments','Spectrum729','2013Mar13','1623_50'])\ndv.open(1)\ndata = dv.get().asarray\nx = data[:,0]\ny = data[:,1]\nfigure = pyplot.figure()\nfigure.clf()\npyplot.plot(x, y,'o-')\n\nfigure.suptitle('Spectrum 2013Mar13 1623_50, 10ms excitation')\npyplot.xlabel('Frequency (MHz)')\npyplot.ylabel('Excitation percentage')\npyplot.show()\n","sub_path":"scripts/dataAnalysis/729Experiments/2013Mar13/plot_broad_spectrum.py","file_name":"plot_broad_spectrum.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"344602891","text":"#!/usr/bin/python3\n\nf = open(\"words.txt\", \"r\")\ndata = f.read()\nf.close()\nwords = data.split(\" \")\n# print(\"The words in the text file are: \")\n# print(words)\nprint(\"the number of words is \", len(words))\nlines = data.split(\"\\n\")\n# print(\"Lines of text are: \")\n# print(lines)\n\nfor l in lines:\n if not l:\n lines.remove(l)\nprint(\"Number of lines \", len(lines))\n\n","sub_path":"Python/Python For Engineers/Wordcount/count_words.py","file_name":"count_words.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"590095090","text":"from socket import *\nimport time\nip_port=('127.0.0.1',8080)\nbuffer_size=1024\n\nudp_server=socket(AF_INET,SOCK_DGRAM)\nudp_server.bind(ip_port)\n\nwhile True:\n data,addr=udp_server.recvfrom(buffer_size)\n if not data:\n dtf=time.strftime('%Y-%m-%d %X')\n else:\n dtf=data.decode('utf-8')\n\n udp_server.sendto(time.strftime(dtf).encode('utf-8'),addr)\n\n","sub_path":"socket/udp服务端.py","file_name":"udp服务端.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"389758248","text":"# http://bigocoder.com/courses/OBLUE01/OBLUE01_LEC06/BLUE_L06P02\n\nt = int(input())\n\nfor i in range(t):\n n = int(input())\n\n graph = [[] for j in range(n)]\n path = [-1] * n\n visited = [False] * n\n\n e = int(input())\n\n for j in range(e):\n x = list(map(int,input().split()))\n graph[x[0]].append(x[1])\n graph[x[1]].append(x[0])\n\n def DFS(s):\n visited[s] = True\n stack = []\n stack.append(s)\n\n while stack != []:\n u = stack.pop()\n for i in graph[u]:\n if not visited[i]:\n visited[i] = True\n path[i] = u\n stack.append(i)\n \n for j in range(n):\n DFS(j)\n \n print(path.count(-1))","sub_path":"BigO/Blue/Lecture06_DFS/Prayatna.py","file_name":"Prayatna.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"114171856","text":"import socket, time\n\ndef discover_cube():\n TIMEOUT=5\n PORT=23272\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, True)\n s.settimeout(TIMEOUT)\n # yes we need to staticly define a src port\n s.bind(('0.0.0.0', PORT))\n\n sender = None\n hexdiscover=\"6551334D61782A002A2A2A2A2A2A2A2A2A2A49\"\n data = bytes.fromhex(hexdiscover)\n\n s.sendto(bytes.fromhex(hexdiscover), (\"\", PORT))\n\n# so we have to listen on port 23272 to get a response, but we want to ignore our own response...\n# so either we do recvfrom twice or until we get something (more of an ugly hack thought)\n while data==bytes.fromhex(hexdiscover):\n try:\n data, (addr, foo) = s.recvfrom(1024)\n# print('Received: %s from %s' % (data, addr))\n except socket.timeout:\n print(\"No cube for you\")\n return sender\n s.close()\n return addr\n","sub_path":"maxcube/discovery.py","file_name":"discovery.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"35424452","text":"__author__ = 'Alok'\n\nimport os\n\nfrom fabric.api import local, abort, settings, sudo, cd, lcd\nfrom fabric.contrib.console import confirm\n\nfrom rocket.base import Base, EnvironmentNotFoundError, SettingsError, RemoteServerError\n\n\nclass Git(Base):\n \"\"\"\n Takes care of all the Git actions performed\n \"\"\"\n @staticmethod\n def push():\n \"\"\"\n Pushed code from local system\n :return:\n \"\"\"\n local(\"git push\")\n\n @staticmethod\n def commit(commit_message=None):\n \"\"\"\n Commits from local system\n :param commit_message: commit message\n :return: None\n \"\"\"\n if commit_message is not None:\n commit_cmd = 'git commit -m \"{0}\"'.format(commit_message)\n else:\n commit_cmd = \"git commit\"\n\n with settings(warn_only=True):\n result = local(\"git add -A && {}\".format(commit_cmd))\n\n if result.failed and not confirm(\"Commit failed. May be because there were no changes. Continue anyway?\"):\n abort(\"Aborting at user request\")\n\n def clone(self, environment):\n \"\"\"\n Looks up for an environment(web_server, database_engine etc), finds it's repo from settings and then clones from\n remote\n\n :param environment: the specific environment, eg- web_server\n :return: True if clone successful else False\n \"\"\"\n env_settings = self.settings.get(environment)\n if env_settings is None:\n raise EnvironmentNotFoundError(\"Environment '{e}' not found in settings\".format(e=environment))\n\n try:\n user = env_settings.get('user')\n remote_repo = env_settings.get('git').get('remote_repository_url')\n deployment_location = os.path.join(env_settings.get('deployment_path'),\n env_settings.get('deployment_directory'))\n\n except AttributeError:\n raise SettingsError(\"Settings file error\")\n\n except Exception:\n raise SettingsError(\"something went wrong\")\n\n command = \"sudo -Hu {user} git clone {repository} {location}\".format(user=user,\n repository=remote_repo,\n locatoin=deployment_location)\n # run command\n try:\n sudo(command)\n except Exception:\n raise RemoteServerError(\"Something went wrong in the server while cloning\")\n\n def pull(self, environment, is_local=False):\n \"\"\"\n Looks up for an environment(web_server, database_engine etc), finds it's repo from settings and then pulls from\n remote\n\n :param environment: the specific environment, eg- web_server\n :param is_local: depending on the system that made the call, True if pull was invoked locally else False.\n :return: True if pull successful else False\n \"\"\"\n pull_command = \"git pull\"\n env_settings = self.settings.get(environment)\n if env_settings is None:\n raise EnvironmentNotFoundError(\"Environment '{e}' not found in settings\".format(e=environment))\n\n try:\n deployment_location = os.path.join(env_settings.get('deployment_path'),\n env_settings.get('deployment_directory'))\n except AttributeError:\n raise SettingsError(\"Settings file error\")\n except Exception:\n raise SettingsError(\"something went wrong\")\n\n if is_local:\n with lcd(deployment_location):\n local(pull_command)\n else:\n with cd(deployment_location):\n local(pull_command)","sub_path":"rocket/git.py","file_name":"git.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"248881440","text":"from random import randint\n\nrude_list = [\n 'Pauvre cloche',\n 'Cher vieux débris',\n 'Misérable loque humaine',\n 'Vieux shnoque',\n 'Séducteur déplumé',\n 'Vieux macaque édenté',\n 'Noble Jean-Foutre',\n 'Chère vieille crapule',\n 'Vieille charogne',\n 'Pâle escroc',\n 'Bougre de galapiat',\n 'Vieux pourri',\n 'Méprisable ordure',\n 'Sinistre individu',\n 'Vieux machin',\n 'Vieillard cacochyme',\n 'Petit foutriquet',\n 'Vieux matou',\n 'Gros malpropre',\n 'Greluchon famélique',\n 'Petit voyou',\n 'Gibier de potence'\n]\n\ndef generate():\n print(rude_list[randint(0,len(rude_list)-1)])\n\nif __name__ == \"__main__\":\n generate()","sub_path":"generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"377330829","text":"import dropbox\r\nimport os\r\n\r\nclass TransferData(object):\r\n def __init__(self,access_token):\r\n self.access_token = access_token\r\n \r\n def upload_file(self,file_from,file_to):\r\n dbx = dropbox.Dropbox(self.access_token)\r\n for root,dirs,files in os.walk(file_from):\r\n for file_name in files:\r\n local_path = os.path.join(root,file_name)\r\n relative_path = os.path.relpath(local_path, file_from)\r\n dropbox_path = os.path.join(file_to,relative_path) \r\n with open(local_path, 'rb') as f:\r\n dbx.files_upload(f.read(), dropbox_path,mode = WriteMode('overwrite')) \r\n\r\ndef main():\r\n access_token = 'sl.AsVWlh4IK-bjh1ymMl9PJNacn_Eqfz0F2cLoRKwI3qj899CshouLFusaf9C5vLCPruz-15vP7lHmH0PWUKYYKh4DRLdzxDBRRCPTgBjKVgbLbg8roLcMgVsMHi_d6iQbK7TCTZc'\r\n tranferData = TransferData(access_token)\r\n file_from = input(\"Enter the file to be uploaded: \")\r\n file_to = input(\"Enter the file you want to upload it to: \")\r\n\r\n tranferData.upload_file(file_from,file_to)\r\n print(\"Your file has been moved!\")\r\n\r\nmain() ","sub_path":"uploadFiles.py","file_name":"uploadFiles.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"542020679","text":"from datetime import datetime\nimport importlib\nimport logging\nimport os\nfrom job import Job\n\n\nclass Settings(object):\n configured = False\n\n def __getattribute__(self, item):\n try:\n attribute = object.__getattribute__(self, item)\n except AttributeError:\n self.configure()\n attribute = object.__getattribute__(self, item)\n\n return attribute\n\n def configure(self):\n self.SETTINGS_MODULE = os.environ.get(\"TRANSPORTER_SETTINGS_MODULE\")\n self.PROJECT_ROOT = os.getcwd()\n self.JOBS_ROOT = os.path.join(self.PROJECT_ROOT, 'jobs')\n self.LOGS_ROOT = os.path.join(self.PROJECT_ROOT, 'logs')\n self.LOG_FILE = None\n self.LOGGER = None\n\n self.MONITOR_LOGIN = 'admin'\n self.MONITOR_PASSWORD = 'password'\n\n self.YELL_JOBS_RUN = False\n\n try:\n mod = importlib.import_module(self.SETTINGS_MODULE)\n for setting in dir(mod):\n if setting.isupper():\n setting_value = getattr(mod, setting)\n setattr(self, setting, setting_value)\n\n self.configured = True\n except AttributeError:\n raise RuntimeError(\"Settings not found: %s\" % self.SETTINGS_MODULE)\n\n\nclass Logger(object):\n initialized = False\n\n def __init__(self):\n self.logger = None\n\n def info(self, *args, **kwargs):\n if self.logger is None:\n self.initialize()\n\n self.logger.info(*args, **kwargs)\n\n def error(self, *args, **kwargs):\n if self.logger is None:\n self.initialize()\n\n self.logger.error(*args, **kwargs)\n\n def exception(self, *args, **kwargs):\n if self.logger is None:\n self.initialize()\n\n self.logger.exception(*args, **kwargs)\n\n def initialize(self):\n log_file = os.environ.get(\"TRANSPORTER_JOB_NAME\", None)\n\n if log_file is None:\n raise \"Transporter job not set\"\n\n log_file += '_%s.log' % datetime.now().strftime('%Y-%m-%d-%H-%M-%S')\n logger = logging.getLogger('transporter_job_logger')\n\n if len(logger.handlers) == 0:\n formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')\n sh = logging.StreamHandler()\n sh.setFormatter(formatter)\n logger.addHandler(sh)\n\n log_file_path = os.path.join(settings.LOG_ROOT, log_file)\n fh = logging.FileHandler(log_file_path)\n fh.setFormatter(formatter)\n logger.addHandler(fh)\n\n logger.setLevel(logging.INFO)\n self.logger = logger\n\nsettings = Settings()\nlog = Logger()\n\nfrom transporter.classes.manager import Manager\nmanager = Manager()","sub_path":"transporter/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"337276090","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n__version__ = \"0.1.0\"\n\nimport argparse\nimport logzero\nimport settings\nimport ebooklib\nfrom ebooklib import epub\nimport re\nimport mecab_tokenize\n\n\nclass EpubTokenize:\n def __init__(self):\n logzero.logfile(\n settings.logfile,\n loglevel=20, maxBytes=1e6, backupCount=3\n )\n self.logger = logzero.logger\n self.mecab = mecab_tokenize.MecabTokenize()\n\n def extract(self, path):\n text = ''\n for item in epub.read_epub(path).get_items():\n if item.get_type() == ebooklib.ITEM_DOCUMENT:\n text += re.sub(r'<.+?>', '', item.get_content().decode())\n return text\n\n def freq(self, text):\n df = self.mecab.freq(text)\n df = df[df['freq'] >= 10]\n df = df[df['info1'].isin(['名詞', '動詞']) & (df['term'].str.len() >= 2)]\n return df\n\n def main(self, args):\n self.logger.info(f'{__file__} {__version__} {args}')\n text = self.extract(args.path)\n df = self.freq(text)\n df.to_csv(args.path + '.freq', sep='\\t')\n\n\nif(__name__ == '__main__'):\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--version',\n action='version', version=f'{__version__}'\n )\n parser.add_argument('path')\n args = parser.parse_args()\n EpubTokenize().main(args)\n","sub_path":"src/epub.py","file_name":"epub.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"291154613","text":"# -*- coding: utf-8 -*-\nimport datetime\nfrom PIL import Image\nimport time\n\nfrom chikong.reserve_weixin_base import get_main_info, get_check_num, submit\n\n\ndef work(id, smstoken, name,office_id, machine_type,machinecode, phone, time_string, date,wx_access_token):\n\n while int(datetime.datetime.now().strftime('%H%M%S')) < 83000:\n time.sleep(1)\n print(\"剩余\" + str(83005 - int(datetime.datetime.now().strftime('%H%M%S'))) + \"秒\")\n while True:\n try:\n if smstoken == \"\":\n smstoken, session = get_main_info()\n except:\n print(\"系统异常\")\n time.sleep(1)\n work(id,smstoken, name,office_id, machine_type,machinecode, phone, time_string, date,wx_access_token)\n return\n print(smstoken)\n\n get_check_num(smstoken)\n this_image = Image.open('./{}.jpg'.format(smstoken))\n this_image.show()\n check_number = input(\"请输入图片验证码:\")\n if submit(\n smstoken=smstoken,\n session=session,\n appoint_date=date,\n people_name=name,\n people_cardid=id,\n office_id=office_id,\n machine_type=machine_type,\n machinecode=machinecode,\n phone=phone,\n appoint_time=time_string,\n check_number=check_number,\n wx_access_token=wx_access_token\n ):\n break\n","sub_path":"chikong/reserve_weixin_work.py","file_name":"reserve_weixin_work.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"349508834","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.macosx-10.7-x86_64/egg/airflow/utils/file.py\n# Compiled at: 2019-09-11 03:47:35\n# Size of source mod 2**32: 1888 bytes\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\nimport errno, os, shutil\nfrom tempfile import mkdtemp\nfrom contextlib import contextmanager\n\n@contextmanager\ndef TemporaryDirectory(suffix='', prefix=None, dir=None):\n name = mkdtemp(suffix=suffix, prefix=prefix, dir=dir)\n try:\n yield name\n finally:\n try:\n shutil.rmtree(name)\n except OSError as e:\n if e.errno != errno.ENOENT:\n raise e\n\n\ndef mkdirs(path, mode):\n \"\"\"\n Creates the directory specified by path, creating intermediate directories\n as necessary. If directory already exists, this is a no-op.\n\n :param path: The directory to create\n :type path: str\n :param mode: The mode to give to the directory e.g. 0o755, ignores umask\n :type mode: int\n \"\"\"\n try:\n try:\n o_umask = os.umask(0)\n os.makedirs(path, mode)\n except OSError:\n if not os.path.isdir(path):\n raise\n\n finally:\n os.umask(o_umask)","sub_path":"pycfiles/apache_ariatosca-0.2.0-py2-none-any/file.cpython-36.py","file_name":"file.cpython-36.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"191225574","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport time\nimport sqlite3\nimport os\n\n#from twisted.internet import protocol, reactor, endpoints, epollreactor\n\nfrom MerkleTree import MerkleTree\n\n'''\nImplementation of a hash calendar\n'''\n\n#------------------------------------------------------------------------------\n\n__author__ = 'Ao Song'\n__email__ = 'ao.song@outlook.com'\n\n\n\nclass HashCalendar:\n def __init__(self):\n self.__calendar = MerkleTree()\n self.__aggregationTree = MerkleTree()\n self.__aggregationInterval = 1 #sec\n self.__publishInterval = 1 #day\n self.__transactionList = []\n\n self.__db = os.path.join(os.path.dirname(__file__), 'HashCalendar.db')\n if os.path.isfile(self.__db):\n os.remove(self.__db)\n\n self.__dbConnection = sqlite3.connect(self.__db)\n self.__dbCursor = self.__dbConnection.cursor()\n\n self.__dbCursor.execute(\n 'create table aggregation('\n 'node varchar(64), '\n 'token varchar(64), '\n 'root varchar(64), '\n 'timestamp varchar(32))')\n\n self.__dbCursor.execute(\n 'create table calendar('\n 'node varchar(64), '\n 'token varchar(64), '\n 'root varchar(64), '\n 'timestamp varchar(32))')\n\n\n def __del__(self):\n self.__dbCursor.close()\n self.__dbConnection.commit()\n self.__dbConnection.close()\n\n\n def set_time(self, aggregationInterval, publishInterval):\n self.__aggregationInterval = aggregationInterval\n self.__publishInterval = publishInterval\n\n\n def start(self):\n aggregationAnchorTime = time.time()\n calendarAnchorTime = aggregationAnchorTime\n\n print(\"Hash calendar started! Timestamp:\", aggregationAnchorTime)\n\n while True:\n runTime = time.time()\n\n if (runTime-calendarAnchorTime) > self.__publishInterval*24*3600:\n self.populate_to_db(\n 'calendar', \n self.__calendar, \n str(runTime))\n print(\"Hash calendar publish! Hash:\", \n self.__calendar.get_root())\n self.__calendar.clear()\n calendarAnchorTime = time.time()\n \n elif (runTime-aggregationAnchorTime) > self.__aggregationInterval:\n self.populate_to_db(\n 'aggregation', \n self.__aggregationTree, \n str(runTime))\n self.__calendar.add_node(self.__aggregationTree.get_root())\n print(\"Aggregation publish! Hash:\", \n self.__aggregationTree.get_root())\n self.__aggregationTree.clear() \n aggregationAnchorTime = time.time()\n\n\n self.aggregate_node() \n\n\n\n \n\n def populate_to_db(self, tableName, tree, timestamp):\n root = tree.get_root()\n if root == None:\n print(\"No data gathered yet!\")\n return None\n\n for leaf in tree.get_node_list():\n token = tree.get_token(leaf)\n sql = '''\n INSERT INTO\n {table}\n VALUES\n (?, ?, ?, ?)\n '''.format(table=tableName)\n self.__dbCursor.execute(sql, \n (str(leaf), str(token), str(root), timestamp))\n\n def aggregate_node(self):\n # todo: get data from non blocking IO, file or network \n time.sleep(1) \n node = 'Hello, world!'\n self.__aggregationTree.add_node(node)\n\n def transaction_aggregation(self):\n pass\n\n \n\n\ndef run_test():\n calendar = HashCalendar()\n calendar.set_time(0.5, 0.0005)\n\n calendar.start()\n\n\nif __name__ == '__main__':\n run_test()\n\n\n\n\n","sub_path":"HashCalendar.py","file_name":"HashCalendar.py","file_ext":"py","file_size_in_byte":3828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"651069521","text":"from setuptools import setup, find_packages\nimport os\n\nversion = open(os.path.join(os.path.abspath(os.path.dirname(__file__)), \n 'plonetheme', 'ist_theme', 'version.txt')).read().strip()\n\nsetup(name='plonetheme.ist_theme',\n version=version,\n description=\"Theme Product for the College of Information Sciences and Technology\",\n long_description=open(\"README.txt\").read() + \"\\n\" +\n open(\"HISTORY.txt\").read(),\n # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n \"Framework :: Plone\",\n \"Programming Language :: Python\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n keywords='',\n author='WebLion Documentation Group, Penn State',\n author_email='support@weblion.psu.edu',\n url='http://weblion.psu.edu/',\n dependency_links = [\n 'https://weblion.psu.edu/svn/weblion/weblion/AD54Elements/dist/',\n ], \n license='GPL',\n packages=find_packages(exclude=['ez_setup']),\n namespace_packages=['plonetheme'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'setuptools',\n 'Products.AD54Elements',\n ],\n entry_points=\"\"\"\n [z3c.autoinclude.plugin]\n\t target = plone\n \"\"\",\n )","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"541658382","text":"# 前k个高频元素\n\n\ndef topKFrequent(nums, k):\n dict_c = {}\n # 遍历数组统计每种字符出现次数写入字典\n for n in nums:\n if n not in dict_c.keys():\n dict_c[n] = 0\n dict_c[n]+=1\n \n # 对字典按值排序\n sorted_d = sorted(dict_c.items(), key=lambda x:x[1], reverse=True) \n outs = []\n \n # 对排序后字典输出前k个键值为结果\n for kk, v in sorted_d:\n outs.append(kk)\n return outs[:k]\n\nif __name__ == \"__main__\":\n nums = [1,1,1,2,2,3]\n k = 2\n print(topKFrequent(nums, k))","sub_path":"Week_02/homework1.py","file_name":"homework1.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"175576168","text":"import mxnet as mx\nimport logging\nimport math\nimport pickle\nimport warnings\nimport numpy\nfrom mxnet.ndarray import sgd_update, sgd_mom_update, NDArray\n\n@mx.optimizer.Optimizer.register\nclass Weight_Regularized_SGD(mx.optimizer.Optimizer):\n \"\"\"The SGD optimizer with momentum and weight decay.\n\n If the storage types of weight and grad are both ``row_sparse``, and ``lazy_update`` is True, \\\n **lazy updates** are applied by::\n\n for row in grad.indices:\n rescaled_grad[row] = lr * rescale_grad * clip(grad[row], clip_gradient) + wd * weight[row]\n state[row] = momentum[row] * state[row] + rescaled_grad[row]\n weight[row] = weight[row] - state[row]\n\n The sparse update only updates the momentum for the weights whose row_sparse\n gradient indices appear in the current batch, rather than updating it for all\n indices. Compared with the original update, it can provide large\n improvements in model training throughput for some applications. However, it\n provides slightly different semantics than the original update, and\n may lead to different empirical results.\n\n Otherwise, **standard updates** are applied by::\n\n rescaled_grad = lr * rescale_grad * clip(grad, clip_gradient) + wd * weight\n state = momentum * state + rescaled_grad\n weight = weight - state\n\n For details of the update algorithm see\n :class:`~mxnet.ndarray.sgd_update` and :class:`~mxnet.ndarray.sgd_mom_update`.\n\n This optimizer accepts the following parameters in addition to those accepted\n by :class:`.Optimizer`.\n\n Parameters\n ----------\n momentum : float, optional\n The momentum value.\n lazy_update : bool, optional\n Default is True. If True, lazy updates are applied \\\n if the storage types of weight and grad are both ``row_sparse``.\n multi_precision: bool, optional\n Flag to control the internal precision of the optimizer.\n ``False`` results in using the same precision as the weights (default),\n ``True`` makes internal 32-bit copy of the weights and applies gradients \\\n in 32-bit precision even if actual weights used in the model have lower precision.\\\n Turning this on can improve convergence and accuracy when training with float16.\n \"\"\"\n def __init__(self, momentum=0.0, lazy_update=True, reg_params={}, reg_lambda=1, **kwargs):\n super(Weight_Regularized_SGD, self).__init__(**kwargs)\n self.momentum = momentum\n self.lazy_update = lazy_update\n self.reg_params = reg_params\n self.reg_lambda = reg_lambda\n\n def create_state_multi_precision(self, index, weight):\n weight_master_copy = None\n if self.multi_precision and weight.dtype == numpy.float16:\n weight_master_copy = weight.astype(numpy.float32)\n return (self.create_state(index, weight_master_copy), weight_master_copy)\n if weight.dtype == numpy.float16 and not self.multi_precision:\n warnings.warn(\"Accumulating with float16 in optimizer can lead to \"\n \"poor accuracy or slow convergence. \"\n \"Consider using multi_precision=True option of the \"\n \"SGD optimizer\")\n return self.create_state(index, weight)\n\n def create_state(self, index, weight):\n momentum = None\n stype = weight.stype if self.lazy_update else 'default'\n if self.momentum != 0.0:\n momentum = zeros(weight.shape, weight.context, dtype=weight.dtype, stype=stype)\n return momentum\n\n def _update_impl(self, index, weight, grad, state, multi_precision=False):\n assert(isinstance(weight, NDArray))\n assert(isinstance(grad, NDArray))\n self._update_count(index)\n lr = self._get_lr(index)\n wd = self._get_wd(index)\n\n # ---------- MAS begin ----------\n # index : layer's name \n if index in self.reg_params:\n reg_param = self.reg_params[index]\n weight_dif = weight - reg_param['init_val']\n regulizer = weight_dif * (2 * self.reg_lambda * reg_param['omega'])\n grad = grad + regulizer\n # ----------- MAS end -----------\n\n kwargs = {'rescale_grad': self.rescale_grad}\n if self.momentum > 0:\n kwargs['momentum'] = self.momentum\n if self.clip_gradient:\n kwargs['clip_gradient'] = self.clip_gradient\n\n if not multi_precision:\n if state is not None:\n sgd_mom_update(weight, grad, state, out=weight,\n lr=lr, wd=wd, **kwargs)\n else:\n sgd_update(weight, grad, out=weight,\n lr=lr, wd=wd, **kwargs)\n else:\n if state[0] is not None:\n mp_sgd_mom_update(weight, grad, state[0], state[1], out=weight,\n lr=lr, wd=wd, **kwargs)\n else:\n mp_sgd_update(weight, grad, state[1], out=weight,\n lr=lr, wd=wd, **kwargs)\n\n def update(self, index, weight, grad, state):\n self._update_impl(index, weight, grad, state, multi_precision=False)\n\n def update_multi_precision(self, index, weight, grad, state):\n use_multi_precision = self.multi_precision and weight.dtype == numpy.float16\n self._update_impl(index, weight, grad, state,\n multi_precision=use_multi_precision)","sub_path":"src/weight_regularized_sgd.py","file_name":"weight_regularized_sgd.py","file_ext":"py","file_size_in_byte":5474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"304839188","text":"class Solution(object):\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n if len(prices) <= 1:\n return 0\n\n max_profit = self.maxForOne(prices)\n prices.append(-32767)\n\n for i in range(1, len(prices)):\n if prices[i - 1] < prices[i] and prices[i + 1] <= prices[i]:\n max_profit = max(max_profit, self.maxForOne(prices[:i + 1]) + self.maxForOne(prices[i + 1:]))\n return max_profit\n\n def maxForOne(self, subPrices):\n lp = len(subPrices)\n if lp <= 1:\n return 0\n minPrice = subPrices[0]\n maxProfit = 0\n for s in subPrices:\n if minPrice < s:\n maxProfit = max(maxProfit, s - minPrice)\n else:\n minPrice = s\n return maxProfit","sub_path":"123. Best Time to Buy and Sell Stock III.py","file_name":"123. Best Time to Buy and Sell Stock III.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"535521166","text":"import pexpect\n\n\ndef main():\n child = pexpect.spawn(\"ssh 172.20.20.23 -l admin\")\n print(child, type(child), dir(child))\n print(child.before)\n print(child.after)\n\n child.expect(\"Password:\")\n print(child.before)\n print(child.after)\n child.sendline(\"admin\")\n\n child.expect(\"leaf3\")\n print(child.before)\n print(child.after)\n child.sendline(\"show version\")\n\n child.expect(\"leaf3\")\n print(child.before)\n print(child.after)\n\n show_version_bytes = child.before\n show_version = show_version_bytes.decode()\n show_version_clean = show_version.split(\"show version\")[1]\n print(show_version_clean)\n\n child.sendline(\"enable\")\n child.expect(\"leaf3\")\n child.sendline(\"terminal length 0\")\n child.expect(\"leaf3#\")\n\n child.sendline(\"show run\")\n child.expect(\"leaf3#\")\n\n show_run_bytes = child.before\n show_run = show_run_bytes.decode()\n show_run_clean = show_run.lstrip(\"show run\")\n print(show_run_clean)\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"python_intro/test_pexpect.py","file_name":"test_pexpect.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"116322116","text":"str=\"tomato potato pineapple carrot watermelon hello @#$%^&*()?!||\"\ndef longest_word(str):\n word_final=''\n word_holder=''\n for w in str:\n #print(w)\n if w in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz':\n word_holder=word_holder+w\n #print(word_holder)\n \n if len(word_final) \" # The character to use as a cursor in the menus\n\n def home(self):\n \"\"\"\n UI home screen\n \"\"\"\n while True:\n print(\"1. Add Student\")\n print(\"2. Remove Student\")\n print(\"3. Display All Students\")\n print(\"4. Search Database\")\n user_choice = input(self.cursor_str)\n try:\n user_choice = int(user_choice)\n if user_choice not in self.screens:\n raise ValueError\n except ValueError:\n print(\"Invalid choice. Try again\")\n continue\n break\n self.screens[user_choice]()\n\n def add(self):\n \"\"\"\n UI for adding students to the database\n \"\"\"\n first = input(\"Enter the student's first name: \")\n last = input(\"Enter the student's last name: \")\n while True:\n num = input(\"Enter the student's number: \")\n try:\n num = int(num)\n except ValueError:\n print(\"Student number must be a number\")\n continue\n break\n try:\n Student(first, last, num)\n except DuplicateStudentException as e:\n print(str(e))\n self.home()\n\n def remove(self):\n \"\"\"\n UI for removing students from database\n \"\"\"\n while True:\n num = input(\"Enter the student number to be deleted: \")\n try:\n num = int(num)\n Student.get_student_by_number(num).delete()\n break\n except ValueError:\n print(\"Student number must be a number\")\n continue\n except StudentNotFoundException as e:\n print(str(e))\n continue\n self.home()\n\n def display_all(self):\n \"\"\"\n UI for displaying all students in database\n \"\"\"\n if len(students) == 0:\n print(\"No students in database\")\n else:\n for s in students:\n print(s)\n self.home()\n\n def search_database(self):\n \"\"\"\n UI home screen for searching the database\n \"\"\"\n searches = {\n 1: self.search_by_first_name,\n 2: self.search_by_last_name,\n 3: self.search_by_number,\n }\n print(\"1. Search by first name\")\n print(\"2. Search by last name\")\n print(\"3. Search by student number\")\n user_choice = int(input(self.cursor_str))\n print(searches[user_choice]())\n\n def search_by_first_name(self):\n \"\"\"\n UI for searching the database by first\n \"\"\"\n first = input(\"Enter the student's first name': \")\n try:\n for s in Student.get_students_by_first_name(first.capitalize()):\n print(s)\n except StudentNotFoundException as e:\n print(str(e))\n self.home()\n\n def search_by_last_name(self):\n \"\"\"\n UI for searching the database by last name\n \"\"\"\n last = input(\"Enter the student's last name': \")\n try:\n for s in Student.get_students_by_last_name(last.capitalize()):\n print(s)\n except StudentNotFoundException as e:\n print(str(e))\n self.home()\n\n def search_by_number(self):\n \"\"\"\n UI for searching the database by student number\n \"\"\"\n num = input(\"Enter the student number to search: \")\n try:\n num = int(num)\n print(Student.get_student_by_number(num))\n except ValueError:\n print(\"Student number must be a number\")\n except StudentNotFoundException as e:\n print(str(e))\n self.home()\n\n\nUI = UI()\n\nUI.home()\n","sub_path":"JackWalmsleyStudentDatabase.py","file_name":"JackWalmsleyStudentDatabase.py","file_ext":"py","file_size_in_byte":7384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"161123522","text":"# -*- coding: UTF-8 -*-\n'''\nAuthor: Jaime Rivera\nFile: custom_widgets.py\nDate: 2019.08.03\nRevision: 2019.08.03\nCopyright: Copyright Jaime Rivera 2019 | www.jaimervq.com\n The program(s) herein may be used, modified and/or distributed in accordance with the terms and conditions\n stipulated in the Creative Commons license under which the program(s) have been registered. (CC BY-SA 4.0)\n\nBrief:\n\n'''\n\n__author__ = 'Jaime Rivera '\n__copyright__ = 'Copyright 2019, Jaime Rivera'\n__credits__ = []\n__license__ = 'Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)'\n__maintainer__ = 'Jaime Rivera'\n__email__ = 'jaime.rvq@gmail.com'\n__status__ = 'Testing'\n\nfrom PySide2 import QtWidgets, QtCore, QtGui\nimport random\nimport json\n\nimport node_classes\n\n\n# -------------------------------- CUSTOM GRAPHICS VIEW -------------------------------- #\n\nclass CustomGW(QtWidgets.QGraphicsView):\n\n def __init__(self):\n QtWidgets.QGraphicsView.__init__(self)\n self.setRenderHints(QtGui.QPainter.Antialiasing)\n self.setAcceptDrops(True)\n\n self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)\n self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)\n\n self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)\n self.setResizeAnchor(QtWidgets.QGraphicsView.NoAnchor)\n\n self.middle_pressed = False\n\n def mousePressEvent(self, event):\n self.middle_pressed = False\n\n if event.button() == QtCore.Qt.MidButton:\n self._dragPos = event.pos()\n self.middle_pressed = True\n self.translate(50, 50)\n\n QtWidgets.QGraphicsView.mousePressEvent(self, event)\n\n def mouseMoveEvent(self, event):\n new_pos = event.pos()\n\n if self.middle_pressed:\n disp = new_pos - self._dragPos\n self._dragPos = new_pos\n self.translate(disp.x(), disp.y())\n\n QtWidgets.QGraphicsView.mouseMoveEvent(self, event)\n\n def mouseReleaseEvent(self, event):\n if event.button() == QtCore.Qt.MidButton:\n self.middle_pressed = False\n\n QtWidgets.QGraphicsView.mouseReleaseEvent(self, event)\n\n def wheelEvent(self, event):\n zoom_increase = 1.2\n zoom_decrease = 0.8\n\n old_pos = self.mapToScene(event.pos())\n\n if event.delta() > 0:\n self.scale(zoom_increase, zoom_increase)\n else:\n self.scale(zoom_decrease, zoom_decrease)\n\n new_pos = self.mapToScene(event.pos())\n disp = new_pos - old_pos\n self.translate(disp.x(), disp.y())\n\n\n# -------------------------------- CUSTOM SCENE CLASS -------------------------------- #\n\nclass CustomScene(QtWidgets.QGraphicsScene):\n def __init__(self):\n QtWidgets.QGraphicsScene.__init__(self)\n\n # NODES\n self.all_nodes = []\n self.selected_node = None\n\n # PATH TESTS\n self.testing_origin = None\n self.testing_path = QtWidgets.QGraphicsPathItem()\n self.testing_path.setPen(QtGui.QPen(QtCore.Qt.magenta, 2))\n self.testing_path.setZValue(-1)\n\n # CONNECTORS (Tests)\n self.testing_origin_connector = None\n self.testing_target_connector = None\n\n def add_node(self, node_class, x, y):\n for c in node_classes.ALL_NODES_LIST:\n if node_class == c.node_class_nice_name or node_class == c.node_class:\n new_node = c()\n self.addItem(new_node)\n new_node.setPos(x, y)\n new_node.set_selected(False)\n self.all_nodes.append(new_node)\n\n return new_node\n\n def delete_node(self):\n for stream in self.selected_node.streams:\n stream.clear_connections()\n\n self.removeItem(self.selected_node)\n self.all_nodes.remove(self.selected_node)\n del self.selected_node\n\n self.color_streams(recolor=False, only_starts=False)\n\n def establish_selected_node(self, node):\n if node:\n self.selected_node = node\n node.set_selected(True)\n else:\n self.selected_node = None\n\n for n in self.all_nodes:\n if n != self.selected_node:\n n.set_selected(False)\n\n def to_stream(self, node_class, node_id, stream_index):\n for node in self.all_nodes:\n if node.node_class == node_class and node.id == node_id:\n for stream in node.streams:\n if stream.index == stream_index:\n return stream\n\n return None\n\n def draw_valid_line(self, p1, p2):\n new_path = QtGui.QPainterPath(p1)\n\n c_p1 = QtCore.QPoint(((p2.x() + p1.x()) / 2) + 10, p1.y())\n c_p2 = QtCore.QPoint(((p2.x() + p1.x()) / 2) - 10, p2.y())\n new_path.cubicTo(c_p1, c_p2, p2)\n\n new_valid_line = QtWidgets.QGraphicsPathItem(new_path)\n new_valid_line.setPen(QtGui.QPen(QtGui.QColor(QtCore.Qt.green), 2))\n self.addItem(new_valid_line)\n new_valid_line.setZValue(-1)\n\n return new_valid_line\n\n def color_streams(self, recolor=True, only_starts=True):\n checkable_nodes = [n for n in self.all_nodes if n.node_class == 'Start']\n if not only_starts:\n checkable_nodes = self.all_nodes\n\n for node in checkable_nodes:\n for stream in node.streams:\n new_pen = QtGui.QPen(QtGui.QColor(QtCore.Qt.green), 2)\n if recolor:\n new_pen = QtGui.QPen(\n QtGui.QColor(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), 6)\n self.recolor_stream(stream, new_pen)\n\n def recolor_stream(self, stream, pen):\n next_stream = stream.output_stream\n if next_stream:\n line = stream.output_line\n line.setPen(pen)\n self.recolor_stream(next_stream, pen)\n\n def save_to_file(self):\n dialog = QtWidgets.QFileDialog()\n result = dialog.getSaveFileName(caption='Specify target file', filter='*.json')\n if not result[0] or not result[1]:\n return\n\n target_file = result[0]\n the_dict = {}\n\n for node in self.all_nodes:\n the_dict[str(node)] = {'class': node.node_class,\n 'id': node.id,\n 'x_pos': node.x(),\n 'y_pos': node.y(),\n 'widget_value': node.get_widget_value(),\n 'stream_count': node.stream_count,\n 'streams': {}}\n for stream in node.streams:\n if stream.output_stream:\n the_dict[str(node)]['streams'][stream.index] = [stream.output_stream.parent_class,\n stream.output_stream.parent_id,\n stream.output_stream.index]\n\n with open(target_file, 'w') as w:\n json.dump(the_dict, w, indent=2)\n\n def load_from_file(self):\n if self.all_nodes:\n warning_window = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, \"Error\",\n \"This functionality is only available with an empty graph.\"\n \"\\nPlease clear the graph and try again.\")\n warning_window.exec_()\n return\n\n dialog = QtWidgets.QFileDialog()\n result = dialog.getOpenFileName(caption='Specify source file', filter='*.json')\n if not result[0] or not result[1]:\n return\n\n source_file = result[0]\n\n with open(source_file, 'r') as r:\n net_dict = json.load(r)\n\n # Nodes creation\n for n in net_dict:\n new_node = self.add_node(net_dict[n]['class'], net_dict[n]['x_pos'], net_dict[n]['y_pos'])\n new_node.relabel_id(net_dict[n]['id'])\n new_node.set_widget_value(net_dict[n]['widget_value'])\n for i in range(net_dict[n]['stream_count'] - 1):\n new_node.add_stream()\n\n max_id = max([n.id for n in self.all_nodes])\n node_classes.GeneralNode.id_counter = max_id\n\n # Nodes connection\n for n in net_dict:\n if not net_dict[n]['streams']:\n continue\n\n for index in net_dict[n]['streams']:\n origin_stream = self.to_stream(net_dict[n]['class'], net_dict[n]['id'], int(index))\n target_stream = self.to_stream(net_dict[n]['streams'][index][0], net_dict[n]['streams'][index][1],\n net_dict[n]['streams'][index][2])\n\n out_c = origin_stream.output_connector\n in_c = target_stream.input_connector\n\n new_l = self.draw_valid_line(out_c.center_point, in_c.center_point)\n out_c.register_connection(in_c, new_l)\n in_c.register_connection(out_c, new_l)\n\n # Framing\n last_node = self.all_nodes[-1]\n self.parent().centerOn(last_node.x() + 50, last_node.y() + 50)\n\n def mousePressEvent(self, event):\n testing_connector = self.itemAt(event.scenePos(), QtGui.QTransform())\n if isinstance(testing_connector, node_classes.Connector):\n if testing_connector.can_recieve_connection:\n self.testing_path.setPen(QtGui.QPen(QtCore.Qt.magenta, 2, QtCore.Qt.DashLine))\n self.testing_origin_connector = testing_connector\n self.testing_origin = testing_connector.center_point\n self.addItem(self.testing_path)\n else:\n self.testing_origin_connector = testing_connector.connected_to\n self.testing_target_connector = testing_connector\n\n self.testing_path = testing_connector.line\n self.testing_path.setPen(QtGui.QPen(QtCore.Qt.magenta, 2, QtCore.Qt.DashLine))\n self.testing_path.setPen(QtGui.QPen(QtCore.Qt.magenta, 2, QtCore.Qt.DashLine))\n if testing_connector.type == 'input':\n self.testing_origin = self.testing_path.path().pointAtPercent(0)\n else:\n self.testing_origin = self.testing_path.path().pointAtPercent(1)\n\n self.testing_origin_connector.toggle_connection(restore=True)\n self.testing_target_connector.toggle_connection(restore=True)\n else:\n self.testing_origin = None\n if testing_connector is None:\n self.establish_selected_node(None)\n\n QtWidgets.QGraphicsScene.mousePressEvent(self, event)\n\n def mouseMoveEvent(self, event):\n if self.testing_origin:\n new_path = QtGui.QPainterPath(self.testing_origin)\n\n p1 = self.testing_path.path().pointAtPercent(0)\n p2 = event.scenePos()\n c_p1 = QtCore.QPoint(((p2.x() + p1.x()) / 2) + 10, p1.y())\n c_p2 = QtCore.QPoint(((p2.x() + p1.x()) / 2) - 10, p2.y())\n new_path.cubicTo(c_p1, c_p2, p2)\n\n if new_path.length() > 7000:\n self.testing_path.hide()\n else:\n self.testing_path.show()\n\n self.testing_path.setPath(new_path)\n\n QtWidgets.QGraphicsScene.mouseMoveEvent(self, event)\n\n def mouseReleaseEvent(self, event):\n self.testing_path.setPath(QtGui.QPainterPath())\n self.removeItem(self.testing_path)\n self.update()\n\n if self.testing_origin:\n if isinstance(self.itemAt(event.scenePos(), QtGui.QTransform()), node_classes.Connector):\n self.testing_target_connector = self.itemAt(event.scenePos(), QtGui.QTransform())\n self.check_connectables()\n\n self.testing_origin = None\n QtWidgets.QGraphicsScene.mouseReleaseEvent(self, event)\n\n def check_connectables(self):\n\n origin_connector, target_connector = self.testing_origin_connector, self.testing_target_connector\n\n checks = [origin_connector.type != target_connector.type,\n origin_connector.parent_node != target_connector.parent_node,\n origin_connector.can_recieve_connection,\n target_connector.can_recieve_connection]\n\n # CONNECTION CHECKS\n if False in checks:\n return\n\n # RIGHT-TO-LEFT CONNECTION\n if not ((origin_connector.type == 'output' and origin_connector.x < target_connector.x) or\n (origin_connector.type == 'input' and origin_connector.x > target_connector.x)):\n return\n\n p1 = origin_connector.center_point\n p2 = target_connector.center_point\n if p1.x() < p2.x():\n new_path = QtGui.QPainterPath(p1)\n c_p1 = QtCore.QPoint(((p2.x() + p1.x()) / 2) + 10, p1.y())\n c_p2 = QtCore.QPoint(((p2.x() + p1.x()) / 2) - 10, p2.y())\n new_path.cubicTo(c_p1, c_p2, p2)\n else:\n new_path = QtGui.QPainterPath(p2)\n c_p1 = QtCore.QPoint(((p2.x() + p1.x()) / 2) + 10, p1.y())\n c_p2 = QtCore.QPoint(((p2.x() + p1.x()) / 2) - 10, p2.y())\n new_path.cubicTo(c_p2, c_p1, p1)\n\n valid_line = QtWidgets.QGraphicsPathItem(new_path)\n valid_line.setPen(QtGui.QPen(QtCore.Qt.green, 2))\n valid_line.setZValue(-1)\n self.addItem(valid_line)\n\n target_connector.register_connection(origin_connector, valid_line)\n origin_connector.register_connection(target_connector, valid_line)\n\n self.color_streams(recolor=False, only_starts=False)\n\n def keyPressEvent(self, event):\n if self.selected_node:\n if event.key() == QtCore.Qt.Key_Delete:\n self.delete_node()\n elif event.key() == QtCore.Qt.Key_Plus and self.selected_node:\n self.selected_node.add_stream()\n elif event.key() == QtCore.Qt.Key_Minus and self.selected_node:\n self.selected_node.remove_stream()\n elif event.key() == QtCore.Qt.Key_F and self.selected_node:\n self.parent().resetMatrix()\n self.parent().centerOn(self.selected_node.x() + 50, self.selected_node.y() + 50)\n\n QtWidgets.QGraphicsScene.keyPressEvent(self, event)\n\n def dragMoveEvent(self, event):\n event.accept()\n\n def dragLeaveEvent(self, event):\n self.dropEvent(event)\n\n def dropEvent(self, event):\n source_widget = event.source()\n if isinstance(source_widget, QtWidgets.QTreeWidget):\n node_type = str(source_widget.selectedItems()[0].text(0)).strip()\n self.add_node(node_type, event.scenePos().x(), event.scenePos().y())\n","sub_path":"custom_widgets.py","file_name":"custom_widgets.py","file_ext":"py","file_size_in_byte":14781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"387389559","text":"import csv\nimport json\nfrom flask import Flask, jsonify\nfrom items import Items \n\napp = Flask(__name__)\n\n#add parse function to convert csv file to json obj\nwith open('Products.csv') as listings:\n reader = csv.DictReader(f)\n rows = list(reader)\n\nwith open('test.json', 'w') as listings:\n json.dump(rows, f)\n\n# listings = [\n# {\n# 'id': 1,\n# 'title': u'item1',\n# 'description': u'??????', \n# 'price': 8.0\n# },\n# {\n# 'id': 2,\n# 'title': u'item2',\n# 'description': u'???????', \n# 'price': 7.0\n# }\n# ]\n\n@app.route('/todo/api/v1.0/tasks', methods=['GET'])\ndef get_tasks():\n return jsonify({'tasks': listings})\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"draft_parse.py","file_name":"draft_parse.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"126608847","text":"from rest_framework.response import Response\nfrom rest_framework import generics, mixins, permissions\n\nfrom account.api.permissions import IsAdminOrReadOnly\n\nfrom rest_framework_jwt.settings import api_settings\nfrom .utils import get_article_group_json_obj\n\nfrom django.db.models import Q\nfrom django.contrib.auth import authenticate\nfrom django.http import JsonResponse\nfrom django.core.files.uploadedfile import InMemoryUploadedFile\n\nfrom PIL import Image\n\nfrom django.core.files.base import ContentFile\nfrom io import BytesIO\nfrom io import StringIO\nimport sys\nimport datetime\nimport pytz\n\nfrom tablib import Dataset\nimport openpyxl\n\nfrom .serializers import ArticleDetailSerializer, ArticleListSerializer, ProducerSerializer, ProducerListSerializer, ArticleImportSerializer, ArticleImagesImportSerializer, ProducerImagesImportSerializer, ArticleGroupListSerializer, ArticleGroupDetailSerializer, PaymentOrderCreateSerializer, PaymentOrderSerializer, PaymentOrderListSerializer, PaymentOrderUpdateSerializer\nfrom product.models import Article, Producer, Attribute, ArticleImage, PaymentItem, PaymentOrder, ArticleGroup, PaymentOrderCommentHistory\nfrom account.models import UserDiscount, Account, User, Company\n\nfrom account.api.permissions import IsOwner, IsOwnerOrAdmin\n\nclass ArticleListApiView(generics.ListAPIView):\n permission_classes = [permissions.IsAuthenticatedOrReadOnly, ]\n serializer_class = ArticleListSerializer\n\n def get_queryset(self, *args, **kwargs):\n queryset_list = Article.objects.all()\n\n category_id_query = dict(\n self.request.GET.lists()).get('category_id', None)\n sub_category_id_query = dict(\n self.request.GET.lists()).get('sub_category_id', None)\n value_query = dict(self.request.GET.lists()).get('value', None)\n category_name = self.request.GET.get('category_name', None)\n sub_category_name = self.request.GET.get('sub_category_name', None)\n producer_query = self.request.GET.get('producer', None)\n\n attr_queryset = Attribute.objects.all()\n if category_id_query:\n queryset_list = queryset_list.filter(\n Q(sub_category_id__category_id__in=category_id_query)\n ).distinct()\n if sub_category_id_query:\n queryset_list = queryset_list.filter(\n Q(sub_category_id__in=sub_category_id_query)\n ).distinct()\n if category_name:\n queryset_list = queryset_list.filter(\n Q(sub_category_id__category_id__category_name__iexact=category_name)\n ).distinct()\n if sub_category_name:\n queryset_list = queryset_list.filter(\n Q(sub_category_id__sub_category_name__iexact=sub_category_name)\n ).distinct()\n if producer_query:\n queryset_list = queryset_list.filter(\n Q(producer_id=producer_query)\n ).distinct()\n\n if value_query:\n attr_queryset = attr_queryset.filter(\n Q(value__in=value_query)\n ).distinct()\n\n articles_id = []\n for val in attr_queryset:\n articles_id.append(val.article_id_id)\n\n queryset_list = queryset_list.filter(\n Q(id__in=articles_id)\n ).distinct()\n\n return queryset_list\n\n\nclass ArticleImportApiView(generics.CreateAPIView):\n permission_classes = [permissions.IsAdminUser, ]\n serializer_class = ArticleImportSerializer\n queryset = Article.objects.all()\n\n def get_serializer_class(self):\n return ArticleImportSerializer\n\n def post(self, request, *args, **kwargs):\n return self.create(self, request, *args, **kwargs)\n\n def create(self, request, *args, **kwargs):\n request = request.request\n serializer = self.get_serializer(data=request.data)\n\n if serializer.is_valid(raise_exception=True):\n file_import = serializer.validated_data.get('file_import')\n\n wb = openpyxl.load_workbook(file_import)\n sheet_name = wb.active.title\n excel_sheet = wb.get_sheet_by_name(sheet_name)\n if excel_sheet.max_column is not 6:\n JsonResponse(\n {\"message\": \"Excel file is not valid.\"}, status=401)\n\n excel_sheet.insert_rows(0)\n excel_sheet['A1'].value = 'PRODUCT_GROUP'\n excel_sheet['B1'].value = 'ARTICLE_CODE'\n excel_sheet['C1'].value = 'ARTICLE_NAME'\n excel_sheet['D1'].value = 'UNIT_OF_MEASURE'\n excel_sheet['E1'].value = 'BUY_PRICE'\n excel_sheet['F1'].value = 'SELL_PRICE'\n\n wb.save(file_import)\n\n dataset = Dataset()\n imported_data = dataset.load(request.FILES[file_import.field_name])\n\n for art in imported_data.dict:\n try:\n art_obj = Article.objects.get(\n article_code=art['ARTICLE_CODE'])\n art_obj.price = art['SELL_PRICE']\n if art_obj.price == 0:\n art_obj.is_available = False\n art_obj.save()\n except Article.DoesNotExist:\n pass\n\n return JsonResponse({\"message\": \"File has been imported successfully.\"}, status=200)\n\n\nclass ProducerImagesImportApiView(generics.CreateAPIView):\n permission_classes = [permissions.IsAdminUser, ]\n serializer_class = ProducerImagesImportSerializer\n queryset = Producer.objects.all()\n\n def get_serializer_class(self):\n return ProducerImagesImportSerializer\n\n def post(self, request, *args, **kwargs):\n return self.create(self, request, *args, **kwargs)\n\n def create(self, request, *args, **kwargs):\n request = request.request\n serializer = self.get_serializer(data=request.data)\n\n if serializer.is_valid(raise_exception=True):\n exel_file_import = serializer.validated_data.get('exel_file')\n path = serializer.validated_data.get('directory_path')\n\n dataset = Dataset()\n imported_data = dataset.load(\n request.FILES[exel_file_import.field_name])\n for prod in imported_data.dict:\n image_file = Image.open(path+prod['image_name'])\n split_name = image_file.filename.split('\\\\')\n\n if image_file.height > 250 and image_file.width > 250 and image_file.mode != 'P':\n h_p = 200/image_file.height\n w_p = 200/image_file.width\n\n per = h_p if h_p > w_p else w_p\n\n image_file = image_file.resize(\n (int(per*image_file.height), int(per*image_file.width)), Image.ANTIALIAS)\n\n if image_file.format is None:\n image_format = split_name[len(split_name)-1].split('.')[1]\n image_file.format = 'PNG' if image_format == 'png' else 'JPEG'\n\n image_file.filename = split_name[len(split_name)-1]\n\n buffer = BytesIO()\n image_file.save(buffer, format=image_file.format, quality=100)\n buffer.seek(0)\n image_django_file = InMemoryUploadedFile(buffer, image_file.filename, split_name[len(\n split_name)-1], 'image/jpeg', buffer.tell(), None)\n\n try:\n producer_obj = Producer.objects.get(id=prod['producer_id'])\n producer_obj.profile_image.delete(save=False)\n\n producer_obj.profile_image.save(\n image_django_file.name, image_django_file)\n producer_obj.save()\n except Producer.DoesNotExist:\n pass\n return JsonResponse({\"message\": \"Images have been imported sucessfully.\"}, status=200)\n\n\nclass ArticleImagesImportApiView(generics.CreateAPIView):\n permission_classes = [permissions.IsAdminUser, ]\n serializer_class = ArticleImagesImportSerializer\n queryset = ArticleImage.objects.all()\n\n def get_serializer_class(self):\n return ArticleImagesImportSerializer\n\n def post(self, request, *args, **kwargs):\n return self.create(self, request, *args, **kwargs)\n\n def create(self, request, *args, **kwargs):\n request = request.request\n serializer = self.get_serializer(data=request.data)\n\n if serializer.is_valid(raise_exception=True):\n exel_file_import = serializer.validated_data.get('exel_file')\n path = serializer.validated_data.get('directory_path')\n\n dataset = Dataset()\n imported_data = dataset.load(\n request.FILES[exel_file_import.field_name])\n\n for art in imported_data.dict:\n # Convert PIL image to django file upload\n image_file = Image.open(path+art['image_name'])\n split_name = image_file.filename.split('\\\\')\n image_file.filename = split_name[len(split_name)-1]\n\n buffer = BytesIO()\n image_file.save(buffer, format=image_file.format, quality=100)\n buffer.seek(0)\n image_django_file = InMemoryUploadedFile(buffer, image_file.filename, split_name[len(\n split_name)-1], 'image/jpeg', buffer.tell(), None)\n\n try:\n article_image = ArticleImage.objects.get(id=art['id'])\n article_image.image_name = split_name[len(split_name)-1][0:29] if len(\n split_name[len(split_name)-1]) > 30 else split_name[len(split_name)-1]\n try:\n article_obj = Article.objects.get(id=art['article_id'])\n except Article.DoesNotExist:\n JsonResponse({\"message\": \"Article with provided id: \" +\n str(art['article_id']) + \"does not exist.\"}, status=200)\n\n article_image.article_id = article_obj\n article_image.content_type = image_file.format\n article_image.size = image_file.decodermaxblock\n article_image.height = image_file.height\n article_image.width = image_file.width\n article_image.purpose = art['purpose']\n\n article_image.image.delete(save=False)\n\n article_image.image.save(\n image_django_file.name, image_django_file)\n article_image.save()\n except ArticleImage.DoesNotExist:\n try:\n article_obj = Article.objects.get(id=art['article_id'])\n except Article.DoesNotExist:\n JsonResponse({\"message\": \"Article with provided id: \" +\n str(art['article_id']) + \"does not exist.\"}, status=200)\n\n image_name = split_name[len(split_name)-1][0:29] if len(\n split_name[len(split_name)-1]) > 30 else split_name[len(split_name)-1]\n article_image = ArticleImage(id=art['id'], image=image_django_file, image_name=image_name, article_id=article_obj, content_type=image_file.format,\n size=image_file.decodermaxblock, height=image_file.height, width=image_file.width, purpose=art['purpose'])\n\n article_image.save()\n\n return JsonResponse({\"message\": \"Images have been imported sucessfully.\"}, status=200)\n\n\nclass ArticleDetailApiView(generics.RetrieveAPIView):\n permission_classes = [permissions.IsAuthenticatedOrReadOnly, ]\n serializer_class = ArticleDetailSerializer\n lookup_field = 'id'\n\n def get_queryset(self, *args, **kwargs):\n return Article.objects.all()\n\n\nclass ProducerDetailApiView(generics.RetrieveAPIView):\n permission_classes = [permissions.IsAuthenticatedOrReadOnly, ]\n serializer_class = ProducerSerializer\n lookup_field = 'id'\n\n def get_queryset(self, *args, **kwargs):\n return Producer.objects.all()\n\n\nclass ProducerListApiView(generics.ListAPIView):\n permission_classes = [permissions.IsAuthenticatedOrReadOnly, ]\n serializer_class = ProducerListSerializer\n pagination_class = None\n\n def get_queryset(self, *args, **kwargs):\n return Producer.objects.all()\n\n def get_serializer_context(self):\n return {'request': self.request}\n\n\n\nclass ArticleGroupListApiView(generics.CreateAPIView,generics.ListAPIView):\n permission_classes = [IsAdminOrReadOnly, ]\n serializer_class = ArticleGroupListSerializer\n pagination_class = None\n\n def get_queryset(self, *args, **kwargs):\n return ArticleGroup.objects.all().order_by('id')\n\n def post(self, request, *args, **kwargs):\n return self.create(self, request, *args, **kwargs)\n\n def create(self, request, *args, **kwargs):\n request = request.request\n serializer = self.get_serializer(data=request.data)\n\n if serializer.is_valid(raise_exception=True):\n group_name = serializer.validated_data.get('group_name', None)\n article_ids = serializer.validated_data.get('article_ids', None)\n description = serializer.validated_data.get('description', None)\n link = serializer.validated_data.get('link', None)\n\n art_grp = ArticleGroup(group_name=group_name,description=description,link=link)\n art_grp.save()\n\n\n for art_id in article_ids:\n art = Article.objects.get(id=art_id.id)\n art_grp.article_ids.add(art)\n\n art_grp.save()\n\n return get_article_group_json_obj(art_grp, request)\n\nclass ArticleGroupDetailApiView(mixins.UpdateModelMixin,\n mixins.DestroyModelMixin,\n generics.RetrieveAPIView):\n permission_classes = [permissions.IsAdminUser, ]\n serializer_class = ArticleGroupDetailSerializer\n pagination_class = None\n lookup_field = 'id'\n \n def get_queryset(self, *args, **kwargs):\n return ArticleGroup.objects.all().order_by('id')\n\n def delete(self, request, *args, **kwargs):\n self.check_object_permissions(self.request, self.get_object())\n return self.destroy(request, *args, **kwargs) \n\n def put(self, request, *args, **kwargs):\n self.check_object_permissions(self.request, self.get_object())\n return self.update(self, request, *args, **kwargs)\n \n def update(self, request, *args, **kwargs):\n request = request.request\n serializer = self.get_serializer(data=request.data)\n\n if serializer.is_valid(raise_exception=False):\n art_group_id = int(self.kwargs['id'])\n art_group_obj = ArticleGroup.objects.get(id=art_group_id)\n\n group_name = serializer.validated_data.get('group_name', None)\n article_ids = serializer.validated_data.get('article_ids', None)\n description = serializer.validated_data.get('description', None)\n link = serializer.validated_data.get('link', None)\n\n if group_name:\n art_group_obj.group_name = group_name\n if description:\n art_group_obj.description = description\n if link:\n art_group_obj.link = link\n if article_ids:\n art_group_obj.article_ids.clear()\n \n for art_id in article_ids:\n art = Article.objects.get(id=art_id.id)\n art_group_obj.article_ids.add(art)\n\n art_group_obj.save()\n\n return get_article_group_json_obj(art_group_obj, request)\n\nclass PaymentOrderCreateApiView(generics.CreateAPIView):\n permission_classes = [permissions.IsAuthenticated, ]\n serializer_class = PaymentOrderCreateSerializer\n\n def get_queryset(self, *args, **kwargs):\n return PaymentOrder.objects.all()\n \n def post(self, request, *args, **kwargs):\n return self.create(self, request, *args, **kwargs)\n\n def create(self, request, *args, **kwargs):\n request = request.request\n serializer = self.get_serializer(data=request.data)\n\n if serializer.is_valid(raise_exception=True):\n user = request.user \n\n address = serializer.validated_data.get('address', None)\n city = serializer.validated_data.get('city', None)\n zip_code = serializer.validated_data.get('zip_code', None)\n phone = serializer.validated_data.get('phone', None)\n method_of_payment = serializer.validated_data.get('method_of_payment', 0)\n comment = serializer.validated_data.get('comment', None)\n\n account = Account.objects.get(email=user.email)\n\n full_name = None\n if account.account_type == 'USR':\n full_name = User.objects.get(email=user.email).__str__()\n else: \n full_name = Company.objects.get(email=user.email).__str__()\n\n payment_order = PaymentOrder(\n email = account,\n full_name = full_name,\n method_of_payment = method_of_payment,\n status = 0,\n address = address,\n city = city,\n zip_code = zip_code,\n phone = phone \n )\n \n payment_order.save()\n\n PaymentOrderCommentHistory(\n created_by = account,\n status= 0,\n payment_order_id=payment_order,\n comment=comment\n ).save()\n\n payment_items = serializer.validated_data.get('payment_items', None)\n for item in payment_items:\n article = item['article_id']\n number_of_pieces = item['number_of_pieces']\n article_attributes = item['article_attributes']\n\n try:\n user_discount = UserDiscount.objects.get(email=account.email,product_group_id=article.product_group_id_id).value\n except UserDiscount.DoesNotExist:\n user_discount = 0\n\n payment_item = PaymentItem(\n article_id=article,\n payment_order_id=payment_order,\n user_discount=user_discount,\n number_of_pieces=number_of_pieces,\n article_price=article.price,\n article_attributes=article_attributes,\n valid='1'\n )\n payment_item.save()\n\n payment_order.total_cost += ((article.price - (user_discount * article.price / 100)) * number_of_pieces)\n\n payment_order.save()\n\n return JsonResponse({\"message\": \"Payment order has been created.\"}, status=200)\n\nclass PaymentOrderDetailApiView(generics.RetrieveUpdateAPIView):\n permission_classes = [IsOwnerOrAdmin,]\n serializer_class = PaymentOrderSerializer\n pagination_class = None\n lookup_field = 'id'\n\n def get_queryset(self, *args, **kwargs):\n return PaymentOrder.objects.all()\n\n def get_serializer_class(self, *args, **kwargs):\n if self.request and self.request.method == 'GET':\n return PaymentOrderSerializer\n return PaymentOrderUpdateSerializer\n\n def get(self, request, *args, **kwargs):\n self.serializer_class = self.get_serializer_class(self,*args, **kwargs)\n return super().get(self, *args, **kwargs)\n\n def put(self, request, *args, **kwargs):\n self.serializer_class = self.get_serializer_class(self, *args, **kwargs)\n self.check_object_permissions(self.request, self.get_object())\n return self.update(self, request, *args, **kwargs)\n \n def update(self, request, *args, **kwargs):\n request = request.request\n serializer = self.get_serializer(data=request.data)\n\n if serializer.is_valid(raise_exception=True):\n user = request.user \n\n payment_order = PaymentOrder.objects.get(id=int(self.kwargs['id']))\n account = Account.objects.get(email=user.email)\n\n address = serializer.validated_data.get('address', None)\n city = serializer.validated_data.get('city', None)\n zip_code = serializer.validated_data.get('zip_code', None)\n phone = serializer.validated_data.get('phone', None)\n status = serializer.validated_data.get('status',None)\n comment = serializer.validated_data.get('comment', '')\n\n if address:\n payment_order.address = address\n if city:\n payment_order.city = city\n if zip_code:\n payment_order.zip_code = zip_code\n if phone:\n payment_order.phone = phone\n\n payment_order.status = status\n\n PaymentOrderCommentHistory(\n created_by = account,\n status=status,\n payment_order_id=payment_order,\n comment=comment\n ).save()\n\n payment_items = serializer.validated_data.get('payment_items', None)\n\n existing_payment_items = PaymentItem.objects.filter(payment_order_id=payment_order.id)\n for ei in existing_payment_items:\n if ei.valid == '-1':\n ei.delete()\n elif ei.valid == '1':\n ei.valid='0'\n ei.save()\n\n if payment_items:\n for item in payment_items:\n article = item['article_id']\n number_of_pieces = item['number_of_pieces']\n article_attributes = item.get('article_attributes',None)\n\n try:\n old_item = existing_payment_items.get(article_id=item['article_id'])\n old_item.valid = '-1'\n old_item.save()\n except PaymentItem.DoesNotExist:\n pass\n\n try:\n user_discount = UserDiscount.objects.get(email=account.email,product_group_id=article.product_group_id_id).value\n except UserDiscount.DoesNotExist:\n user_discount = 0\n\n if number_of_pieces is not -1:\n payment_item = PaymentItem(\n article_id=article,\n payment_order_id=payment_order,\n user_discount=user_discount,\n number_of_pieces=number_of_pieces,\n article_price=article.price,\n article_attributes=article_attributes,\n valid='1'\n )\n payment_item.save()\n\n new_payment_items = PaymentItem.objects.filter(payment_order_id=payment_order.id)\n\n payment_order.total_cost = 0\n for item in new_payment_items:\n if item.valid in ['0', '1']:\n payment_order.total_cost += ((item.article_price - (item.user_discount * item.article_price / 100)) * item.number_of_pieces)\n\n payment_order.save() \n\n return JsonResponse({\"message\": \"Payment order has been updated.\"}, status=200) \n\nclass PaymentOrderListApiView(generics.ListAPIView):\n permission_classes = [permissions.IsAuthenticated,]\n serializer_class = PaymentOrderListSerializer\n\n def get_queryset(self, *args, **kwargs):\n queryset_list = PaymentOrder.objects.all()\n order_field = self.request.GET.get('order_by',None)\n\n status_query = dict(self.request.GET.lists()).get('status', None)\n full_name_query = self.request.GET.get('full_name', None)\n date_from = self.request.GET.get('date_from',None)\n date_to = self.request.GET.get('date_to',None)\n\n try:\n if date_from:\n datetime.datetime.strptime(date_from, '%Y-%m-%d')\n else:\n date_from = datetime.datetime(1,1,1,0,0,0,0,tzinfo=pytz.UTC)\n if date_to:\n datetime.datetime.strptime(date_to, '%Y-%m-%d')\n else:\n date_to = datetime.datetime(9999,12,31,0,0,0,0,tzinfo=pytz.UTC)\n\n if date_from or date_to:\n queryset_list = queryset_list.filter(time_created__range=[date_from,date_to]) \n except ValueError:\n pass\n\n if status_query:\n queryset_list = queryset_list.filter(\n Q(status__in=status_query)\n ).distinct()\n\n if full_name_query:\n queryset_list = queryset_list.filter(\n Q(full_name__contains=full_name_query)\n ).distinct()\n\n if order_field in ['id', 'full_name', 'email', 'status', 'time_created', 'time_modified', 'total_cost', '-id', '-email', '-full_name', '-status', '-time_created', '-time_modified', '-total_cost']:\n queryset_list = queryset_list.order_by(order_field)\n\n return queryset_list\n","sub_path":"product/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":25127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"165761840","text":"#!/home/meichen/anaconda3/bin/python\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndata = pd.read_csv('pairsfile_rgp_select.csv',skipinitialspace=True)\ndata_array = np.array(data)\nmaster_lat = []\nmaster_lon = []\nmaster_radius = []\nmaster_mag = []\negf_lat = []\negf_lon = []\negf_radius = []\negf_mag = []\ndist = []\nfor i in np.arange(len(data_array[:,0])):\n master_lat.append(np.float(data_array[i,3])*np.pi/180.0)\n master_lon.append(np.float(data_array[i,4])*np.pi/180.0)\n master_radius.append(6371-np.float(data_array[i,5]))\n master_mag.append(np.float(data_array[i,2]))\n egf_mag.append(np.float(data_array[i,8]))\n egf_lat.append(np.float(data_array[i,11])*np.pi/180.0)\n egf_lon.append(np.float(data_array[i,12])*np.pi/180.0)\n egf_radius.append(6371-np.float(data_array[i,13]))\n\nfor i in np.arange(len(master_lat)):\n arg = np.cos(master_lat[i])*np.cos(egf_lat[i])*np.cos(master_lon[i]-egf_lon[i])+np.sin(master_lat[i])*np.sin(egf_lat[i])\n d = np.sqrt(master_radius[i]**2+egf_radius[i]**2-2*master_radius[i]*egf_radius[i]*arg)\n dist.append(d)\n\nprint(np.sum(np.array(dist)<300)*1.0/len(dist))\n\nfig,ax=plt.subplots(1,2,figsize=[10,5])\nax[0].hist(dist,bins=15,edgecolor='k',facecolor='gray',lw=0.1,alpha=0.7)\nax[0].tick_params(labelsize=8)\nax[0].set_xlabel('Hypocentral Distance (km)',size=10)\nax[0].set_ylabel('Number',size=10)\nax[1].hist(np.array(master_mag)-np.array(egf_mag),bins=15,edgecolor='k',facecolor='gray',lw=0.1,alpha=0.7)\nax[1].tick_params(labelsize=8)\nax[1].set_xlabel('Magnitude Difference',size=10)\nax[1].set_ylabel('Number',size=10)\nfig.savefig('dist_P.pdf')\n","sub_path":"figures/neic/P_rg/Brune/cal_dist.py","file_name":"cal_dist.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"535966528","text":"from app import db, models\nfrom flask.ext.wtf import Form\nfrom flask.ext.wtf.file import FileField, FileAllowed, FileRequired\nfrom wtforms import TextField, TextAreaField, BooleanField, IntegerField, SelectMultipleField\nfrom wtforms.validators import Required\nfrom operator import itemgetter\n\nclass LoginForm(Form):\n remember_me = BooleanField('remember_me', default = True)\n\nclass EditUserForm(Form):\n first_name = TextField('first', validators = [Required()])\n last_name = TextField('last', validators = [Required()])\n image = FileField('image', validators=[FileAllowed(('jpg',), '.JPG only!')])\n\nclass SearchForm(Form):\n search = TextField('search', validators = [Required()])\n \nclass RecipeForm(Form):\n name = TextField('name', validators = [Required()])\n instructions = TextAreaField('instructions', validators = [Required()])\n time = IntegerField('time', validators = [Required()])\n difficulty = IntegerField('difficulty', validators = [Required()])\n servings = IntegerField('', validators = [Required()])\n image = FileField('image', validators=[FileRequired(), FileAllowed(('jpg',), '.JPG only!')])\n\nclass IngredientForm(Form):\n name = TextField('name', validators = [Required()])\n","sub_path":"app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"468676928","text":"import argparse\nimport collections\nimport sys\nfrom typing import Any\nfrom typing import DefaultDict\nfrom typing import Generator\nfrom typing import List\nfrom typing import NamedTuple\nfrom typing import Set\nfrom typing import Tuple\nfrom typing import Union\n\nimport pytest\n\nfrom support import timing\n\n\nclass Or(NamedTuple):\n # mypy recursive types not supported\n choices: Tuple[Tuple[Union[str, Any], ...], ...]\n\n\ndef build_node(s: str, i: int) -> Tuple[Tuple[Union[str, Or], ...], int]:\n ret: List[Union[str, Or]] = ['']\n\n while i < len(s):\n if s[i] == '|':\n return tuple(ret), i + 1\n elif s[i] == ')':\n return tuple(ret), i\n elif s[i] == '(':\n i += 1\n ornodes: List[Tuple[Union[str, Or], ...]] = []\n while s[i] != ')':\n ornode, i = build_node(s, i)\n ornodes.append(ornode)\n\n # hax: an empty ornode\n if s[i - 1] == '|':\n ornodes.append(('',))\n\n ret.extend((Or(tuple(ornodes)), ''))\n else:\n assert isinstance(ret[-1], str), ret[-1]\n ret[-1] += s[i]\n i += 1\n return tuple(ret), i\n\n\ndef traverse(\n px: int, py: int,\n directions: DefaultDict[Tuple[int, int], Set[str]],\n seq: Tuple[Union[str, Or], ...],\n) -> Tuple[int, int]:\n for part in seq:\n if isinstance(part, str):\n for c in part:\n if c == 'W':\n directions[(px, py)].add('W')\n px -= 1\n directions[(px, py)].add('E')\n elif c == 'E':\n directions[(px, py)].add('E')\n px += 1\n directions[(px, py)].add('W')\n elif c == 'S':\n directions[(px, py)].add('S')\n py += 1\n directions[(px, py)].add('N')\n elif c == 'N':\n directions[(px, py)].add('N')\n py -= 1\n directions[(px, py)].add('S')\n else:\n px_before, py_before = px, py\n for choice in part.choices:\n px, py = traverse(px_before, py_before, directions, choice)\n\n return px, py\n\n\ndef next_points(\n px: int,\n py: int,\n directions: Set[str],\n) -> Generator[Tuple[int, int], None, None]:\n for direction in directions:\n if direction == 'W':\n yield (px - 1, py)\n elif direction == 'E':\n yield (px + 1, py)\n elif direction == 'S':\n yield (px, py + 1)\n elif direction == 'N':\n yield (px, py - 1)\n\n\ndef compute(s: str) -> int:\n s = s.strip()[1:-1]\n i = 0\n seq, _ = build_node(s, i)\n\n directions: DefaultDict[Tuple[int, int], Set[str]]\n directions = collections.defaultdict(set)\n\n traverse(0, 0, directions, seq)\n\n minx, maxx = sys.maxsize, -sys.maxsize\n miny, maxy = sys.maxsize, -sys.maxsize\n for x, y in directions:\n minx, maxx = min(minx, x), max(maxx, x)\n miny, maxy = min(miny, y), max(maxy, y)\n\n distance = 0\n seen = {(0, 0)}\n pts = [(0, 0)]\n while pts:\n next_pts = []\n for point in pts:\n for cand_point in next_points(*point, directions[point]):\n if cand_point not in seen:\n seen.add(cand_point)\n next_pts.append(cand_point)\n\n pts = next_pts\n distance += 1\n\n return distance - 1\n\n\n@pytest.mark.parametrize(\n ('input_s', 'expected'),\n (\n ('^WNE$', 3),\n ('^ENWWW(NEEE|SSE(EE|N))$', 10),\n ('^ENNWSWW(NEWS|)SSSEEN(WNSE|)EE(SWEN|)NNN$', 18),\n ('^ESSWWN(E|NNENN(EESS(WNSE|)SSS|WWWSSSSE(SW|NNNE)))$', 23),\n (\n '^WSSEESWWWNW(S|NENNEEEENN'\n '(ESSSSW(NWSW|SSEN)|WSWWN(E|WWS(E|SS))))$',\n 31,\n ),\n ),\n)\ndef test(input_s: str, expected: int) -> None:\n assert compute(input_s) == expected\n\n\ndef main() -> int:\n parser = argparse.ArgumentParser()\n parser.add_argument('data_file')\n args = parser.parse_args()\n\n with open(args.data_file) as f, timing():\n print(compute(f.read()))\n\n return 0\n\n\nif __name__ == '__main__':\n exit(main())\n","sub_path":"day20/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":4250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"145094530","text":"# O()\n\nimport time\n\n\nstart = time.clock()\ndata = open(\"AviationData.txt\",\"r\").readlines()\nsearch_val = \"LAX94LA336\"\n\naviation_data = [i.split(\" | \") for i in data]\n\nheader = aviation_data[0]\nprint(header)\n\naviation_dict_list = [dict(zip(header,i)) for i in aviation_data[1:]]\nlax_dict = [i for i in aviation_dict_list if i.get('Accident Number') == search_val]\n\nprint(time.clock() - start)\nprint(lax_dict)\n \n","sub_path":"dataquest/projects/Guided Project_ Investigating Airplane Accidents/dict_read.py","file_name":"dict_read.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"53738267","text":"import re\nimport math as mt\nimport time as t\nimport random as rand\n\nclass Kim_number:\n\n def __init__(self):\n self.seq = []\n\n def is_prime(self, in_num):\n\n sqrt = int(mt.sqrt(in_num))\n isPrime = 1\n\n if in_num < 2:\n isPrime = 0\n\n else:\n\n for rep in range(2, sqrt + 1):\n\n res = in_num % rep\n if res == 0:\n isPrime = 0\n break\n\n return isPrime\n\n def get_prime(self, in_num):\n\n pri_lis = []\n for rep in range(1, in_num + 1):\n\n if self.is_prime(rep):\n pri_lis.append(rep)\n\n return pri_lis\n\n def gcd(self, in_num1, in_num2):\n\n if in_num1 > in_num2:\n\n max = in_num1\n min = in_num2\n\n else:\n\n max = in_num2\n min = in_num1\n\n while True:\n\n res = max % min\n max = min\n min = res\n\n if res != 0:\n continue\n return max\n\n def facto(self, in_num):\n\n mul = 1\n for rep in range(1, in_num + 1):\n mul = mul*rep\n print(mul)\n\n def numerical_diff(self, func):\n delta = 1e-6\n return (func(x+delta) - func(x-delta)) / (2*delta)\n\nclass Kim_RSA(Kim_number):\n\n def gen_key(self, in_num):\n\n c_time = t.ctime()\n rand.seed(c_time)\n\n primes = rand.sample(self.get_prime(in_num), 2)\n pri1 = primes[0]\n pri2 = primes[1]\n\n pu_key = {}\n pr_key = {}\n enc = 0\n dec = 0\n\n n = pri1 * pri2\n eul_n = (pri1 - 1) * (pri2 - 1)\n\n for rep in range(2, eul_n):\n\n if self.gcd(rep, eul_n) == 1:\n enc = rep\n break\n\n for rep in range(2, eul_n):\n\n if enc*rep % eul_n == 1:\n dec = rep\n break\n\n pu_key['enc'] = enc; pu_key['n'] = n\n pr_key['dec'] = dec; pr_key['n'] = n\n\n return pu_key, pr_key\n\nclass Kim_backpack(Kim_number):\n\n def bin_trim(self, in_bin):\n\n in_bin = in_bin[2:] # NOTE : 2진수로 변환하였을 때, 0b가 붙는 것을 제거해줌.\n return in_bin\n\n def message(self, in_message):\n\n with open(in_message) as data:\n\n cha2int = [] # NOTE : 평문을 숫자로 변환하여 저장해줄 리스트\n self.message = '' # NOTE : 평문을 2진 코드로 변환한 결과를 저장할 문자열\n mul = 1; sum = 0\n \n # NOTE : 데이터 전처리 과정\n contents = data.read() # NOTE : 데이터 불러오기\n contents = contents.upper() # NOTE : 소문자를 대문자로 바꿔줌.\n contents = contents.replace(\" \", \"\") # NOTE : 공백 제거.\n contents = contents.replace(\"\\n\", \"\") # NOTE : 줄 띄우기 제거.\n contents = contents.replace(\"'\",\"\") # NOTE : 작은 따옴표 제거.\n contents = re.sub('[-.,\"!?:]', \"\", contents) # NOTE : 정규표현식으로 특수문자들 제거.\n\n # NOTE : 문자의 아스키 코드 값이 65를 넘으면 65를 빼줌.\n for rep in contents:\n if ord(rep) > 64:\n cha2int.append(ord(rep) - 64)\n\n # NOTE : 복호화 할때 5글자의 2진코드로 끊어서 할 수 있도록,\n # 2진코드로 변환한 결과의 길이가 5가 아니면 모자란 만큼 앞에 0을 추가하고, 모든 이진코드를 하나로 붙임.\n for rep in range(0, len(cha2int)):\n\n mesg = list(self.bin_trim(bin(cha2int[rep])))\n if len(mesg) != 5:\n for rep2 in range(0, 5-len(mesg)):\n mesg.insert(rep2, '0')\n\n mesg = ''.join(mesg)\n self.message = self.message + mesg\n\n # NOTE : 초월 증가 수열인 2의 거듭제곱승을 모아둔 리스트\n for rep in range(1, len(self.message) + 1):\n mul *= 2\n self.seq.append(mul)\n\n # NOTE : 초월 증가 수열의 합\n for rep in range(0, len(self.message)):\n sum += self.seq[rep]\n\n return sum , len(self.seq)\n\n def get_nums(self, in_message):\n\n res, seq_sum = self.message(in_message)\n\n vec = [rep for rep in range(seq_sum + 10000) if rep > seq_sum + 1] # NOTE : 초월수열의 합보다 큰 수들을 모아둔 리스트.\n pr_key1 = rand.sample(vec, 1) # NOTE : 초월수열의 합보다 큰 수들을 모아둔 리스트에서 임의로 하나를 추출하여 비밀키 중 하나로 보관.\n\n for rep in range(vec[0], pr_key1[0]):\n if self.gcd(rep, pr_key1[0]) == 1: # NOTE : 임의로 추출한 비밀키와 서로소인 수를 임의로 하나 골라서 두번째 비밀키로 보관.\n pr_key2 = rep\n\n return pr_key1[0], pr_key2\n\n def gen_key(self, in_message):\n\n self.pu_key = []\n\n self.pr_key1, pr_key2 = self.get_nums(in_message)\n\n for rep in range(1, self.pr_key1):\n if rep*pr_key2 % self.pr_key1 == 1:\n self.dec_key = rep\n\n for rep in range(0, len(self.seq)):\n b = self.seq[rep] * pr_key2 % self.pr_key1 # NOTE : 초월증가 수열의 각각의 원소들과 두번쨰 비밀키 값을 곱해 첫번째 비밀키 값으로 나누어줌.\n self.pu_key.append(b) # NOTE : 위의 설명과 같은 값을 모아둔 리스트들을 공개키로써 공개함.\n\n return len(self.pu_key), self.dec_key\n\n def enc(self, in_message):\n\n m_len, dec_key= self.gen_key(in_message)\n self.cryp = 0\n\n for rep in range(0, m_len):\n\n self.cryp = self.cryp + int(self.message[rep])*self.pu_key[rep] # NOTE : 평문을 2진 코드로 변환한 값과 공개키의 원소를 내적하여 암호화 함.\n\n int_mesg = self.cryp*dec_key % self.pr_key1\n\n return self.cryp, int_mesg\n\n def dec(self, in_message):\n\n seq = self.seq\n int_mesg = self.enc(in_message)[1]\n mesg = []\n\n for rep in range(len(seq)-1, -1, -1):\n if seq[rep] > int_mesg:\n mesg.append('0')\n else:\n int_mesg -= seq[rep]\n mesg.append('1')\n\n mesg = ''.join(mesg)\n\n\n return mesg\n\nkim = Kim_backpack()\nprint(kim.dec(\"Hae.txt\"))\n\n","sub_path":"Encrytion/Kim_Enc_class.py","file_name":"Kim_Enc_class.py","file_ext":"py","file_size_in_byte":6428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"554415785","text":"import os\nfrom collections import defaultdict\nfrom os.path import join\n\nimport click\nfrom flask import Flask\n\nfrom guniflask_cli.errors import UsageError\nfrom guniflask_cli.sqlgen import SqlToModelGenerator\n\n\n@click.group()\ndef cli_table2model():\n pass\n\n\n@cli_table2model.command('table2model')\n@click.option('-p', '--active-profiles', metavar='PROFILES', help='Active profiles (comma-separated).')\n@click.option('--no-app', default=False, is_flag=True, help='Do conversion without initializing app.')\ndef main(active_profiles, no_app):\n \"\"\"\n Convert database tables to definition of models.\n \"\"\"\n TableToModel().run(active_profiles, no_app)\n\n\nclass TableToModel:\n def run(self, active_profiles, no_app):\n if active_profiles:\n os.environ['GUNIFLASK_ACTIVE_PROFILES'] = active_profiles\n os.environ.setdefault('GUNIFLASK_ACTIVE_PROFILES', 'dev')\n\n if no_app:\n from guniflask.app import AppInitializer\n from guniflask.config import load_app_env\n load_app_env()\n app_initializer = AppInitializer()\n app = Flask(app_initializer.name)\n app_initializer._make_settings(app)\n app_initializer._init_app(app)\n else:\n from guniflask.app import create_app\n app = create_app(with_context=False)\n app_name = app.name\n with app.app_context():\n settings = app.settings\n s = app.extensions.get('sqlalchemy')\n if not s:\n raise UsageError('Did you initialize Flask-SQLAlchemy?')\n db = s.db\n default_dest = defaultdict(dict)\n binds = [None] + list(app.config.get('SQLALCHEMY_BINDS') or ())\n for b in binds:\n if b is None:\n default_dest[b] = {'dest': join(app_name, 'models')}\n else:\n default_dest[b] = {'dest': join(app_name, f'models_{b}')}\n dest_config = settings.get_by_prefix('guniflask.table2model_dest', default_dest)\n if isinstance(dest_config, str):\n default_dest[None]['dest'] = dest_config\n else:\n for b in dest_config:\n if b not in default_dest:\n raise UsageError(f'\"{b}\" is not configured in binds')\n c = dest_config[b]\n if isinstance(c, str):\n default_dest[b]['dest'] = c\n else:\n default_dest[b].update(c)\n for b in default_dest:\n c = default_dest[b]\n engine = db.engines[b]\n gen = SqlToModelGenerator(app_name, engine, bind=b)\n gen.render(join(settings['home'], c.get('dest')))\n","sub_path":"guniflask_cli/commands/table2model.py","file_name":"table2model.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"87173707","text":"\"\"\"Tapestation export functions.\"\"\"\n\nfrom genologics.entities import Process\n\nimport clarity_epp.export.utils\n\n\ndef samplesheet(lims, process_id, output_file):\n \"\"\"Create Tapestation samplesheet.\"\"\"\n process = Process(lims, id=process_id)\n well_plate = {}\n\n for placement, artifact in process.output_containers()[0].placements.iteritems():\n placement = ''.join(placement.split(':'))\n well_plate[placement] = artifact.name.split('_')[0]\n\n for well in clarity_epp.export.utils.sort_96_well_plate(well_plate.keys()):\n output_file.write('{sample}\\n'.format(\n sample=well_plate[well]\n ))\n","sub_path":"clarity_epp/export/tapestation.py","file_name":"tapestation.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"146319839","text":"# -*-coding:utf-8-*-\n\"\"\"\n作者:LYF\n日期:2021年01月28日\n\"\"\"\nimport pymysql\nimport csv\nfrom settings import *\n\n\ndef create_input_data():\n conn = pymysql.connect( # 与mysql建立连接\n host=HOST,\n port=PORT,\n user=USER,\n password=PASSWORD,\n database='wuhu',\n charset='utf8')\n cursor = conn.cursor() # 获取游标\n\n sql = 'create table input_data(' \\\n 'id tinyint unsigned not null primary key auto_increment,' \\\n 'url varchar(300),' \\\n 'jsonstr varchar(500),' \\\n 'id_data varchar(30),' \\\n 'name varchar(20),' \\\n 'danwei varchar(20));'\n try:\n cursor.execute(sql) # 执行sql语句\n conn.commit() # 提交事务\n print('input_data数据表创建成功!!!')\n except Exception as e:\n print('创建失败!!!\\n失败原因:')\n print(e)\n conn.rollback() # 回滚撤销\n finally:\n cursor.close() # 关闭游标\n conn.close() # 关闭连接\n\n\ndef sql_write(sql_str_list): # 写入数据\n conn = pymysql.connect(\n host=HOST,\n port=PORT,\n user=USER,\n password=PASSWORD,\n database='wuhu',\n charset='utf8')\n\n cursor = conn.cursor()\n sql = 'insert input_data(url, jsonstr, id_data, name, danwei) values(%s, %s, %s, %s, %s)'\n try:\n cursor.execute(sql, sql_str_list)\n conn.commit()\n except Exception as e:\n print('写入出错!!!\\n出错原因:')\n print(e)\n conn.rollback()\n finally:\n cursor.close()\n conn.close()\n\n\ndef create_wuhu():\n conn = pymysql.connect(\n host=HOST,\n port=PORT,\n user=USER,\n password=PASSWORD,\n database='sys',\n charset='utf8')\n\n cursor = conn.cursor()\n sql = 'create database wuhu;'\n try:\n cursor.execute(sql)\n conn.commit()\n print('wuhu数据库创建成功!!!')\n except Exception as e:\n print('创建出错!!!\\n出错原因:')\n print(e)\n conn.rollback()\n finally:\n cursor.close()\n conn.close()\n\n\ndef ready():\n create_wuhu() # 创建wuhu\n","sub_path":"sql_create_wuhu.py","file_name":"sql_create_wuhu.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"548375438","text":"import torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.nn.functional as F\n\nimport os\nfrom torchvision.utils import save_image\nimport glob\nimport math \nfrom sklearn.model_selection import train_test_split\nimport gc\nimport time\nimport torch.optim as optim\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import DataLoader\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom UNet_zoo.model import *\nfrom tqdm import trange\n\nepoch_train_losses = [] # Defining an empty list to store the epoch losses\nepoch_val_losses = [] \naccu_train_epoch = [] # Defining an empty list to store the accuracy per epoch\naccu_val_epoch = []\n\nmodel = U_Net()\n\ndef make_tensor(tensor):\n if torch.cuda.is_available():\n return torch.cuda.FloatTensor(tensor)\n else:\n return torch.FloatTensor(tensor)\n\nbatch_size = 1\nepochs = 1\nlr = 0.001\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\nloss = nn.BCEWithLogitsLoss() \nmodel = model.to(device)\noptimizer = torch.optim.SGD(model.parameters(), lr, momentum = 0.99)\n\ndef iou_score(output, target):\n smooth = 1e-5\n\n if torch.is_tensor(output):\n output = output.data.cpu().numpy()\n if torch.is_tensor(target):\n target = target.data.cpu().numpy()\n output_ = output > 0.5\n target_ = target > 0.5\n intersection = (output_ & target_).sum()\n union = (output_ | target_).sum()\n\n return (intersection + smooth) / (union + smooth)\n\ndef train_UNet(model, dataset, optimizer, criterion, device):\n\n train_loss_batch = []\n accu_train_batch = []\n model.train()\n for idx,(images, labels) in enumerate(dataset):\n images = images.to(device)\n labels = labels.to(device)\n\n #Forward Pass\n output = model(make_tensor(images))\n torch.clip(output, 0.0025, 0.9975) # I am clipping the output because if it becomes 0 or 1 then there is a chance that loss function can explode\n labels = torch.round(labels) # Rounding of the image pixel values to 0 or 1 since some of them had values like 0.001, 0.998 etc\n train_loss = loss(output,labels)\n train_loss_batch.append(train_loss)\n output = torch.round(output)\n acc = iou_score(output, labels)\n accu_train_batch.append(acc)\n print(f\"Batch: {idx + 1} Train Loss: {train_loss} Accuracy: {acc}\")\n # Backward\n optimizer.zero_grad()\n train_loss.backward()\n optimizer.step()\n epoch_train_losses.append(sum(train_loss_batch)/len(dataset))\n accu_train_epoch.append(sum(accu_train_batch)/len(dataset))\n print(f\"Train Epoch Loss: {sum(train_loss_batch)/len(dataset)} Train Epoch Accuracy: {sum(accu_train_batch)/len(dataset)}\")\n\ndef eval_UNet(model, dataset, criterion, device):\n\n val_loss_batch = []\n accu_val_batch = []\n model.eval()\n for idx,(images, labels) in enumerate(dataset):\n with torch.no_grad():\n images = images.to(device)\n labels = labels.to(device)\n #Forward Pass\n output = model(make_tensor(images))\n torch.clip(output, 0.0025, 0.9975)\n labels = torch.round(labels)\n # Loss\n val_loss = criterion(output,labels)\n val_loss_batch.append(val_loss)\n torch.round(output)\n acc = iou_score(output, labels)\n accu_val_batch.append(acc)\n epoch_val_losses.append((sum(val_loss_batch))/len(dataset))\n accu_val_epoch.append((sum(accu_val_batch))/len(dataset))\n print(f\"Val Epoch Loss: {(sum(val_loss_batch))/len(dataset)} Val Epoch Accuracy: {(sum(accu_val_batch))/len(dataset)}\")","sub_path":"src/UNet_zoo/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"335506259","text":"# -*- coding: utf-8 -*-\n# Minio Python Library for Amazon S3 compatible cloud storage, (C) 2015 Minio, Inc.\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\nimport sys\nimport io\nimport platform\n\nimport urllib3\nimport certifi\n\n__author__ = \"Minio, Inc.\"\n\nfrom io import RawIOBase\n\nfrom .__version__ import get_version\nfrom .acl import is_valid_acl\nfrom .compat import urlsplit, strtype\nfrom .generators import (ListObjectsIterator, ListIncompleteUploads,\n ListUploadParts, DataStreamer)\nfrom .helpers import (get_target_url, is_non_empty_string, is_valid_url,\n get_sha256, encode_to_base64, get_md5,\n calculate_part_size, encode_to_hex,\n is_valid_bucket_name, get_region)\nfrom .parsers import (parse_list_buckets, parse_acl, parse_error,\n parse_new_multipart_upload)\nfrom .error import ResponseError\nfrom .definitions import Object\nfrom .signer import sign_v4\nfrom .xml_requests import bucket_constraint, get_complete_multipart_upload\n\nclass Minio(object):\n def __init__(self, url, access_key=None, secret_key=None, certs=None):\n \"\"\"\n Creates a new cloud storage client.\n\n Examples:\n\n client = Minio('https://play.minio.io:9000')\n client = Minio('https://s3.amazonaws.com', 'ACCESS_KEY', 'SECRET_KEY')\n\n :param url: A string of the URL of the cloud storage server.\n :param access_key: Access key to sign self._http.request with.\n :param secret_key: Secret key to sign self._http.request with.\n :param certs: Path to SSL certificates\n :return: Minio object\n \"\"\"\n is_valid_url(url)\n\n url_components = urlsplit(url)\n self._location = url_components.netloc\n self._endpoint_url = url_components.geturl()\n self._access_key = access_key\n self._secret_key = secret_key\n self._user_agent = 'minio-py/' + get_version() + \\\n ' (' + platform.system() + '; ' + \\\n platform.machine() + ')'\n if certs is None:\n certs = certifi.where()\n\n self._http = urllib3.PoolManager(\n cert_reqs='CERT_REQUIRED',\n ca_certs=certs\n )\n\n # Client level\n def set_user_agent(self, name=None, version=None, comments=None):\n \"\"\"\n Adds an entry to the list of user agents.\n\n Example:\n minio.add_user_agent('my_app', '1.0.0', ['ex', 'parrot'])\n # Results in my_app/1.0.0 (ex; parrot) appended to user agent\n\n :param name: user agent name\n :param version: user agent version\n :param comments: list of comments to include in comments section\n :return: None\n \"\"\"\n if name is None or version is None:\n raise TypeError()\n if not isinstance(name, strtype) or \\\n not isinstance(version, strtype):\n raise TypeError()\n if not name.strip() or not version.strip():\n raise ValueError()\n\n if comments is not None:\n joined_comments = '; '.join(comments)\n components = [' ', name, '/', version, ' (', joined_comments, ')']\n self._user_agent += ''.join(components)\n else:\n components = [' ', name, '/', version, ' ']\n self._user_agent += ''.join(components)\n\n # Bucket level\n def make_bucket(self, bucket, acl=None):\n \"\"\"\n Make a new bucket on the server.\n\n Optionally include an ACL. Valid ACLs are as follows:\n\n Acl.public_read_write()\n Acl.public_read()\n Acl.authenticated_read()\n Acl.private()\n\n Examples:\n minio.make_bucket('foo')\n minio.make_bucket('foo', Acl.public_read())\n\n :param bucket: Bucket to create on server\n :param acl: Canned ACL to use. Default is Acl.private()\n :return:\n \"\"\"\n is_valid_bucket_name(bucket)\n if acl is not None:\n is_valid_acl(acl)\n\n method = 'PUT'\n url = get_target_url(self._endpoint_url, bucket=bucket)\n headers = {}\n\n if acl is not None:\n headers['x-amz-acl'] = acl\n\n region = get_region(self._location)\n\n content = ''\n if not (region == 'us-east-1' or region == 'milkyway'):\n content = bucket_constraint(region)\n headers['Content-Length'] = str(len(content))\n\n content_sha256 = get_sha256(content)\n if content.strip():\n content_md5 = encode_to_base64(get_md5(content))\n headers['Content-MD5'] = content_md5\n\n headers = sign_v4(method=method, url=url, headers=headers,\n access_key=self._access_key,\n secret_key=self._secret_key,\n content_hash=content_sha256)\n\n response = self._http.urlopen(method, url, body=content,\n headers=headers)\n\n if response.status != 200:\n parse_error(response, bucket)\n\n def list_buckets(self):\n \"\"\"\n List all buckets owned by the user.\n\n\n Example:\n bucket_list = minio.list_buckets()\n for bucket in bucket_list:\n print bucket.name,bucket.created_date\n\n :return: A list of buckets owned by the current user.\n \"\"\"\n url = get_target_url(self._endpoint_url)\n method = 'GET'\n headers = {}\n\n headers = sign_v4(method=method, url=url, headers=headers,\n access_key=self._access_key,\n secret_key=self._secret_key)\n\n response = self._http.request(method, url, headers=headers,\n redirect=False)\n\n if response.status != 200:\n try:\n parse_error(response)\n except ResponseError as err:\n if err.code == 'Redirect':\n err.code = 'AccessDeniedException'\n raise err\n return parse_list_buckets(response.data)\n\n def bucket_exists(self, bucket):\n \"\"\"\n Check if the bucket exists and if the user has access to it.\n\n :param bucket: To test the existence and user access.\n :return: True on success. Otherwise, returns False\n \"\"\"\n is_valid_bucket_name(bucket)\n\n method = 'HEAD'\n url = get_target_url(self._endpoint_url, bucket=bucket)\n headers = {}\n\n headers = sign_v4(method=method, url=url, headers=headers,\n access_key=self._access_key,\n secret_key=self._secret_key)\n\n response = self._http.request(method, url, headers=headers)\n\n if response.status != 200:\n if response.status == \"404\":\n return False\n parse_error(response, bucket)\n\n return True\n\n def remove_bucket(self, bucket):\n \"\"\"\n Remove a bucket.\n\n :param bucket: Bucket to remove\n :return: None\n \"\"\"\n is_valid_bucket_name(bucket)\n\n method = 'DELETE'\n url = get_target_url(self._endpoint_url, bucket=bucket)\n headers = {}\n\n headers = sign_v4(method=method, url=url, headers=headers,\n access_key=self._access_key,\n secret_key=self._secret_key)\n\n response = self._http.request(method, url, headers=headers)\n\n if response.status != 204:\n parse_error(response, bucket)\n\n def get_bucket_acl(self, bucket):\n \"\"\"\n Get a bucket's canned ACL, if any.\n\n Example:\n canned_acl = minio.get_bucket_acl('foo')\n if canned_acl == Acl.private():\n # do something\n\n :param bucket: Bucket to check canned ACL of.\n :return: A string representing canned ACL on the bucket.\n \"\"\"\n is_valid_bucket_name(bucket)\n\n method = 'GET'\n url = get_target_url(self._endpoint_url, bucket=bucket,\n query={\"acl\": None})\n headers = {}\n\n headers = sign_v4(method=method, url=url, headers=headers,\n access_key=self._access_key,\n secret_key=self._secret_key)\n\n response = self._http.request(method, url, headers=headers)\n\n if response.status != 200:\n parse_error(response, bucket)\n\n return parse_acl(response.data)\n\n def set_bucket_acl(self, bucket, acl):\n \"\"\"\n Set a bucket's canned acl\n\n Valid ACLs include:\n Acl.public_read_write()\n Acl.public_read()\n Acl.authenticated_read()\n Acl.private()\n\n Example:\n canned_acl = minio.get_bucket_acl('foo')\n if canned_acl == Acl.private():\n # do something\n\n :param bucket: Bucket to set\n :param acl: ACL to set\n :return: None\n \"\"\"\n is_valid_bucket_name(bucket)\n is_valid_acl(acl)\n\n method = 'PUT'\n url = get_target_url(self._endpoint_url, bucket=bucket,\n query={\"acl\": None})\n\n headers = {\n 'x-amz-acl': acl,\n }\n\n headers = sign_v4(method=method, url=url, headers=headers,\n access_key=self._access_key,\n secret_key=self._secret_key)\n\n response = self._http.urlopen(method, url, headers=headers)\n\n if response.status != 200:\n parse_error(response, bucket)\n\n def drop_all_incomplete_uploads(self, bucket):\n \"\"\"\n Drop all incomplete uploads in a bucket.\n\n :param bucket: Bucket to drop all incomplete uploads.\n :return: None\n \"\"\"\n # check bucket\n is_valid_bucket_name(bucket)\n\n uploads = ListIncompleteUploads(self._http, self._endpoint_url,\n bucket, None,\n access_key=self._access_key,\n secret_key=self._secret_key)\n\n for upload in uploads:\n self._drop_incomplete_upload(bucket, upload.key, upload.upload_id)\n\n def get_object(self, bucket, key):\n \"\"\"\n Retrieves an object from a bucket.\n\n Examples:\n my_partial_object = minio.get_partial_object('foo', 'bar')\n\n :param bucket: Bucket to retrieve object from\n :param key: Key to retrieve\n :return: An iterable containing a byte stream of the data.\n \"\"\"\n return self.get_partial_object(bucket, key)\n\n # Object Level\n def get_partial_object(self, bucket, key, offset=0, length=0):\n \"\"\"\n Retrieves an object from a bucket.\n\n Optionally takes an offset and length of data to retrieve.\n\n Examples:\n my_partial_object = minio.get_partial_object('foo', 'bar', 2, 4)\n\n :param bucket: Bucket to retrieve object from\n :param key: Key to retrieve\n :param offset: Optional offset to retrieve bytes from. Must be >= 0\n :param length: Optional number of bytes to retrieve. Must be > 0\n :return: An iterable containing a byte stream of the data.\n \"\"\"\n is_valid_bucket_name(bucket)\n is_non_empty_string(key)\n\n request_range = ''\n if offset is not 0 and length is not 0:\n request_range = str(offset) + \"-\" + str(offset + length - 1)\n if offset is not 0 and length is 0:\n request_range = str(offset) + \"-\"\n if offset is 0 and length is not 0:\n request_range = \"0-\" + str(length - 1)\n\n method = 'GET'\n url = get_target_url(self._endpoint_url, bucket=bucket, key=key)\n headers = {}\n\n if request_range:\n headers['Range'] = 'bytes=' + request_range\n\n headers = sign_v4(method=method, url=url, headers=headers,\n access_key=self._access_key,\n secret_key=self._secret_key)\n\n response = self._http.urlopen(method, url, headers=headers,\n preload_content=False)\n\n if response.status != 206 and response.status != 200:\n parse_error(response, bucket+\"/\"+key)\n\n return DataStreamer(response)\n\n def put_object(self, bucket, key, length, data,\n content_type=\"application/octet-stream\"):\n \"\"\"\n Add a new object to the cloud storage server.\n\n Data can either be a string, byte array, or reader (e.g. open('foo'))\n\n Examples:\n minio.put('foo', 'bar', 11, 'hello world')\n\n minio.put('foo', 'bar', 11, b'hello world', 'text/plain')\n\n with open('hello.txt', 'rb') as data:\n minio.put('foo', 'bar', 11, b'hello world', 'text/plain')\n\n :param bucket: Bucket of new object.\n :param key: Key of new object.\n :param length: Total length of object.\n :param data: Contents to upload.\n :param content_type: mime type of object as a string.\n :return: None\n \"\"\"\n is_valid_bucket_name(bucket)\n is_non_empty_string(key)\n\n if length is 0:\n raise ValueError('length')\n\n if length <= 5 * 1024 * 1024:\n # reference 'file' for python 2.7 compatibility, RawIOBase for 3.X\n if type(data).__name__ == 'file' or \\\n isinstance(data, io.BufferedReader):\n data = data.read(length)\n if isinstance(data, io.TextIOWrapper):\n data = data.read(length).encode('utf-8')\n if sys.version_info >= (3, 0) and isinstance(data, strtype):\n data = data.encode('utf-8')\n return self._do_put_object(bucket, key, length, data, content_type)\n self._stream_put_object(bucket, key, length, data, content_type)\n\n def list_objects(self, bucket, prefix=None, recursive=False):\n \"\"\"\n List objects in the given bucket.\n\n Examples:\n objects = minio.list_objects('foo')\n for current_object in objects:\n print current_object\n # hello\n # hello/\n # hello/\n # world/\n\n objects = minio.list_objects('foo', prefix='hello/')\n for current_object in objects:\n print current_object\n # hello/world/\n\n objects = minio.list_objects('foo', recursive=True)\n for current_object in objects:\n print current_object\n # hello/world/1\n # world/world/2\n # ...\n\n objects = minio.list_objects('foo', prefix='hello/',\n recursive=True)\n for current_object in objects:\n print current_object\n # hello/world/1\n # hello/world/2\n\n :param bucket: Bucket to list objects from\n :param prefix: String specifying objects returned must begin with\n :param recursive: If yes, returns all objects for a specified prefix\n :return: An iterator of objects in alphabetical order.\n \"\"\"\n is_valid_bucket_name(bucket)\n return ListObjectsIterator(self._http, self._endpoint_url, bucket,\n prefix, recursive, self._access_key,\n self._secret_key)\n\n def stat_object(self, bucket, key):\n \"\"\"\n Check if an object exists.\n\n :param bucket: Bucket of object.\n :param key: Key of object\n :return: Object metadata if object exists\n \"\"\"\n is_valid_bucket_name(bucket)\n is_non_empty_string(key)\n\n method = 'HEAD'\n url = get_target_url(self._endpoint_url, bucket=bucket, key=key)\n headers = {}\n\n headers = sign_v4(method=method, url=url, headers=headers,\n access_key=self._access_key,\n secret_key=self._secret_key)\n\n response = self._http.request(method, url, headers=headers)\n\n if response.status != 200:\n parse_error(response, bucket+\"/\"+key)\n\n content_type = response.headers['Content-Type']\n etag = response.headers['ETag'].replace('\"', '')\n size = response.headers['Content-Length']\n last_modified = response.headers['Last-Modified']\n\n return Object(bucket, key, content_type=content_type,\n last_modified=last_modified, etag=etag, size=size)\n\n def remove_object(self, bucket, key):\n \"\"\"\n Remove an object from the bucket.\n\n :param bucket: Bucket of object to remove\n :param key: Key of object to remove\n :return: None\n \"\"\"\n is_valid_bucket_name(bucket)\n is_non_empty_string(key)\n\n method = 'DELETE'\n url = get_target_url(self._endpoint_url, bucket=bucket, key=key)\n headers = {}\n\n headers = sign_v4(method=method, url=url, headers=headers,\n access_key=self._access_key,\n secret_key=self._secret_key)\n\n response = self._http.urlopen(method, url, headers=headers)\n\n if response.status != 204:\n parse_error(response, bucket+\"/\"+key)\n\n def drop_incomplete_upload(self, bucket, key):\n \"\"\"\n Drops all in complete uploads for a given bucket and key.\n\n :param bucket: Bucket to drop incomplete uploads\n :param key: Key of object to drop incomplete uploads of\n :return: None\n \"\"\"\n is_valid_bucket_name(bucket)\n is_non_empty_string(key)\n\n # check key\n uploads = ListIncompleteUploads(self._http, self._endpoint_url,\n bucket, key,\n access_key=self._access_key,\n secret_key=self._secret_key)\n for upload in uploads:\n self._drop_incomplete_upload(bucket, upload.key, upload.upload_id)\n\n # helper functions\n\n def _do_put_object(self, bucket, key, length, data,\n content_type='application/octet-stream',\n upload_id='', part_number=0):\n method = 'PUT'\n\n if len(data) != length:\n raise DataSizeMismatchError()\n\n if upload_id.strip() and part_number is not 0:\n url = get_target_url(self._endpoint_url, bucket=bucket, key=key,\n query={'uploadId': upload_id,\n 'partNumber': part_number})\n else:\n url = get_target_url(self._endpoint_url, bucket=bucket, key=key)\n\n content_sha256 = get_sha256(data)\n content_md5 = encode_to_base64(get_md5(data))\n\n headers = {\n 'Content-Length': length,\n 'Content-Type': content_type,\n 'Content-MD5': content_md5\n }\n\n headers = sign_v4(method=method, url=url, headers=headers,\n access_key=self._access_key,\n secret_key=self._secret_key,\n content_hash=content_sha256)\n\n data = io.BytesIO(data)\n response = self._http.urlopen(method, url, headers=headers, body=data)\n\n if response.status != 200:\n parse_error(response, bucket+\"/\"+key)\n\n return response.headers['ETag'].replace('\"', '')\n\n def _stream_put_object(self, bucket, key, length, data, content_type):\n if type(data).__name__ != 'file':\n if not isinstance(data, io.BufferedReader):\n if not isinstance(data, RawIOBase):\n if sys.version_info >= (3, 0):\n if isinstance(data, strtype):\n data = data.encode('utf-8')\n data = io.BytesIO(data)\n data = io.BufferedReader(data)\n\n part_size = calculate_part_size(length)\n\n current_uploads = ListIncompleteUploads(self._http,\n self._endpoint_url,\n bucket,\n key,\n access_key=self._access_key,\n secret_key=self._secret_key)\n\n upload_id = None\n for upload in current_uploads:\n upload_id = upload.upload_id\n uploaded_parts = {}\n if upload_id is not None:\n part_iter = ListUploadParts(self._http, self._endpoint_url,\n bucket, key, upload_id,\n access_key=self._access_key,\n secret_key=self._secret_key)\n for part in part_iter:\n uploaded_parts[part.part_number] = part\n else:\n upload_id = self._new_multipart_upload(bucket, key, content_type)\n total_uploaded = 0\n current_part_number = 1\n etags = []\n while total_uploaded < length:\n current_data = data.read(part_size)\n if len(current_data) == 0:\n break\n current_data_md5 = encode_to_hex(get_md5(current_data))\n previously_uploaded_part = None\n if current_part_number in uploaded_parts:\n previously_uploaded_part = uploaded_parts[current_part_number]\n if previously_uploaded_part is None or \\\n previously_uploaded_part.etag != current_data_md5:\n etag = self._do_put_object(bucket=bucket, key=key,\n length=len(current_data),\n data=current_data,\n content_type=content_type,\n upload_id=upload_id,\n part_number=current_part_number)\n else:\n etag = previously_uploaded_part.etag\n etags.append(etag)\n total_uploaded += len(current_data)\n current_part_number += 1\n if total_uploaded != length:\n raise DataSizeMismatchError()\n self._complete_multipart_upload(bucket, key, upload_id, etags)\n\n def _drop_incomplete_upload(self, bucket, key, upload_id):\n method = 'DELETE'\n query = {\n 'uploadId': upload_id\n }\n url = get_target_url(self._endpoint_url, bucket=bucket, key=key, query=query)\n headers = {}\n\n headers = sign_v4(method=method, url=url, headers=headers,\n access_key=self._access_key,\n secret_key=self._secret_key)\n\n response = self._http.request(method, url, headers=headers)\n\n if response.status != 204:\n parse_error(response, bucket+\"/\"+key)\n\n def _new_multipart_upload(self, bucket, key, content_type):\n method = 'POST'\n query = {\n 'uploads': None\n }\n\n url = get_target_url(self._endpoint_url, bucket=bucket,\n key=key, query=query)\n\n headers = {\n 'Content-Type': content_type\n }\n\n headers = sign_v4(method=method, url=url, headers=headers,\n access_key=self._access_key,\n secret_key=self._secret_key)\n\n response = self._http.urlopen(method, url, headers=headers, body=None)\n\n if response.status != 200:\n parse_error(response, bucket+\"/\"+key)\n\n return parse_new_multipart_upload(response.data)\n\n def _complete_multipart_upload(self, bucket, key, upload_id, etags):\n method = 'POST'\n query = {\n 'uploadId': upload_id\n }\n url = get_target_url(self._endpoint_url, bucket=bucket,\n key=key, query=query)\n headers = {}\n\n data = get_complete_multipart_upload(etags)\n data_sha256 = get_sha256(data)\n data_md5 = encode_to_base64(get_md5(data))\n\n headers['Content-Length'] = len(data)\n headers['Content-Type'] = 'application/xml'\n headers['Content-MD5'] = data_md5\n\n headers = sign_v4(method=method, url=url, headers=headers,\n access_key=self._access_key,\n secret_key=self._secret_key, content_hash=data_sha256)\n\n response = self._http.urlopen(method, url, headers=headers, body=data)\n\n if response.status != 200:\n parse_error(response, bucket+\"/\"+key)\n\nclass DataSizeMismatchError(BaseException):\n pass\n","sub_path":"minio/minio.py","file_name":"minio.py","file_ext":"py","file_size_in_byte":25066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"186232579","text":"import cv2\n\ncap = cv2.VideoCapture(0) # 0 mean first webcam\n\nif cap.isOpened():\n while True:\n state, frame = cap.read()\n if state:\n cv2.imshow(\"Video\",frame)\n if cv2.waitKey(1) == 27: # click on esc to quit\n break\n cap.release()\n cv2.destroyAllWindows()\nelse:\n print('Camera not working')","sub_path":"cam_test.py","file_name":"cam_test.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"384503804","text":"import torch\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport sys\n\nmodel = \"match_pyramid_ms\" ## 10%\nvocab_file = \"../vocab_ms.index\" ## 10%\n\ndef readVocab():\n vocab = []\n fp = open(vocab_file,'r')\n for line in fp:\n psd = (line.rstrip()).split(' ')\n term = psd[1]\n vocab.append(term)\n fp.close()\n print(\"vocab read\")\n print('term of 0 index = ', vocab[0])\n return vocab\n ##\n\nif __name__ == '__main__':\n vocab = readVocab()\n num = int(sys.argv[1])\n #num = 59 # +51 -59\n# num -= 1\n fname = \"../save_\" + model + \"/result_cam.pt\" + str(num)\n res = torch.load(fname)\n\n #gdata = data['hmulti'].detach().cpu()\n #gdata = data['rmulti'].detach().cpu()\n gdata = res['embcross'].detach().cpu()\n gdata = gdata.squeeze(0)\n gdata = gdata.squeeze(0)\n \n print(gdata.shape)\n\n# gdata[gdata<0] = 0\n \n np_data = gdata.numpy()\n plt.figure(figsize=(20, 5))\n plt.axis('off')\n #ax = sns.heatmap(np_data, cmap=\"YlGnBu\", xticklabels=False, yticklabels=False, cbar=False)\n ## for mixing\n ax = sns.heatmap(np_data, cmap=\"Greys\", xticklabels=False, yticklabels=False, cbar=False)\n imgname = model + \"_heat_\" + str(num) + \".jpg\"\n plt.savefig(imgname, pad_inches=0, bbox_inches='tight')\n\n ## naive\n ax = sns.heatmap(np_data, cmap=\"Greys\")\n imgname = model + \"_heat_nomix_\" + str(num) + \".jpg\"\n plt.savefig(imgname, pad_inches=0, bbox_inches='tight')\n\n\n\n","sub_path":"eval_source/make_heatmap.py","file_name":"make_heatmap.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"534712914","text":"# Python3 code to demonstrate working of\n# Dictionary Values Mean\n# Using loop + len()\n\n# initializing dictionary\ntest_dict = {\"Gfg\" : 4, \"is\" : 7, \"Best\" : 8, \"for\" : 6, \"Geeks\" : 10}\n\n# printing original dictionary\nprint(\"The original dictionary is : \" + str(test_dict))\n\n# loop to sum all values\nres = 0\nfor val in test_dict.values():\n res += val\n\n# using len() to get total keys for mean computation\nres = res / len(test_dict)\n","sub_path":"mean2.py","file_name":"mean2.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"514918839","text":"LINES_FOR_EACH_INPUT = 1\r\nINPUT_FILE_NAME = 'A-small-attempt0.in'\r\nOUTPUT_FILE_NAME = 'A-small-attempt0.out'\r\n\r\ndef do_case(num):\r\n if(num==0):\r\n return \"INSOMNIA\"\r\n \r\n digits=[False for i in range(10)]\r\n mult=num\r\n while(not all(digits)):\r\n temp=mult\r\n while(temp>0):\r\n digits[temp%10]=True\r\n temp//=10\r\n mult+=num\r\n return str(mult-num)\r\n\r\ndef do_parse(input):\r\n return int(input[0].rstrip()) \r\n\r\ndef main():\r\n input_f = open(INPUT_FILE_NAME, 'r')\r\n output = []\r\n\t\r\n num_of_test_cases = int(input_f.readline(), 10)\r\n\t\r\n input_lines = input_f.readlines()\r\n\t\r\n for test_case in range(num_of_test_cases):\r\n parsed_input = do_parse(input_lines[test_case*LINES_FOR_EACH_INPUT : (test_case + 1) * LINES_FOR_EACH_INPUT])\r\n output.append('Case #' + str(test_case + 1) + ': ' + do_case(parsed_input))\r\n\r\n output_f = open(OUTPUT_FILE_NAME, 'w')\r\n output_f.write('\\n'.join(output))\r\n\t\r\n input_f.close()\r\n output_f.close()\r\n\t\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"solutions_5652388522229760_0/Python/romd/ssheep.py","file_name":"ssheep.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"427013336","text":"import random\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\nfrom collections import namedtuple\nimport json\n\nAttraction = namedtuple('Attraction', ['latlon', 'score', 'is_hotel', 'is_restaurant', 'metadata_google'])\n\n#####################################################################\n# K-means Clustering\n#####################################################################\ndef get_cluster_id_list(attraction_list, num_clusters):\n # use k-means clustering\n xy_list = [attraction.latlon for attraction in attraction_list]\n xy_list = np.array(xy_list)\n kmeans = KMeans(n_clusters=num_clusters).fit(xy_list)\n centroids = kmeans.cluster_centers_ \n cluster_id_list = kmeans.labels_ \n return cluster_id_list, centroids\n\ndef cluster_attraction_list(cluster_id_list, attraction_list, num_clusters):\n # seperate xys_list by clusters\n attraction_list_clusters = [[] for _ in range(num_clusters)]\n for i, attraction in enumerate(attraction_list):\n k = int(cluster_id_list[i])\n attraction_list_clusters[k].append(attraction)\n return attraction_list_clusters\n\n#####################################################################\n# Score Filtering/Curation \n#####################################################################\ndef select_locales(S, metadata):\n num_neighbors, = metadata\n S_idxs = np.argsort(S, axis=0)[-num_neighbors:]\n return S_idxs\n\ndef filter_attraction_list(attraction_list, max_itr, num_neighbors, sensitivity, bias):\n # get scores\n s_list = [attraction.score for attraction in attraction_list]\n S = np.array(s_list)\n S_original = np.array(s_list)\n\n # get distance matrix\n L = get_dists(attraction_list)\n l_avg = np.mean(L)\n\n metadata = (num_neighbors,)\n for _ in range(max_itr):\n S_idxs = select_locales(S, metadata)\n S_neighbors = ((l_avg-L)*S)[S_idxs]\n S_agg = np.sum(S_neighbors, axis=0)\n S_tilde = S_agg + bias*S_original*S_original\n #S = 10*sigmoid(sensitivity*S_tilde/np.max(S_tilde))\n S = 10*S_tilde/np.max(S_tilde)\n '''\n # iteratively refine scores\n # collect neighbor scores\n S_avg = np.mean(S)\n S_neighbors = (l_avg-L)*S# - L*(S-S_avg)\n # aggregate to top num_neighbor neighbors with the highest scores\n S_neighbors_filtered = np.sort(S_neighbors, axis=0)[-num_neighbors:]\n S_agg = np.sum(S_neighbors_filtered, axis=0)\n # bias for the original score \n S_tilde = S_agg + bias*S_original*S_original\n # normalize scores \n S_tilde = (S_tilde-np.mean(S_tilde))\n S = 10*sigmoid(sensitivity*S_tilde/np.max(S_tilde))\n '''\n \n # reconstruct xys_list (do not do in-place modification) \n xys_filtered_list = []\n for i, s in enumerate(S):\n x,y = attraction_list[i].latlon\n xys_filtered_list.append((x,y,s))\n return xys_filtered_list\n\ndef get_dists(attraction_list):\n # get l2 distance between all node pairs\n # Note: this code can be optimized in future releases\n N = len(attraction_list)\n L = np.zeros(shape=(N,N)) \n xy_list = [attraction.latlon for attraction in attraction_list]\n for i in range(N):\n for j in range(i, N):\n coord1 = np.array(xy_list[i])\n coord2 = np.array(xy_list[j])\n l = np.linalg.norm(coord1-coord2) \n L[i][j] = l\n L[j][i] = l\n return L \n\ndef sigmoid(x):\n # sigmoid function\n return 1 / (1 + np.exp(-x))\n\n#####################################################################\n# Synthetic Dataset Generation\n#####################################################################\ndef gen_syn_loc(synthetic_params, restaurant_thresh, hotel_thresh):\n assert hotel_thresh + restaurant_thresh < 1\n xys_list = []\n for param in synthetic_params:\n # generate 2D gaussian\n num_samples, mu, sigma = param\n mu_x, mu_y = mu\n sigma_x, sigma_y = sigma\n for _ in range(num_samples):\n # sample data points \n x = random.gauss(mu_x, sigma_x)\n y = random.gauss(mu_y, sigma_y)\n s = 10*random.random()\n xys_list.append((x,y,s))\n random.shuffle(xys_list)\n json_list = []\n for xys in xys_list:\n x,y,s = xys\n is_hotel = random.random() < hotel_thresh\n is_restaurant = random.random() < restaurant_thresh\n locale_type = 'hotel' if is_hotel else ('restaurant' if is_restaurant else 'other')\n metadata_google = json.dumps({'latitude': x, 'longitude':y, 'google_score': s, 'type': locale_type, 'metadata': random.random()*1000})\n json_list.append(metadata_google)\n print(json_list)\n return json_list\n\nfloat_list = lambda x_list: [float(x) for x in x_list]\ndef json2attraction(metadata_google):\n metadata_google_decoded = json.loads(metadata_google)\n\n latlon_raw = (metadata_google_decoded['latitude'],metadata_google_decoded['longitude'])\n score_raw = metadata_google_decoded['google_score']\n is_restaurant_raw = metadata_google_decoded['type'] == 'restaurant'\n is_hotel_raw = metadata_google_decoded['type'] == 'hotel'\n\n latlon = tuple(float_list(latlon_raw))\n score = float(score_raw)\n is_restaurant = bool(is_restaurant_raw)\n is_hotel = bool(is_hotel_raw)\n assert len(latlon) == 2\n return Attraction(latlon, score, is_hotel, is_restaurant, metadata_google)\n\ndef attraction2xys(attraction):\n x,y = attraction.latlon\n s = attraction.score\n return x,y,s\n\n#####################################################################\n# Plotting Utilities \n#####################################################################\ndef plot(xys_list, ax, k=None):\n color = 'grey'\n color_sel = 'red'\n if k is None:\n # setting up plottig parameters \n x_list = [xys[0] for xys in xys_list]\n y_list = [xys[1] for xys in xys_list]\n s_list = [xys[2] for xys in xys_list]\n plot_helper(x_list, y_list, s_list, ax, color)\n else:\n # setting up plottig parameters \n s_list = [xys[2] for xys in xys_list]\n s_list_topk = (np.array(s_list).argsort()[-k:][::-1]).tolist()\n x_list1, y_list1, s_list1 = [], [], []\n x_list2, y_list2, s_list2 = [], [], []\n for i, xys in enumerate(xys_list):\n x,y,s = xys\n if i in s_list_topk:\n x_list2.append(x)\n y_list2.append(y)\n s_list2.append(s)\n else:\n x_list1.append(x)\n y_list1.append(y)\n s_list1.append(s)\n plot_helper(x_list1, y_list1, s_list1, ax, color)\n plot_helper(x_list2, y_list2, s_list2, ax, color_sel)\n\ndef plot_helper(x_list, y_list, s_list, ax, color):\n # actual plotting code\n ax.scatter(x_list, y_list, c=color)\n for i, s in enumerate(s_list):\n ax.annotate('{0:.2f}'.format(s), (x_list[i], y_list[i]))\n\n#####################################################################\n# Main Function \n#####################################################################\ndef main():\n # dataset configurations\n synthetic_params = [(35, (0,-10), (5,6)), (33, (12,8), (7,7))]\n # clustering configurations\n num_days=2\n # topk?\n k = 8 \n # filtering configurations\n max_itr=5000\n num_neighbors=k\n sensitivity=8\n bias=10\n\n # generate synthetic datasets\n random.seed(123)\n json_list = gen_syn_loc(synthetic_params, 0.05, 0.1)\n \n attraction_list = [json2attraction(metadata_google) for metadata_google in json_list]\n xys_list = [attraction2xys(attraction) for attraction in attraction_list]\n\n # generate cluster by number of days\n cluster_id_list, centroids = get_cluster_id_list(attraction_list, num_days)\n attraction_list_clusters = cluster_attraction_list(cluster_id_list, attraction_list, num_days)\n\n # plotting the clusters\n xys_list_temp = xys_list.copy()\n xys_list_temp.extend([(centroid[0], centroid[1], float('inf')) for centroid in centroids])\n ax = plt.gca()\n ax.set_title('Input Scores and Cluster Centroids')\n ax.set_xlabel('X location')\n ax.set_ylabel('Y location')\n plot(xys_list_temp, ax, k=num_days)\n plt.show()\n\n for i, attraction_list in enumerate(attraction_list_clusters):\n # curate the score list of each cluster\n xys_filtered_list = filter_attraction_list(attraction_list, max_itr=max_itr, num_neighbors=num_neighbors, sensitivity=sensitivity, bias=bias)\n\n # Show the pre- and post-filtering scores and selections\n '''\n ax1 = plt.subplot(121)\n ax1.set_title('Input Scores (topk={}) for Cluster {}'.format(k, i))\n ax1.set_xlabel('X location')\n ax1.set_ylabel('Y location')\n plot(xys_list, ax1, k=k)\n '''\n ax2 = plt.subplot(111)\n ax2.set_title('Filtered Scores (topk={}) for Cluster {}'.format(k, i))\n ax2.set_xlabel('X location')\n ax2.set_ylabel('Y location')\n plot(xys_filtered_list, ax2, k=k)\n plt.show()\n\nif __name__ == '__main__':\n main()\n","sub_path":"maps/filter_scores.py","file_name":"filter_scores.py","file_ext":"py","file_size_in_byte":9095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"172497424","text":"import sys\nimport pickle\nimport argparse\nfrom sys import stdin\nfrom collections import defaultdict\n\ndef PercepClassify():\n\n parser = argparse.ArgumentParser(description='-------This is a description of %(prog)s', epilog = '-------This is a epilog of %(prog)s')\n parser.add_argument('model_path', help='path of model file')\n args = parser.parse_args()\n \n model_file_path = args.model_path\n \n with open(model_file_path, 'rb') as model_file:\n model = pickle.load(model_file)\n\n first_word = ''\n for word in model['words_cls_weight_map_dict'].keys():\n first_word = word\n break\n \n for cls in model['class_weight_map_dict'].keys():\n default_class = cls\n break\n \n for line in stdin:\n words = line.split()\n max_cls_weight_sum = -float('inf')\n result_cls = default_class\n\n for cls in model['words_cls_weight_map_dict'][first_word].keys():\n cur_cls_weight_sum = 0\n\n for word in words:\n if word in model['words_cls_weight_map_dict'].keys():\n cur_cls_weight_sum += model['words_cls_weight_map_dict'][word][cls]\n if cur_cls_weight_sum > max_cls_weight_sum:\n max_cls_weight_sum = cur_cls_weight_sum\n result_cls = cls\n\n print(result_cls) \n sys.stdout.flush() \n\n\nif __name__ == '__main__':\n PercepClassify()\n","sub_path":"NameEntity&POS/percepclassify.py","file_name":"percepclassify.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"271749563","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.common.keys import Keys\nfrom pandas import ExcelWriter\nimport pandas as pd\n\nbang=[]\ndic=pd.read_csv('dictionary.csv')\ndata=pd.read_excel('jobstreet.xlsx',index_col=0)\nprint\ntechskill=dic.technology_skill\nonegenskill=techskill[0].split(',')\nn=len(data.job_description)+1\nm=len(onegenskill)+1\ndf = pd.DataFrame({'job_description':data.job_description,\n })\nfor i in onegenskill:\n danhdau=[]\n for j in range(1,n):\n if i in data.job_description[j] or i.title() in data.job_description[j]:\n dau='x'\n else: dau=''\n danhdau.append(dau)\n df[i]=danhdau\n\n# for i in range(1,m-1):\n# k=onegenskill[i]\n# df = pd.DataFrame({'job_description':data.job_description,\n# str(k):bang[i],\n# })\n\nwriter = ExcelWriter(\"test.xlsx\")\ndf.to_excel(writer)\nwriter.save() ","sub_path":"Source/Beta/test_excel.py","file_name":"test_excel.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"376292846","text":"#!/usr/bin/env python\n\n'''\nCopyright (c) 2020 RIKEN\nAll Rights Reserved\nSee file LICENSE for details.\n\nusage: python %prog dir_to_files\nversion: Python 3.7\n'''\n\nimport os,sys,glob\nfrom Bio.Blast import NCBIXML\nimport pysam\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\nmatplotlib.rcParams['lines.linewidth']=0.5\nmatplotlib.rcParams['axes.linewidth']=0.5\nmatplotlib.rcParams['xtick.major.width']=0.5\nmatplotlib.rcParams['ytick.major.width']=0.5\nmatplotlib.rcParams['font.size']=5\n\n\n# virus fai, smrv\nvirus=[0, 8785]\nlltr=[0, 456]\nrltr=[8329, 8785]\n\nnear_len=10000\n\n# load hu genome fai\nfai={}\nf='/path_to/GRCh38_full_analysis_set_plus_decoy_hla.fa.fai' # specify path to the reference human genome index\nwith open(f) as infile:\n for line in infile:\n ls=line.split()\n fai[ls[0]]= int(ls[1])\n if 'chrY' in line:\n break\nchrs=list(fai.keys())\nchrs_set=set(chrs)\n\nchr_boxs={}\nsum_len=0\nspacer=10000000 # 10MB\nfor chr in fai:\n chr_boxs[chr]=[sum_len, fai[chr]]\n sum_len= sum_len + fai[chr] + spacer\n\nchr_extend={}\nfor chr in chr_boxs:\n chr_extend[chr]=chr_boxs[chr][0]\n\nout=[]\n\ndef plot(dir):\n try:\n # count all reads\n f='%s/mapped_to_target.bam' % dir # specify a bam file with reads mapping to viruses\n mapped_rn=set()\n with pysam.AlignmentFile(f, 'rb') as infile:\n for line in infile:\n if line.is_secondary is False:\n mapped_rn.add(line.query_name)\n \n # count hybrid reads\n f='%s/mapped_to_target_f8.bam' % dir # specify a bam file with reads mapping to viruses, must only contain reads with sam flag 8\n hybrid_n=0\n with pysam.AlignmentFile(f, 'rb') as infile:\n for line in infile:\n if line.is_secondary is False:\n hybrid_n += 1\n \n sample_id=dir.split('/')[2].split('_')[0]\n # load blastn results\n f='%s/blastn_mapped_to_target_f4_s.xml' % dir # specify a blastn output file which contains results of read-mapping to the reference human genome, must be xml format.\n mapped={}\n blast_records=NCBIXML.parse(open(f))\n for blast_record in blast_records:\n if len(blast_record.alignments) == 1:\n for alignment in blast_record.alignments:\n for hsp in alignment.hsps: # Bio.Blast.Record.HSP\n chr=alignment.title.split()[0]\n if chr in chrs_set:\n read_name=blast_record.query.split('/')[0]\n chr_pos=hsp.sbjct_end + chr_extend[chr]\n if hsp.strand[1] == 'Plus':\n chr_strand='+'\n else:\n chr_strand='-'\n mapped[read_name]=[chr_pos, chr_strand]\n\n # load mates; virus side\n f='%s/mapped_to_target_f8.bam' % dir # specify a bam file with reads mapping to viruses, must only contain reads with sam flag 8\n with pysam.AlignmentFile(f, 'rb') as infile:\n for line in infile:\n if line.query_name in mapped:\n if line.is_secondary is False:\n if line.is_reverse is False:\n virus_strand='+'\n pos=line.reference_end\n else:\n virus_strand='-'\n pos=line.reference_start\n if rltr[0] <= pos <= rltr[1]:\n pos= pos - rltr[0]\n mapped[line.query_name].append(pos)\n mapped[line.query_name].append(virus_strand)\n\n for read in mapped:\n if not len(mapped[read]) == 4:\n print(read)\n \n # identify near breakpoints\n breakpoints=set()\n for read in mapped:\n chr_pos,chr_strand,v_pos,v_strand=mapped[read]\n for r in mapped:\n if not r == read:\n chr_pos2,chr_strand2,v_pos2,v_strand2=mapped[r]\n if -1 * near_len < (chr_pos - chr_pos2) < near_len:\n if not chr_strand == chr_strand2:\n breakpoints.add(min([chr_pos, chr_pos2]))\n info='%s\\t%d\\t%d\\t%d\\t%d\\n' % (sample_id, len(mapped_rn), hybrid_n, len(mapped), len(breakpoints))\n out.append(info)\n print(info, end='')\n \n # plot\n ymax=2\n box_height=0.1\n\n fig=plt.figure(figsize=(4, 2)) # (x, y)\n ax=fig.add_subplot(111)\n\n # draw chr\n a=0.25\n for chr in chr_boxs:\n a=0.25 if a == 0.5 else 0.5\n rect=matplotlib.patches.Rectangle((chr_boxs[chr][0], 0), chr_boxs[chr][1], box_height, color='k', alpha=a, ec=None)\n ax.add_patch(rect)\n xmax= chr_boxs[chr][0] + chr_boxs[chr][1]\n vpos_coeff= np.floor(xmax / virus[1])\n\n # draw virus\n rect=matplotlib.patches.Rectangle((virus[0] * vpos_coeff, ymax - box_height), (virus[1] - virus[0]) * vpos_coeff, box_height, color='tab:gray', alpha=0.25, ec=None)\n ax.add_patch(rect)\n rect=matplotlib.patches.Rectangle((lltr[0] * vpos_coeff, ymax - box_height), (lltr[1] - lltr[0]) * vpos_coeff, box_height, color='tab:gray', alpha=0.5, ec=None)\n ax.add_patch(rect)\n rect=matplotlib.patches.Rectangle((rltr[0] * vpos_coeff, ymax - box_height), (rltr[1] - rltr[0]) * vpos_coeff, box_height, color='tab:gray', alpha=0.5, ec=None)\n ax.add_patch(rect)\n\n scatter_pos_x,scatter_pos_y,scatter_neg_x,scatter_neg_y=[],[],[],[]\n for read in mapped:\n chr_pos,chr_strand,v_pos,v_strand=mapped[read]\n if chr_strand == '+':\n scatter_pos_x.append(chr_pos)\n scatter_pos_y.append(box_height)\n y_pos1=box_height\n else:\n scatter_neg_x.append(chr_pos)\n scatter_neg_y.append(0)\n y_pos1=0\n if v_strand == '+':\n scatter_pos_x.append(v_pos * vpos_coeff)\n scatter_pos_y.append(ymax)\n y_pos2=ymax\n else:\n scatter_neg_x.append(v_pos * vpos_coeff)\n scatter_neg_y.append(ymax - box_height)\n y_pos2=ymax - box_height\n ax.plot([chr_pos, v_pos * vpos_coeff], [y_pos1, y_pos2], color='tab:gray', linewidth=0.25, alpha=0.25)\n\n ax.scatter(scatter_pos_x, scatter_pos_y, s=5, c='dodgerblue', alpha=0.25)\n ax.scatter(scatter_neg_x, scatter_neg_y, s=5, c='orangered', alpha=0.25)\n \n for pos in breakpoints:\n ax.plot([pos, pos], [0, box_height], color='k', linewidth=0.5, alpha=0.75)\n \n plt.suptitle(sample_id)\n plt.savefig('%s/plot_%s_smrv_hybrid.pdf' % (dir, sample_id))\n plt.close()\n except:\n info='%s\\t%d\\t%d\\tNA\\tNA\\n' % (sample_id, len(mapped_rn), hybrid_n)\n out.append(info)\n print(info, end='')\n\n\ndir=sys.argv[1]\nplot(dir)\n\nwith open('1kGP_smrv_hybrid_summary.txt', 'w') as outfile:\n outfile.write(''.join(out))\n","sub_path":"scripts/visualize_chr_virus_hybrid_reads/plot_SMRV_hybrid_reads.py","file_name":"plot_SMRV_hybrid_reads.py","file_ext":"py","file_size_in_byte":7265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"369885450","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom .models import Snippet, Tag, search_snippets_for_user\nfrom users.models import User\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import SnippetForm\n\n\n\ndef home_page(request):\n if request.user.is_authenticated:\n return redirect(to='list_snippet')\n\n return render(request, \"snippets/home_page.html\")\n\ndef login(request):\n return render(request, \"snippets/login.html\")\n\n\n@login_required\ndef profile_page(request):\n return render(request, \"snippets/profile_page.html\")\n\n\n@login_required\ndef list_snippet(request):\n snippets = request.user.snippets.all()\n return render(request, \"snippets/list_snippet.html\", {'snippets': snippets})\n\n\n@login_required\ndef snippet_detail(request, snippet_pk):\n snippet = get_object_or_404(request.user.snippets, pk=snippet_pk)\n return render(request, \"snippets/snippet_detail.html\", {'snippet': snippet})\n\n\n@login_required\ndef add_snippet(request):\n if request.method == \"POST\":\n form = SnippetForm(data=request.POST)\n if form.is_valid():\n snippet = form.save(commit=False)\n snippet.user = request.user\n snippet.save()\n snippet.set_tag_names(form.cleaned_data['tag_names'])\n return redirect(to='snippet_detail', snippet_pk=snippet.pk)\n else:\n form = SnippetForm()\n \n return render(request, 'snippets/add_snippet.html', {'form': form})\n\n\n@login_required\ndef edit_snippet(request, snippet_pk):\n snippet = get_object_or_404(request.user.snippets, pk=snippet_pk)\n \n if request.method == \"POST\":\n form = SnippetForm(instance=snippet, data=request.POST)\n if form.is_valid():\n snippet = form.save()\n snippet.set_tag_names(form.cleaned_data['tag_names'])\n return redirect(to='snippet_detail', snippet_pk=snippet.pk)\n\n else:\n form = SnippetForm(instance=snippet, initial={\"tag_names\": snippet.get_tag_names()})\n \n return render(request, \"snippets/edit_snippet.html\", {'form': form, 'snippet': snippet})\n\n\n@login_required\ndef delete_snippet(request, snippet_pk):\n snippet = get_object_or_404(request.user.snippets, pk=snippet_pk)\n\n if request.method == 'POST':\n snippet.delete()\n return redirect(to='list_snippet')\n\n return render(request, \"snippets/delete_snippet.html\", {'snippet': snippet})\n\n\n@login_required\ndef show_tag(request, tag_name):\n tag = get_object_or_404(Tag, tag=tag_name)\n snippets = tag.snippets.filter(user=request.user)\n return render(request, \"snippets/tag_detail.html\", {\"tag\": tag, 'snippets': snippets})\n\n\n@login_required\ndef search_snippets(request):\n query = request.GET.get('q')\n\n if query is not None:\n snippets = search_snippets_for_user(request.user, query)\n else:\n snippets = None\n \n return render(request, \"snippets/search.html\", {\"snippets\":snippets, \"query\":query})","sub_path":"snippets/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"490759398","text":"import os\nimport sys\nimport syslog\n\nfrom gtts import gTTS\nfrom io import BytesIO\nimport pygame\nimport hashlib\nimport pydub\n\ndef playNag(message):\n \n print(\"nagger.playNag(%s)\" % message)\n \n filename = \"/tmp/abafilter_nag_%s.wav\" % hashlib.md5(message.encode('utf-8')).hexdigest()\n \n if not os.path.exists(filename):\n print (filename, \"not found. Generating\")\n \n myobj = gTTS(text=message, lang='en', slow=False)\n myobj.save(\"/tmp/abafilter_nag_temp.mp3\")\n sound = pydub.AudioSegment.from_mp3(\"/tmp/abafilter_nag_temp.mp3\")\n sound.export(filename, format=\"wav\")\n \n pygame.mixer.init(24000, -16, 1, 2048)\n clock = pygame.time.Clock()\n\n try:\n pygame.mixer.music.load(filename)\n except pygame.error:\n print(\"nagger.playNag(%s) ERROR\" % message, pygame.get_error())\n return\n \n pygame.mixer.music.play()\n \n while pygame.mixer.music.get_busy():\n # check if playback has finished\n clock.tick(30)\n \n print(\"nagger.playNag(%s) done\" % message)\n\n\nplayNag(\"this is a test\")\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"369330896","text":"from sqlite3 import dbapi2\n\nfrom reportlab.lib import colors\nfrom reportlab.lib.pagesizes import A4\nfrom reportlab.platypus import (SimpleDocTemplate, PageBreak, TableStyle, Table)\n\n\nclass GenerarProductos():\n def __init__(self):\n listaInventario = []\n listaInventario.append(list(['Listado de Productos', '', '', '']))\n listaInventario.append(list(['Nombre', 'Descripción', 'Precio', 'Stock']))\n\n try:\n baseDatos = dbapi2.connect(\"base.dat\")\n cursor = baseDatos.cursor()\n productos = cursor.execute(\"select name, desc, precio, stock from productos\")\n for producto in productos:\n listaInventario.append(list([producto[0], producto[1], str(producto[2]), str(producto[3])]))\n except (dbapi2.DatabaseError) as error:\n print(error)\n finally:\n cursor.close()\n baseDatos.close()\n\n doc = SimpleDocTemplate(\"export/listadoProductos.pdf\", pagesize=A4)\n guion = []\n taboa = Table(listaInventario, colWidths=150, rowHeights=30)\n taboa.setStyle(TableStyle([\n ('TEXTCOLOR', (0, 0), (-1, 1), colors.green),\n ('TEXTCOLOR', (0, 4), (-1, -1), colors.black),\n # ('BOX', (0, 2), (-1, -4), 1, colors.black),\n ('INNERGRID', (0, 2), (-1, -1), 0.5, colors.grey),\n ('FONTSIZE', (0, 0), (-1, -1), 8),\n ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),\n ('ALIGN', (0, 0), (-1, -1), 'CENTER')\n ]))\n guion.append(taboa)\n guion.append(PageBreak())\n doc.build(guion)\n\n\nif __name__ == \"__main__\":\n GenerarProductos()\n","sub_path":"scripts/generarListadoProductos.py","file_name":"generarListadoProductos.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"208438817","text":"#Basic if statement\nnumber = 5\nif number == 5:\n print(\"Number is 5\")\nelse:\n print(\"Number is NOT 5\")\n\n#Truthy and Falsey\nif number:\n print(\"Number is defined as truthy\")\n #any number other than 0\n\ntext = \"python\"\nif python:\n print(\"Text is defined as truthy\")\n #any value that is not an empty string\n\n#Boolean and None\npython_course = True\nif python_course:\n print(\"This will execute\")\n\naliens_found = None\nif aliens_found:\n print(\"This code will NOT execute\")\n\n#Not if\nnumber = 5\nif number != 5:\n print(\"This code will NOT execute\")\n\npython_course = True\nif not python_course:\n print(\"This code will NOT execute\")\n\n#Multiple if conditions\nnumber = 3\npython_course = True\nif number == 3 and python_course:\n print(\"This code will execute\")\n\nif number == 17 or python_course:\n print(\"This code will also execute\")\n\n#Ternary if statement\na = 1\nb = 2\n\"bigger\" if a > b else \"smaller\"","sub_path":"pluralsight/if.py","file_name":"if.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"198486774","text":"\nimport ssl\nimport sys\nfrom easywiki import wiki_data\n\nsys.tracebacklimit= None\n\n\n\nsiteDefault=\"https://en.wikipedia.org/wiki/\"\n\nsearchSpecialBeg=\"https://en.wikipedia.org/w/index.php?search=\"\nsearchSpecialEnd=\"&title=Special%3ASearch&fulltext=1\"\n\ndef main():\n try:\n if len(sys.argv) > 2:\n raise Exception(\n \"too many arguments usage: wiki_data.py \\n[use \\\" \\\" to enclose argument with spaces]\")\n else:\n searchItem = sys.argv[1]\n\n status = wiki_data.getResult(siteDefault, searchItem)\n if status == 0:\n key = wiki_data.getSpecialResult(searchSpecialBeg, searchSpecialEnd, searchItem)\n wiki_data.getResult(siteDefault, key)\n\n\n\n except IndexError:\n print(\"usage: wiki_data.py \\n[use \\\" \\\" to enclose argument with spaces]\")\n\nif __name__ == '__main__':\n main()","sub_path":"easywiki/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"232602448","text":"#importing library file\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nimport seaborn as sns\nfrom sklearn.svm import SVC\n\n\n#loading iris dataset\nirisdataset = sns.load_dataset('iris')\n\n#printing the 1st five data\nprint (irisdataset.head())\n#printing the description of the data\nprint(irisdataset.describe())\n#shows the name of the species by uniqueifying\nprint(irisdataset['species'].unique())\n\n#counts members under each species\nsns.countplot(x='species',data=irisdataset)\nplt.show()\n\n#taking the values of different variables\nX = irisdataset[['sepal_length', 'sepal_width', 'petal_length', 'petal_width']]\ny = irisdataset['species']\n\n#splitting the dataset into train data and test data\nX_train, X_test, y_train, y_test = train_test_split(X, y)\n\n#using linear kernel as support vector machine\nsvm = SVC(kernel='linear', random_state=0, C=1)\n#fitting the model with the train data\nsvm.fit(X_train, y_train)\n\n#printing the accuracy for train and test data set\nprint('Accuracy of SVM classifier on training set: {:.2f}'\n .format(svm.score(X_train, y_train)))\nprint('Accuracy of SVM classifier on test set: {:.2f}'\n .format(svm.score(X_test, y_test)))\n\n\n","sub_path":"ICP6/ICP6_2_svm_iris.py","file_name":"ICP6_2_svm_iris.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"245445882","text":"# https://docs.python.org/3/library/sqlite3.html#module-sqlite3\r\n# https://sqlitestudio.pl/index.rvt?act=download\r\nimport sqlite3\r\nimport telebot\r\n\r\nbot = telebot.TeleBot(\"token\")\r\n\r\nconn = sqlite3.connect('db/database.db', check_same_thread=False)\r\ncursor = conn.cursor()\r\n\r\ndef db_table_val(user_id: int, user_name: str, user_surname: str, username: str):\r\n\tcursor.execute('INSERT INTO test (user_id, user_name, user_surname, username) VALUES (?, ?, ?, ?)', (user_id, user_name, user_surname, username))\r\n\tconn.commit()\r\n\r\n\r\n@bot.message_handler(commands=['start'])\r\ndef start_message(message):\r\n\tbot.send_message(message.chat.id, 'Добро пожаловать')\r\n\r\n\r\n@bot.message_handler(content_types=['text'])\r\ndef get_text_messages(message):\r\n\tif message.text.lower() == 'привет':\r\n\t\tbot.send_message(message.chat.id, 'Привет! Ваше имя добавлено в базу данных!')\r\n\t\t\r\n\t\tus_id = message.from_user.id\r\n\t\tus_name = message.from_user.first_name\r\n\t\tus_sname = message.from_user.last_name\r\n\t\tusername = message.from_user.username\r\n\t\t\r\n\t\tdb_table_val(user_id=us_id, user_name=us_name, user_surname=us_sname, username=username)\r\n\r\n\r\nbot.polling(none_stop=True)\r\n\r\n\r\n\r\n","sub_path":"lesson45.py","file_name":"lesson45.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"583792280","text":"from django.db import models\nimport datetime\nfrom django.core.validators import MaxValueValidator, MinValueValidator\nfrom pedidos import config\nfrom pedidos import models as pLabModel\nfrom pedidos.models import PedidoAlaboratorio\nfrom pedidos.models import PedidoDeClinica\nfrom django.db.models import Avg, Max, Min, Sum\n\n\nclass Factura(models.Model):\n\n TIPO = (\n (1, \"A\"),\n (2, \"B\"),\n (3, \"C\")\n )\n tipo = models.PositiveIntegerField(choices=TIPO)\n fecha = models.DateField()\n cuit = models.CharField(max_length=45)\n pagada = models.BooleanField(default=False)\n\n class Meta:\n abstract = True\n\nclass DetalleFactura(models.Model):\n\n cantidad = models.PositiveIntegerField(validators=[MinValueValidator(1),\n MaxValueValidator(config.MAXIMA_CANTIDAD_MEDICAMENTOS)])\n precioUnitario = models.DecimalField(max_digits=8, decimal_places=2, default=0)\n importe = models.DecimalField(max_digits=8, decimal_places=2, default=0)\n class Meta:\n abstract = True\n\nclass PieDeFactura(models.Model):\n subtotal = models.DecimalField(max_digits=8, decimal_places=2, default=0)\n iva = models.DecimalField(max_digits=8, decimal_places=2, default=0)\n total = models.DecimalField(max_digits=8, decimal_places=2, default=0)\n class Meta:\n abstract = True\n\n\n#==================================CONCRETAS============================================================================\n\n#============================================FACTURA DE PROVEEDORES=====================================================\nclass FacturaDeProveedor(Factura):\n\n nroFactura = models.CharField(max_length=45,primary_key=True)\n pedidoRel = models.OneToOneField(PedidoAlaboratorio,null=True)\n\n def __str__(self):\n return \"%s - %s %s\" % (self.tipo, self.nroFactura, self.cuit)\n\n def get_detalles(self):\n response = []\n if self.nroFactura:\n response = DetalleFacturaDeProveedor.objects.filter(factura=self)\n return response\n\n\nclass DetalleFacturaDeProveedor(DetalleFactura):\n renglon = models.AutoField(primary_key=True)\n medicamento = models.ForeignKey('medicamentos.Medicamento')\n factura = models.ForeignKey('FacturaDeProveedor', null=True, on_delete=models.CASCADE)\n\n\nclass pieDeFacturaDeProveedor(PieDeFactura):\n FILTROS = [\"desde\", \"hasta\"]\n FILTERMAPPER = {\n 'desde': \"factura__fecha__gte\",\n 'hasta': \"factura__fecha__lte\",\n }\n factura = models.OneToOneField('FacturaDeProveedor',null=True)\n\n #Facturas que se pagaron entre dos fechas determinadas.\n #Precondicion las fechas deben tener el formato 'xxxx-xx-xx'.\n def get_facturasPagadas(self,fechaInicial,fechaFinal):\n return pieDeFacturaDeProveedor.objects.filter(\n factura__fecha__range=[fechaInicial,fechaFinal],\n factura__pagada=True)\n\n def get_cantidad_facturasPagadas(self,fechaInicial,fechaFinal):\n return pieDeFacturaDeProveedor.objects.filter(\n factura__fecha__range=[fechaInicial,fechaFinal],\n factura__pagada=True).count()\n\n def get_facturasImpagas(self,fechaInicial,fechaFinal):\n return pieDeFacturaDeProveedor.objects.filter(\n factura__fecha__range=[fechaInicial,fechaFinal],\n factura__pagada=False)\n\n def get_cantidad_facturasImpagas(self,fechaInicial,fechaFinal):\n return pieDeFacturaDeProveedor.objects.filter(\n factura__fecha__range=[fechaInicial,fechaFinal],\n factura__pagada=False).count()\n\n def get_totalFacturasPagadas(self):\n return pieDeFacturaDeProveedor.objects.filter(factura__pagada=True)\n\n def get_totalFacturasImpagas(self):\n return pieDeFacturaDeProveedor.objects.filter(factura__pagada=False)\n\n def get_monto_pagado_entre(self,fechaInicial,fechaFinal):\n resultDic=pieDeFacturaDeProveedor.objects.filter(\n factura__fecha__range=[fechaInicial,fechaFinal],\n factura__pagada=True).aggregate(Sum('total'))\n return resultDic['total__sum']\n\n def get_monto_a_pagar(self):\n resultDic=pieDeFacturaDeProveedor.objects.filter(factura__pagada=False).aggregate(Sum('total'))\n return resultDic['total__sum']\n\n #Cuanto se le pago a un proovedor entre dos fechas determinadas\n def get_monto_pagados_aProv_entre(self,proveedor,fechaInicial,fechaFinal):\n resultDic = pieDeFacturaDeProveedor.objects.filter(\n factura__fecha__range=[fechaInicial,fechaFinal],\n factura__pagada=True,\n factura__pedidoRel__laboratorio__razonSocial=proveedor\n ).aggregate(Sum('total'))\n return resultDic['total__sum']\n\n #Ranking de montos pagados a proveedores entre dos fechas determinadas.\n def get_rank_montosPagos_aProv_entre(self,fechaInicial,fechaFinal):\n pagadas = pieDeFacturaDeProveedor.objects.filter(\n factura__fecha__range=[fechaInicial,fechaFinal],\n factura__pagada=True\n )\n resumen={}\n for pagada in pagadas:\n proveedor=pagada.factura.pedidoRel.laboratorio.razonSocial\n if not proveedor in resumen:\n resumen[proveedor]=self.monto_pagados_aProv_entre(proveedor,fechaInicial,fechaFinal)\n\n ranking=resumen.items()\n ranking.sort(key=lambda x: x[1],reverse=True)#Ordenado de mayor a menor segun monto que se le pago\n return ranking\n\n #Proveedor al que mas se le pago entre dos fechas determinadas\n def get_max_montoPagado_aProv_entre(self,fechaInicial,fechaFinal):\n ranking = self.rank_montosPagos_aProv_entre(fechaInicial,fechaFinal)\n return ranking[0]\n\n\n\n#====================================FACTURACION A CLINICA===================================================\nclass FacturaAclinica(Factura):\n nroFactura=models.AutoField(primary_key=True)\n pedidoRel = models.OneToOneField(PedidoDeClinica,null=True)\n\n def __str__(self):\n return \"%s - %s %s\" % (self.tipo, self.identificador, self.titular)\n\n def get_detalles(self):\n response = []\n if self.identificador:\n response = DetalleFacturaAclinica.objects.filter(factura=self)\n return response\n\n\nclass DetalleFacturaAclinica(DetalleFactura):\n renglon = models.AutoField(primary_key=True)\n medicamento = models.ForeignKey('medicamentos.Medicamento')\n factura = models.ForeignKey('FacturaAclinica', null=True, on_delete=models.CASCADE)\n\nclass pieDeFacturaAclinica(PieDeFactura):\n FILTROS = [\"desde\", \"hasta\"]\n FILTERMAPPER = {\n 'desde': \"factura__fecha__gte\",\n 'hasta': \"factura__fecha__lte\",\n }\n factura = models.OneToOneField('FacturaAclinica',null=True)\n\n#==================================================================================================\n\nclass formaDePago(models.Model):\n formaPago=models.CharField(max_length=45)\n def __str__(self):\n return self.formaPago\n\nclass Pago(models.Model):\n factura = models.ForeignKey('FacturaDeProveedor',null=True)\n importe = models.DecimalField(max_digits=8, decimal_places=2, default=0)\n fecha = models.DateField()\n observaciones = models.CharField(max_length=120,null=True)\n formaDePago = models.ForeignKey('formaDePago',null=True)\n\n def __str__(self):\n return \"fecha: %s - importe: %s - obs.: %s - forma de pago: %s\" % (self.fecha, self.importe, self.observaciones, self.formaDePago)\n\n\n\n","sub_path":"facturacion/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"158249976","text":"'''\nCreated on 28 mars 2017\n\n@author: Alexandre\n'''\n\n#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# get quotes for multiple contracts\n# using a different tickerId for each one\n\nfrom ib.ext.Contract import Contract\nfrom ib.opt import ibConnection, message\nfrom time import sleep\n\n# print all messages from TWS\ndef watcher(msg): print(msg)\n\n# choose which price quotes to print\ndef printQuote(msg):\n qtype = \"nada\"\n if msg.field == 1: qtype = \"bid\"\n if msg.field == 2: qtype = \"ask\"\n if msg.field == 4: qtype = \"last\"\n if msg.field == 9: qtype = \"close\"\n\n if qtype != \"nada\":\n optstring = \"\"\n if float(contractDict[msg.tickerId][5]) > 0.001:\n optlist = []\n optlist.append(str(contractDict[msg.tickerId][4]))\n optlist.append(\" \")\n optlist.append(str(contractDict[msg.tickerId][5]))\n optlist.append(\" \")\n optlist.append(contractDict[msg.tickerId][6])\n optstring = ''.join([s for s in optlist])\n print( '%s: %s: %s: %s: %s' % (contractDict[msg.tickerId][1],\n contractDict[msg.tickerId][0], optstring, qtype, msg.price))\n\ndef makeContract(contractTuple):\n newContract = Contract()\n newContract.m_symbol = contractTuple[0]\n newContract.m_secType = contractTuple[1]\n newContract.m_exchange = contractTuple[2]\n newContract.m_currency = contractTuple[3]\n newContract.m_expiry = contractTuple[4]\n newContract.m_strike = contractTuple[5]\n newContract.m_right = contractTuple[6]\n if len(contractTuple) > 7:\n if contractTuple[1] == \"OPT\":\n newContract.m_multiplier = contractTuple[7]\n return newContract\n\nif __name__ == '__main__':\n\n contractDict = {}\n # a stock\n contractDict[0] = ('QQQ', 'STK', 'SMART', 'USD', '', 0.0, '')\n # another stock\n contractDict[1] = ('SPY', 'STK', 'SMART', 'USD', '', 0.0, '')\n # a stock option contract\n contractDict[2] = \\\n ('QQQ', 'OPT', 'SMART', 'USD', '20121221', 65.0, 'CALL', 100)\n # a futures contract\n contractDict[3] = ('ES', 'FUT', 'GLOBEX', 'USD', '201212', 0.0, '')\n # a futures option contract\n contractDict[4] = \\\n ('ES', 'FOP', 'GLOBEX', 'USD', '20121221', 1400.0, 'PUT')\n # a forex contract\n contractDict[5] = ('EUR', 'CASH', 'IDEALPRO', 'USD', '', 0.0, '')\n\n con = ibConnection()\n con.registerAll(watcher)\n showPrintQuotesOnly = True # set False to see lots of tick messages\n if showPrintQuotesOnly:\n con.unregister(watcher, (message.tickSize,),\n (message.tickPrice,),\n (message.tickString,),\n (message.tickOptionComputation,))\n con.register(printQuote, (message.tickPrice,))\n con.connect()\n sleep(.1)\n print('\\n* * * * REQUESTING 10 SECONDS OF MARKET DATA * * * *\\n')\n for tickId in range(len(contractDict)):\n stkContract = makeContract(contractDict[tickId])\n con.reqMktData(tickId, stkContract, '', False)\n sleep(10)\n print('\\n* * * * CANCELING MARKET DATA * * * *')\n for tickId in range(len(contractDict)):\n con.cancelMktData(tickId)\n sleep(.1)\n con.disconnect()\n sleep(.1)\n","sub_path":"GetMultipleMarketData.py","file_name":"GetMultipleMarketData.py","file_ext":"py","file_size_in_byte":3196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"196765362","text":"#!/usr/bin/env python\n\nimport os\nimport sys\n\nimport humanize\nimport psutil\n\nprocess = psutil.Process(os.getpid())\nfile1 = sys.argv[1]\nfile2 = sys.argv[2]\n\nprint(f\"Computing {file1} - {file2}\", file=sys.stderr)\n\nwith open(sys.argv[1]) as fin:\n set1 = set(line.strip() for line in fin.readlines())\n\nwith open(sys.argv[2]) as fin:\n set2 = set(line.strip() for line in fin.readlines())\n\nprint(f\"len(set1) = {len(set1)}, len(set2) = {len(set2)}\", file=sys.stderr)\n\n# or\n# import resource\n# resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\nprint(f\"Current RAM: {humanize.naturalsize(process.memory_info().rss)}\", file=sys.stderr)\n\nfor line in sorted(set1 - set2):\n print(line)\n","sub_path":"scripts/compare-lists.py","file_name":"compare-lists.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"169787703","text":"# 3진법에서 개념을 따온 형태\n\ndef solution(n):\n number = ('1', '2', '4')\n answer = ''\n\n while n>0:\n n -= 1\n answer = number[n % 3] + answer\n n //= 3\n \n return answer\n \n# 반성할 점\n# 1. 너무 숫자에 혈안이 돼 숫자를 문자로 생각하지 못 했던 점\n","sub_path":"2019_12_week1/kiryanchi_12899.py","file_name":"kiryanchi_12899.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"628780288","text":"#sqlclchemy在SQL语句的基础上又封装了一层\n\nfrom sqlalchemy import Column, String, create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\n\n#创建对象的基类\nBase = declarative_base()\n\n#定义User类对象\nclass User(Base):\n #表的名字:\n __tablename__ = 'user'\n\n #表的结构:\n id = Column(String(20), primary_key = True)\n name = Column(String(20))\n\n#初始化数据库链接 '数据库类型+数据库驱动名称://用户名:口令@机器地址:端口号/数据库名'\nengine = create_engine('mysql+mysqlconnector://root:123@localhost:3306/test')\n\n#创建DBSession类型:\nDBSession = sessionmaker(bind = engine)\n\n\n\n#添加记录函数\ndef addInfo(id1, name1):\n #创建session对象:\n session = DBSession()\n #创建新User对象\n new_user = User(id = id1, name = name1)\n #添加到session\n session.add(new_user)\n #提交保存到数据库\n session.commit()\n #关闭session\n session.close()\n\n#查询记录\ndef queryInfo(id1):\n #创建session对象:\n session = DBSession()\n # 创建Query查询,filter是where条件,最后调用one()返回唯一行,如果调用all()则返回所有行:\n user = session.query(User).filter(User.id == id1).one()\n # 打印类型和对象的name属性:\n print('type:', type(user))\n print('name:', user.name)\n # 关闭Session:\n session.close()\n\n# addInfo('5', 'Bob')\nqueryInfo('5')\n\n\n","sub_path":"TdbSession.py","file_name":"TdbSession.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"541098666","text":"from django.contrib.auth.decorators import login_required\nfrom datetime import datetime, timedelta\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.shortcuts import render, get_object_or_404, HttpResponseRedirect\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic import CreateView, UpdateView, DeleteView\nfrom .forms import ProjectForm, CourseForm, FileForm, MarkForm\nfrom .models import Project, File, Course, Mark\nfrom django.db.models import Q\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.urls import reverse_lazy, reverse\nfrom core.decorators import teacher_required, student_required\nfrom django.http import JsonResponse\nfrom bootstrap_modal_forms.generic import BSModalCreateView, BSModalUpdateView, BSModalReadView, BSModalDeleteView\nfrom profiles.models import Profile\nfrom django.contrib.auth import get_user_model\n\nUser = get_user_model()\n\n\n@login_required\n@teacher_required\ndef projects_list(request):\n # good to know - capital letters have priority over lowercase one in alphabetical sorting\n project_list = Project.objects.order_by('name')\n query = request.GET.get('q')\n if query:\n project_list = Project.objects.filter(\n Q(name__icontains=query)\n ).distinct()\n\n paginator = Paginator(project_list, 15) # 15 project per page\n page = request.GET.get('page')\n\n try:\n projects = paginator.page(page)\n except PageNotAnInteger:\n projects = paginator.page(1)\n except EmptyPage:\n projects = paginator.page(paginator.num_pages)\n\n context = {\n 'projects': projects\n }\n return render(request, \"projects/project_list.html\", context)\n\n\n@student_required\ndef projects_list_for_students(request):\n project_list = Project.objects.order_by('name')\n paginator = Paginator(project_list, 15) # 15 project per page\n page = request.GET.get('page')\n\n try:\n projects = paginator.page(page)\n except PageNotAnInteger:\n projects = paginator.page(1)\n except EmptyPage:\n projects = paginator.page(paginator.num_pages)\n\n user = Profile.objects.get(user=request.user)\n context = {\n 'projects': projects,\n 'user': user,\n }\n return render(request, \"projects/projects_list_for_students.html\", context)\n\n\nclass ProjectCreateView(BSModalCreateView):\n model = Project\n form_class = ProjectForm\n success_url = reverse_lazy('project_list')\n success_message = 'Success: Project was created.'\n\n def form_valid(self, form, **kwargs):\n form.instance.teacher = self.request.user\n return super().form_valid(form)\n\n\nclass ProjectUpdateView(BSModalUpdateView):\n model = Project\n template_name = 'projects/project_update_form.html'\n success_url = reverse_lazy('project')\n form_class = ProjectForm\n success_message = 'Success: Project was updated.'\n\n def get_success_url(self):\n pk = self.kwargs.get('pk')\n return reverse_lazy('project', kwargs={'pk': pk})\n\n def form_valid(self, form, **kwargs):\n form.instance.teacher = self.request.user\n return super().form_valid(form)\n\n\nclass ProjectDeleteView(BSModalDeleteView):\n model = Project\n template_name = 'projects/project_delete.html'\n success_message = 'Success: Project was deleted.'\n success_url = reverse_lazy('project_list')\n\n\ndef subscribe(request, pk):\n if request.POST.get('action') == 'post':\n project = Project.objects.get(pk=pk)\n obj = Profile.objects.get(user=request.user)\n print(obj.projects.all())\n if project in obj.projects.all():\n obj.projects.remove(project.id)\n print(obj.projects.all())\n else:\n obj.projects.add(project.id)\n print(obj.projects.all())\n obj.save()\n data = {'is_valid': True, 'project': str(project)}\n return JsonResponse(data)\n\n\nclass ProjectReadView(BSModalReadView):\n model = Project\n template_name = 'projects/project_shortcut.html'\n\n # TODO: call subscribe function (12.12.19)\n\n # def (self, project_id, **kwargs):\n # subscribe(self.request, project_id)\n\n\ndef projects(request, pk):\n # TODO: check js in template, change delete form to bootstrap modal\n projects_data = Project.objects.get(id=pk)\n courses = Course.objects.filter(project=pk)\n profile = Profile.objects.get(user=request.user)\n marks = Mark.objects.filter(student=profile.user, course__in=courses)\n subscribe(request, pk)\n\n max_points = sum([i.points for i in courses])\n user_points = sum([i.mark for i in marks])\n\n context = {\n 'project': projects_data,\n 'courses': courses,\n 'profile': profile,\n 'max_points': max_points,\n 'user_points': user_points,\n }\n return render(request, 'projects/project.html', context)\n\n\n@method_decorator([login_required, teacher_required], name='dispatch')\nclass CourseCreateView(CreateView):\n model = Course\n form_class = CourseForm\n template_name = 'projects/course_form.html'\n success_message = 'Success: Course was created.'\n\n def form_valid(self, form, **kwargs):\n form.instance.teacher = self.request.user\n form.instance.project = get_object_or_404(Project, pk=self.kwargs.get('pk'))\n return super().form_valid(form)\n\n def get_success_url(self):\n pk = self.object.project.pk\n return reverse('project', kwargs={'pk': pk})\n\n\nclass CourseUpdateView(UpdateView):\n model = Course\n form_class = CourseForm\n success_url = reverse_lazy('course')\n\n def get_success_url(self):\n pk = self.kwargs.get('pk')\n return reverse_lazy('course', kwargs={'pk': pk})\n\n def form_valid(self, form, **kwargs):\n form.instance.teacher = self.request.user\n return super().form_valid(form)\n\n\nclass CourseDeleteView(DeleteView):\n model = Course\n success_url = reverse_lazy('project')\n\n def get_success_url(self):\n pk = self.object.project.id\n return reverse('project', kwargs={'pk': pk})\n\n\ndef course_list(request, pk):\n if request.method == \"POST\":\n form = FileForm(request.POST, request.FILES)\n if form.is_valid():\n form.instance.course = pk\n form.instance.sender = request.user\n file = form.save()\n data = {'is_valid': True, 'name': file.file.name, 'url': file.file.url}\n else:\n data = {'is_valid': False}\n return JsonResponse(data)\n\n course_data = Course.objects.get(id=pk)\n teacher = Profile.objects.get(user=course_data.teacher)\n user = request.user\n user_points = None\n max_points = course_data.points\n try:\n user_points = Mark.objects.get(student=user, course=course_data).mark\n except Mark.DoesNotExist:\n user_points = user_points\n files = File.objects.filter(course=pk)\n senders = [i.sender for i in files]\n student = Profile.objects.filter(projects__course__id=course_data.id).order_by('last_name')\n students = [i.user for i in student]\n m_students = Mark.objects.filter(student__in=students, course=course_data)\n marked = [i.student for i in m_students]\n late_list = list(set(students) - set(senders) - set(marked))\n late = Profile.objects.filter(user__in=late_list)\n\n if course_data.end_date <= datetime.today().date():\n for i in late_list:\n mark = Mark(student=i, course=course_data, mark=0, date=datetime.today().date())\n mark.save()\n for j in senders:\n try:\n if Mark.objects.get(student=j, course=course_data) and course_data.end_date <= \\\n datetime.today().date() + timedelta(days=14):\n delete_file(request, File.objects.get(sender=j).id)\n except ObjectDoesNotExist:\n pass\n\n context = {\n 'files': files,\n 'course': course_data,\n 'teacher': teacher,\n 'user': user,\n 'user_points': user_points,\n 'max_points': max_points,\n 'pk': pk,\n 'late': late,\n 'marked': marked,\n 'senders': senders,\n }\n return render(request, 'projects/course.html', context)\n\n\ndef delete_file(request, pk):\n for file in File.objects.filter(id=pk):\n file.file.delete()\n file.delete()\n return HttpResponseRedirect(request.POST.get('next'))\n\n\nclass MarkCreateView(BSModalCreateView):\n form_class = MarkForm\n template_name = 'projects/mark.html'\n success_message = 'Success: mark set'\n\n def form_valid(self, form):\n form.instance.course = Course.objects.get(pk=self.kwargs.get('pk'))\n return super().form_valid(form)\n\n def get_context_data(self, **kwargs):\n course = Course.objects.get(pk=self.kwargs.get('pk'))\n mark = Mark.objects.filter(course=course)\n file = File.objects.filter(course=course.id)\n student = Profile.objects.filter(projects__course__id=course.id).order_by('last_name')\n students = list(\n set([i.sender for i in file]).intersection([i.user for i in student]) - set([i.student for i in mark]))\n context = super(MarkCreateView, self).get_context_data(**kwargs)\n context['max_mark'] = course.points\n context['course'] = course\n context['students'] = students\n return context\n\n def get_success_url(self, **kwargs):\n pk = self.object.course.id\n return reverse('course', kwargs={'pk': pk})\n","sub_path":"projects/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"180680598","text":"from controllers.modules import *\n\n__PERM__UPLOADS__ = \"uploads/permanent/\"\n__TEMP__UPLOADS__ = \"uploads/temp/\"\n\nclass UploadHandler(RequestHandler):\n\n\tdef set_default_headers(self):\n\t\tprint(\"setting headers!!!\")\n\t\tself.set_header(\"Access-Control-Allow-Origin\", \"*\")\n\t\tself.set_header(\"Access-Control-Allow-Headers\", \"Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Access-Control-Allow-Origin, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers\")\n\t\tself.set_header('Access-Control-Allow-Methods', ' POST,OPTIONS')\n\n\tdef upload(self, fileinfo):\n\t\t\n\t\tfname = fileinfo['filename']\n\t\textn = splitext(fname)[1]\n\t\tcname = str(uuid.uuid4()) + extn\n\t\tfh = open(__PERM__UPLOADS__ + cname, 'wb')\n\t\tfh.write(fileinfo['body'])\n\t\tfh.close()\n\n\t\treturn {\"status\" : 200, \"message\" : \"File Sucessfully Uploaded\", \"file_loc\" : __PERM__UPLOADS__ + cname}\n\n\t@coroutine\n\tdef post(self):\n\n\t\ttry:\n\t\t\tresponse = self.upload(fileinfo=self.request.files['image'][0])\n\t\t\t#self.write({\"status\" : 200, \"message\" : \"Sucessfully Submitted Details\"})\n\n\t\texcept Exception as e:\n\t\t\tself.write({\"status\" : 400, \"message\" : \"Cannot Upload Image\"})\n\n\n\n\tdef options(self):\n\t\tself.set_status(204)","sub_path":"controllers/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"377511756","text":"\r\nfrom random import randint\r\nfrom time import sleep\r\nfrom operator import itemgetter\r\n\r\njogadores = {\r\n 'jogador1' : randint(1, 6),\r\n 'jogador2' : randint(1, 6),\r\n 'jogador3' : randint(1, 6),\r\n 'jogador4' : randint(1, 6),\r\n}\r\n\r\nfor key, value in jogadores.items():\r\n print(f'O {key} acertou o número {value} no dado')\r\n sleep(1)\r\n\r\nranking = sorted(jogadores.items(), key=itemgetter(1), reverse=True)\r\n\r\nprint('='*30)\r\n\r\nfor count, value in enumerate(ranking):\r\n print(f'{count + 1}º lugar, {value[0]} que conseguiu o numero {value[1]} no dado')\r\n","sub_path":"Dicionarios .py","file_name":"Dicionarios .py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"494217425","text":"# Escribe un programa que pida una palabra por pantalla \n# y muestre por pantalla una lista con las vocales y el \n# número de veces que aparecen en la palabra.\nvocales=['a','e','i','o','u']\nvenp=[]\npalabra=input(\"Introduzca la palabra: \")\nfor letra in palabra:\n letra=letra.lower()\n if (letra in vocales) :\n temporal=[letra,palabra.count(letra)]\n if temporal not in venp:\n venp.append(temporal)\nprint(\"Vocales en palabra: \",list(venp))","sub_path":"movaiva/Python/Boletin_6/Ejercicio9.py","file_name":"Ejercicio9.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"77877717","text":"from django.db import models\nclass BaseModel(models.Model):\n @classmethod\n def create(cls, **kwargs):\n \"\"\"\n A quick way to use get_or_create on Class level.\n \"\"\"\n return cls.objects.get_or_create(**kwargs)\n\n def info(self, **kwargs):\n info = {}\n for key, value in kwargs.items():\n info[key] = value\n return info\n\n class Meta:\n abstract = True\n\nclass Timestamp(models.Model):\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n \n class Meta:\n abstract = True\n\nclass Person(BaseModel):\n first_name = models.CharField(max_length=30, null=True)\n last_name = models.CharField(max_length=30, null=True)\n address = models.CharField(max_length=100, null=True)\n phone_number = models.CharField(max_length=50, null=True)\n cellphone_number = models.CharField(max_length=50, blank=True, null=True)\n email = models.EmailField(unique=True, null=True)\n registered_date = models.DateField(blank=True, null=True)\n leave_date = models.DateField(blank=True, null=True)\n user = models.OneToOneField('site_auth.User', on_delete=models.CASCADE, null=True, blank=True)\n\n def __str__(self):\n return '{} {}'.format(self.first_name, self.last_name)\n\n @property\n def name(self):\n return '{} {}'.format(self.first_name, self.last_name)\n\n def save(self, **kwargs):\n from apps.auth.models import User\n role_field_maping = {\n 'student': 1,\n 'teacher': 2,\n 'executive': 3,\n 'admin': 4,\n }\n role = kwargs.get('role', None)\n if self.pk is None:\n if role != 4:\n user = User.objects.create_user(account=self.email, password=self.phone_number)\n user.role_field = role_field_maping[role]\n self.user = user\n else:\n user = User.objects.create_superuser(\n self.email, self.phone_number)\n self.user = user\n self.user.save()\n if role:\n del kwargs['role']\n super().save(**kwargs)\n\n def delete(self, **kwargs):\n self.user.delete()\n super().delete(**kwargs)\n\n class Meta:\n abstract = True\n","sub_path":"core/models/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"251724649","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n Author: kun.wang\n Create: 2015-06-24\n\nusing: PySide\n\"\"\"\nimport sys\n\nimport PySide.QtCore as QtCore\nimport PySide.QtGui as QtGui\n\nimport honey\nfrom obj_combo_box import HoneyObjectComboBox\n\n\nclass HoneyObjectAttrib(QtGui.QWidget):\n def __init__(self, parent=None):\n super(HoneyObjectAttrib, self).__init__(parent)\n self.title = u'Attrib Editor'\n\n def set_data(self, data):\n pass\n\n def get_data(self):\n return {}\n\n\nclass ProjectTypeAttrib(HoneyObjectAttrib):\n def __init__(self, parent=None):\n super(ProjectTypeAttrib, self).__init__(parent)\n self.title = u'项目类型'\n self.resize(400, 100)\n\n self.name = QtGui.QLineEdit()\n self.desc = QtGui.QLineEdit()\n\n self.main_layout = QtGui.QGridLayout()\n self.setLayout(self.main_layout)\n self.main_layout.setColumnStretch(1, 1)\n self.main_layout.setColumnStretch(2, 1)\n self.main_layout.addWidget(QtGui.QLabel(u'类型名: '), 0, 0, QtCore.Qt.AlignRight)\n self.main_layout.addWidget(self.name, 0, 1, 1, 2)\n self.main_layout.addWidget(QtGui.QLabel(u'描述: '), 1, 0, QtCore.Qt.AlignRight)\n self.main_layout.addWidget(self.desc, 1, 1, 1, 2)\n\n def set_data(self, data):\n self.name.setText(data.get('name', ''))\n self.desc.setText(data.get('desc', ''))\n\n def get_data(self):\n data = dict()\n data['name'] = unicode(self.name.text())\n data['desc'] = unicode(self.desc.text())\n return data\n\n\nclass ProjectStatusAttrib(HoneyObjectAttrib):\n def __init__(self, parent=None):\n super(ProjectStatusAttrib, self).__init__(parent)\n self.title = u'项目状态'\n self.resize(400, 100)\n\n self.name = QtGui.QLineEdit()\n self.color = QtGui.QLineEdit()\n self.desc = QtGui.QLineEdit()\n\n self.main_layout = QtGui.QGridLayout()\n self.setLayout(self.main_layout)\n self.main_layout.setColumnStretch(1, 1)\n self.main_layout.setColumnStretch(2, 1)\n self.main_layout.addWidget(QtGui.QLabel(u'状态名: '), 0, 0, QtCore.Qt.AlignRight)\n self.main_layout.addWidget(self.name, 0, 1, 1, 2)\n self.main_layout.addWidget(QtGui.QLabel(u'颜色: '), 1, 0, QtCore.Qt.AlignRight)\n self.main_layout.addWidget(self.color, 1, 1, 1, 2)\n self.main_layout.addWidget(QtGui.QLabel(u'描述: '), 2, 0, QtCore.Qt.AlignRight)\n self.main_layout.addWidget(self.desc, 2, 1, 1, 2)\n\n def set_data(self, data):\n self.name.setText(data.get('name', ''))\n self.color.setText(data.get('color', ''))\n self.desc.setText(data.get('desc', ''))\n\n def get_data(self):\n data = dict()\n data['name'] = unicode(self.name.text())\n data['color'] = unicode(self.color.text())\n data['desc'] = unicode(self.desc.text())\n return data\n\n\nclass ProjectAttrib(HoneyObjectAttrib):\n def __init__(self, parent=None):\n super(ProjectAttrib, self).__init__(parent)\n self.title = u'项目'\n self.resize(400, 100)\n\n self.project_name = QtGui.QLineEdit()\n self.project_type = HoneyObjectComboBox(honey.project.ProjectType)\n self.project_status = HoneyObjectComboBox(honey.project.ProjectStatus)\n self.desc = QtGui.QLineEdit()\n\n self.main_layout = QtGui.QGridLayout()\n self.setLayout(self.main_layout)\n self.main_layout.setColumnStretch(1, 1)\n self.main_layout.setColumnStretch(2, 1)\n self.main_layout.addWidget(QtGui.QLabel(u'项目名: '), 0, 0, QtCore.Qt.AlignRight)\n self.main_layout.addWidget(self.project_name, 0, 1, 1, 2)\n self.main_layout.addWidget(QtGui.QLabel(u'项目类型: '), 1, 0, QtCore.Qt.AlignRight)\n self.main_layout.addWidget(self.project_type, 1, 1, 1, 2)\n self.main_layout.addWidget(QtGui.QLabel(u'状态: '), 2, 0, QtCore.Qt.AlignRight)\n self.main_layout.addWidget(self.project_status, 2, 1, 1, 2)\n self.main_layout.addWidget(QtGui.QLabel(u'描述: '), 3, 0, QtCore.Qt.AlignRight)\n self.main_layout.addWidget(self.desc, 3, 1, 1, 2)\n\n def set_data(self, data):\n self.project_name.setText(data.get('name', ''))\n self.project_type.set_form_id(data.get('project_type_id', ''))\n self.project_status.set_form_id(data.get('project_status_id', ''))\n self.desc.setText(data.get('desc', ''))\n\n def get_data(self):\n data = dict()\n data['name'] = unicode(self.project_name.text())\n data['project_type_id'] = self.project_type.current_id()\n data['project_status_id'] = self.project_status.current_id()\n data['desc'] = unicode(self.desc.text())\n return data\n\n\nclass TaskTypeAttrib(HoneyObjectAttrib):\n def __init__(self, parent=None):\n super(TaskTypeAttrib, self).__init__(parent)\n self.title = u'任务类型'\n self.resize(400, 100)\n\n self.name = QtGui.QLineEdit()\n self.desc = QtGui.QLineEdit()\n\n self.main_layout = QtGui.QGridLayout()\n self.setLayout(self.main_layout)\n self.main_layout.setColumnStretch(1, 1)\n self.main_layout.setColumnStretch(2, 1)\n self.main_layout.addWidget(QtGui.QLabel(u'类型名: '), 0, 0, QtCore.Qt.AlignRight)\n self.main_layout.addWidget(self.name, 0, 1, 1, 2)\n self.main_layout.addWidget(QtGui.QLabel(u'描述: '), 1, 0, QtCore.Qt.AlignRight)\n self.main_layout.addWidget(self.desc, 1, 1, 1, 2)\n\n def set_data(self, data):\n self.name.setText(data.get('name', ''))\n self.desc.setText(data.get('desc', ''))\n\n def get_data(self):\n data = dict()\n data['name'] = unicode(self.name.text())\n data['desc'] = unicode(self.desc.text())\n return data\n\n\nclass TaskStatusAttrib(HoneyObjectAttrib):\n def __init__(self, parent=None):\n super(TaskStatusAttrib, self).__init__(parent)\n self.title = u'任务状态'\n self.resize(400, 100)\n\n self.name = QtGui.QLineEdit()\n self.desc = QtGui.QLineEdit()\n\n self.main_layout = QtGui.QGridLayout()\n self.setLayout(self.main_layout)\n self.main_layout.setColumnStretch(1, 1)\n self.main_layout.setColumnStretch(2, 1)\n self.main_layout.addWidget(QtGui.QLabel(u'状态名: '), 0, 0, QtCore.Qt.AlignRight)\n self.main_layout.addWidget(self.name, 0, 1, 1, 2)\n self.main_layout.addWidget(QtGui.QLabel(u'描述: '), 1, 0, QtCore.Qt.AlignRight)\n self.main_layout.addWidget(self.desc, 1, 1, 1, 2)\n\n def set_data(self, data):\n self.name.setText(data.get('name', ''))\n self.desc.setText(data.get('desc', ''))\n\n def get_data(self):\n data = dict()\n data['name'] = unicode(self.name.text())\n data['desc'] = unicode(self.desc.text())\n return data\n\n\nclass TaskPriorityAttrib(HoneyObjectAttrib):\n def __init__(self, parent=None):\n super(TaskPriorityAttrib, self).__init__(parent)\n self.title = u'任务优先级'\n self.resize(400, 100)\n\n self.name = QtGui.QLineEdit()\n self.level = QtGui.QSpinBox()\n\n self.main_layout = QtGui.QGridLayout()\n self.setLayout(self.main_layout)\n self.main_layout.setColumnStretch(1, 1)\n self.main_layout.setColumnStretch(2, 1)\n self.main_layout.addWidget(QtGui.QLabel(u'优先级: '), 0, 0, QtCore.Qt.AlignRight)\n self.main_layout.addWidget(self.name, 0, 1, 1, 2)\n self.main_layout.addWidget(QtGui.QLabel(u'描述: '), 1, 0, QtCore.Qt.AlignRight)\n self.main_layout.addWidget(self.level, 1, 1, 1, 2)\n\n def set_data(self, data):\n self.name.setText(data.get('name', ''))\n self.level.setValue(data.get('level', 0))\n\n def get_data(self):\n data = dict()\n data['name'] = unicode(self.name.text())\n data['level'] = self.level.value()\n return data\n\n\nclass TaskDifficultyAttrib(HoneyObjectAttrib):\n def __init__(self, parent=None):\n super(TaskDifficultyAttrib, self).__init__(parent)\n self.title = u'任务难易'\n self.resize(400, 100)\n\n self.name = QtGui.QLineEdit()\n self.star = QtGui.QSpinBox()\n\n self.main_layout = QtGui.QGridLayout()\n self.setLayout(self.main_layout)\n self.main_layout.setColumnStretch(1, 1)\n self.main_layout.setColumnStretch(2, 1)\n self.main_layout.addWidget(QtGui.QLabel(u'难易程度: '), 0, 0, QtCore.Qt.AlignRight)\n self.main_layout.addWidget(self.name, 0, 1, 1, 2)\n self.main_layout.addWidget(QtGui.QLabel(u'星级: '), 1, 0, QtCore.Qt.AlignRight)\n self.main_layout.addWidget(self.star, 1, 1, 1, 2)\n\n def set_data(self, data):\n self.name.setText(data.get('name', ''))\n self.star.setValue(data.get('star', 0))\n\n def get_data(self):\n data = dict()\n data['name'] = unicode(self.name.text())\n data['star'] = self.star.value()\n return data\n\n\nclass TaskAttrib(HoneyObjectAttrib):\n def __init__(self, parent=None):\n super(TaskAttrib, self).__init__(parent)\n self.title = u'任务'\n self.resize(400, 100)\n\n self.name = QtGui.QLineEdit()\n self.task_type = HoneyObjectComboBox(honey.task.TaskType)\n self.status = HoneyObjectComboBox(honey.task.TaskStatus)\n self.priority = HoneyObjectComboBox(honey.task.TaskPriority)\n self.difficulty = HoneyObjectComboBox(honey.task.TaskDifficulty)\n\n self.main_layout = QtGui.QGridLayout()\n self.setLayout(self.main_layout)\n self.main_layout.setColumnStretch(1, 1)\n self.main_layout.setColumnStretch(2, 1)\n self.main_layout.addWidget(QtGui.QLabel(u'任务名: '), 0, 0, QtCore.Qt.AlignRight)\n self.main_layout.addWidget(self.name, 0, 1, 1, 2)\n self.main_layout.addWidget(QtGui.QLabel(u'类型: '), 1, 0, QtCore.Qt.AlignRight)\n self.main_layout.addWidget(self.task_type, 1, 1, 1, 2)\n self.main_layout.addWidget(QtGui.QLabel(u'状态: '), 2, 0, QtCore.Qt.AlignRight)\n self.main_layout.addWidget(self.status, 2, 1, 1, 2)\n self.main_layout.addWidget(QtGui.QLabel(u'优先级: '), 3, 0, QtCore.Qt.AlignRight)\n self.main_layout.addWidget(self.priority, 3, 1, 1, 2)\n self.main_layout.addWidget(QtGui.QLabel(u'难易: '), 4, 0, QtCore.Qt.AlignRight)\n self.main_layout.addWidget(self.difficulty, 4, 1, 1, 2)\n\n def set_data(self, data):\n self.name.setText(data.get('name', ''))\n self.task_type.set_form_id(data.get('task_type_id', ''))\n self.status.set_form_id(data.get('task_status_id', ''))\n self.priority.set_form_id(data.get('task_priority_id', ''))\n self.difficulty.set_form_id(data.get('task_difficulty_id', ''))\n\n def get_data(self):\n data = dict()\n data['name'] = unicode(self.name.text())\n data['task_type_id'] = self.task_type.current_id()\n data['task_status_id'] = self.status.current_id()\n data['task_priority_id'] = self.priority.current_id()\n data['task_difficulty_id'] = self.difficulty.current_id()\n return data\n\n\nclass HoneyObjectDialog(QtGui.QDialog):\n def __init__(self, editor=None, parent=None):\n super(HoneyObjectDialog, self).__init__(parent)\n self.editor = editor\n if not self.editor:\n self.editor = HoneyObjectAttrib()\n\n self.setWindowTitle(self.editor.title)\n self.main_layout = QtGui.QVBoxLayout()\n self.setLayout(self.main_layout)\n\n self.main_layout.addWidget(self.editor)\n\n self.button_layout = QtGui.QHBoxLayout()\n self.main_layout.addLayout(self.button_layout)\n self.ok = QtGui.QPushButton(u\"确定\")\n self.cancel = QtGui.QPushButton(u\"取消\")\n\n self.ok.clicked.connect(self.accept)\n self.cancel.clicked.connect(self.reject)\n self.button_layout.addStretch()\n self.button_layout.addWidget(self.ok)\n self.button_layout.addWidget(self.cancel)\n\n def add_layout(self, layout):\n self.main_layout.insertLayout(0, layout)\n\n def add_widget(self, widget):\n self.main_layout.insertWidget(0, widget)\n\n def set_data(self, data):\n self.editor.set_data(data)\n\n def get_data(self):\n return self.editor.get_data()\n\n\ndef create_dialog(name, parent=None):\n class_name = name + \"Attrib\"\n dialog = None\n if hasattr(sys.modules[__name__], class_name):\n d_cls = getattr(sys.modules[__name__], class_name)\n dialog = HoneyObjectDialog(d_cls(), parent)\n return dialog\n\n\nif __name__ == '__main__':\n app = QtGui.QApplication(sys.argv)\n client = honey.client.HoneyClient()\n client.connect()\n\n view = create_dialog('Project')\n view.show()\n\n # def s():\n # print(view.get_data())\n #\n # button = QtGui.QPushButton('show')\n # button.clicked.connect(s)\n # button.show()\n\n # ds = create_dialog(\"Project\")\n # if ds:\n # ds.show()\n\n sys.exit(app.exec_())\n","sub_path":"OpenCGPipeline/HoneyMongo/honey_gui/base_ui/attrib_editor.py","file_name":"attrib_editor.py","file_ext":"py","file_size_in_byte":12989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"528698658","text":"from .base import *\n\nDEBUG = True\n\nSECRET_KEY = os.environ['SECRET_KEY']\n\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'sirius',\n 'USER': 'siriusadmin',\n 'PASSWORD': 'password',\n 'HOST': 'localhost',\n 'PORT': '',\n }\n}\n\nAWS_SES_REGION_NAME = os.environ['AWS_SES_REGION_NAME']\nAWS_SES_REGION_ENDPOINT = os.environ['AWS_SES_REGION_ENDPOINT']\nEMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\nEMAIL_USE_TLS = True\nDEFAULT_FROM_EMAIL = os.environ['DEFAULT_FROM_EMAIL']\nSERVER_EMAIL = os.environ['SERVER_EMAIL']\nEMAIL_HOST = 'smtp.gmail.com'\nEMAIL_PORT = 587\nEMAIL_HOST_USER = os.environ['SERVER_EMAIL']\nEMAIL_HOST_PASSWORD = os.environ['SIRIUS_EMAIL_PASS']\n\n\nMEDIA_ROOT = os.environ['MEDIA_ROOT']\n\nINTERNAL_IPS = '127.0.0.1'\n\nINSTALLED_APPS += ['debug_toolbar', 'django_extensions', 'storages', 's3file']\n\nMIDDLEWARE += [\n 'debug_toolbar.middleware.DebugToolbarMiddleware',\n 's3file.middleware.S3FileMiddleware',\n]\n\n\nTEMPLATES[0]['DIRS'] = ['templates', '/home/aaron/dev/sirius/templates/partials']\n\nDEBUG_TOOLBAR_CONFIG = {\n 'SHOW_TEMPLATE_CONTEXT': True,\n}\n\nFIXTURE_DIRS = ['fixtures']\n\nGRAPH_MODELS = {\n 'all_applications': True,\n 'group_models': True,\n}\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'handlers': {\n 'console': {\n 'class': 'logging.StreamHandler',\n },\n },\n 'loggers': {\n 'django.template': {\n 'handlers': ['console'],\n 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),\n },\n },\n}\n\nDEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'\nAWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']\nAWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']\nAWS_STORAGE_BUCKET_NAME = os.environ['AWS_STORAGE_BUCKET_NAME']\nAWS_LOCATION = 'media'\n","sub_path":"config/settings/local.py","file_name":"local.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"547981477","text":"from svggen.api.component import Component\n\n\nclass DoubleBeam(Component):\n\n _test_params = {\n 'shape': 3,\n 'tangle': 45,\n 'bangle': 45,\n 'phase': 2,\n }\n\n def define(self, **kwargs):\n self.addConstant(\"shape\", 3, **kwargs)\n self.addConstant(\"phase\", 0, **kwargs)\n a = self.addParameter(\"angle\", 0)\n\n self.addSubcomponent(\"leg1\", \"Beam\", shape=self.getParameter(\"shape\"), phase=self.getParameter(\"phase\"))\n self.addSubcomponent(\"leg2\", \"Beam\", shape=self.getParameter(\"shape\"), phase=self.getParameter(\"phase\"))\n\n self.addConnection((\"leg1\", \"topedge\"),\n (\"leg2\", \"botedge\"), angle=a)\n\n self.inheritInterface(\"input\", (\"leg2\", \"topedge\"))\n self.inheritInterface(\"output\", (\"leg1\", \"botedge\"))\n\n\nif __name__ == \"__main__\":\n from svggen.utils.utils import printSummary\n\n f = DoubleBeam(shape=4)\n f.toYaml(\"DoubleBeam.yaml\")\n printSummary(f)\n\n '''\n f.setParameter(\"leg1.q_a\", 1)\n for x in \"roll yaw\".split():\n f.setParameter(\"leg2.\" + x, 0)\n for x in \"dx dy dz roll pitch yaw\".split():\n f.setParameter(\"leg1.\" + x, 0)\n '''\n #for x in \"dx dy dz q_i q_j q_k\".split():\n #f.setParameter(\"leg1.\" + x, 0)\n #f.setParameter(\"leg2.q_a\", 0)\n\n #f.setParameter(\"leg1.length\", 100)\n #f.setParameter(\"leg1.beamwidth\", 10)\n #f.setParameter(\"leg2.length\", 50)\n\n '''\n print \"~~~ Parameters:\"\n for p, (n, v) in sorted(f.allParameters.iteritems(), key = lambda x: x[1][0]):\n print p, f.getVariableSub(p), [(x, p.assumptions0[x]) for x in p.assumptions0 if x not in \"real complex hermitian imaginary commutative\".split()]\n for v in sorted(f.getVariables(), key = lambda x: repr(x)):\n print v, [(x, v.assumptions0[x]) for x in v.assumptions0 if x not in \"real complex hermitian imaginary commutative\".split()]\n print\n '''\n\n '''\n print \"~~~ Equations:\"\n from svggen.utils.utils import schemeRepr, schemeList\n for i,c in enumerate(f.getRelations()):\n #print i, \":\", repr(schemeList(c))\n print schemeRepr(schemeList(c))\n print c\n #print c.subs(f.getSubs())\n print\n print\n '''\n\n '''\n print \"~~~ Solutions:\"\n solns = sympy.solve(f.getRelations())\n for s in solns:\n print s\n '''\n '''\n arr = [5, 2,0]\n print arr\n r = [f.getRelations()[x] for x in arr]\n print \n for c in r:\n print c\n print\n print sympy.solve(r)\n '''\n\n\n '''\n f.make()\n\n print f.getInterface(\"output\").getEdges()\n print f.getInterface(\"output\").getValue()\n f.getInterface(\"input\").setInputValue(-10)\n print f.getInterface(\"output\").getValue()\n\n f._make_test(protobuf=True)\n\n print f.getInterface(\"output\").getValue()\n f.getInterface(\"input\").setInputValue(-10)\n print f.getInterface(\"output\").getValue()\n print f.composables[\"function\"].ports\n print f.getInterface.func_code.co_varnames\n '''\n\n","sub_path":"svggen/library/legacy/DoubleBeam.py","file_name":"DoubleBeam.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"632592707","text":"import xlrd, xlwt, xlutils\n\n# data = xlrd.open_workbook(\"2.微保_防癌_站内_1续_赔付率.xlsx\")\n# print(data.sheet_loaded(0)) # 工作表是否被加载\n# print(data.sheet_loaded(1)) # 工作表是否被加载\n# print(data.sheet_loaded(2)) # 工作表是否被加载\n# data.unload_sheet(0) # 根据索引或者名称卸载工作表\n# print(data.sheet_loaded(0))\n# print(data.sheet_loaded(1)) # 工作表是否被加载\n\n# 工作表的获取\n# print(data.sheets()) # 获取全部的sheet,数组\n# print(data.sheets()[0])\n# data.sheet_by_index(0) # 获取索引为0的工作表\n# data.sheet_by_name(\"总结\") # 根据名称获取工作表\n# print(data.sheet_names()) # 获取工作表的所有名称\n# print(data.nsheets) # 返回工作表的的数量\n\n# 操作excel行\n# sheet = data.sheet_by_index(0)\n# print(sheet.nrows) # 获取当前sheet下的有效行数\n# print(sheet.row(0)) # 获取第一行的内容,组成的列表\n# print(sheet.row_types(0)) # 获取指定行的数据类型 0(空)\\1(字符串)\\2(num)\\3(date)\\4(bool)\\5(error)\n# print(sheet.row(0)[2]) # 获取第一行第三列的值\n# print(sheet.row(0)[2].value) # 获取第一行第三列的值\n# print(sheet.row_values(0)) # 得到指定行单元格的值的列表\n# print(sheet.row_len(0)) # 获取单元格的长度\n\n# 操作excel列\n# sheet = data.sheet_by_index(0)\n# print(sheet.ncols) # 当前工作表的有效列\n# print(sheet.col(2)) # 获取单元格列的数据信息\n# print(sheet.col(2)[1].value) # 获取单元格指定列指定行的数据信息\n# print(sheet.col_values(0)) # 得到指定列单元格的值的列表\n# print(sheet.col_types(1)) # 合并的单元格会被默认成空\n\n# 操作excel单元格\n# sheet = data.sheet_by_index(0)\n# print(sheet.cell(1, 2)) # 坐标获取单元格对象\n# print(sheet.cell_type(1, 2)) # 单元格数据类型\n# print(sheet.cell(1, 2).ctype) # 单元格数据类型\n# print(sheet.cell(1, 2).value) # 单元格的数据\n# print(sheet.cell_value(1, 2)) # 单元格的数据\n#\n\n# 创建工作簿\nwb = xlwt.Workbook()\n# 创建工作表\nws = wb.add_sheet('CNY')\n# 填充数据\nws.write_merge(0, 1, 0, 5, '2019年货币兑换表')\ndata = (('01/01/2019', 4.54646, 1, 0.8888, 0.0672, 6.8885), ('01/01/2019', 4.54646, 1, 0.8888, 0.0672, 6.8885),\n ('01/01/2019', 4.54646, 1, 0.8888, 0.0672, 6.8885))\n\nfor i, item in enumerate(data): # 获取索引的方法\n for j, val in enumerate(item):\n ws.write(i + 2, j, val)\n#\n# # 新建sheet也添加图片\n# # wsImage = wb.add_sheet('image')\n# # wsImage.insert_bitmap('微信截图_20210608235716.bmp', 0, 0)\n# # 保存数据\n# wb.save('2019-CNY.xls')\n","sub_path":"dealExcel/xlrd-xlwt/study.py","file_name":"study.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"294303423","text":"import requests\r\n#Jonathan Sanchez - CODE2040 Fellow 2017 Applicant\r\n#Stage 2 - Reverse a string\r\n\r\n#API Token in the form of JSON\r\napi_token = '37d4156cbcfc15b43886dbff56d75e9d'\r\n\r\n#CODE2040 Endpoint\r\nendpoint = 'http://challenge.code2040.org/api/reverse'\r\n\r\n#CODE2040 Validate Endpoint\r\nv_endpoint = 'http://challenge.code2040.org/api/reverse/validate'\r\n\r\n#Create a JSON Dictionary with my Token\r\njson_token = {'token': api_token}\r\n\r\n#I will now run the 'send' function to send my Token to the Endpoint\r\nstring = requests.post(endpoint, json_token)\r\n\r\n#Reverse the string\r\nnew_string = str(string.text[::-1])\r\n\r\n#Create a returning JSON Dictionary\r\nreturning_token = {'token': api_token, 'string': new_string}\r\n\r\n#I will now POST my JSON to the VALIDATE server\r\nprint(requests.post(v_endpoint, returning_token))\r\n","sub_path":"stage2.py","file_name":"stage2.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"279703291","text":"#!/usr/bin/env python\n# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-\n# ex: set expandtab softtabstop=4 shiftwidth=4:\n#\n# Copyright (C) 2012,2013,2014 Contributor\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\"\"\"Module for testing the add service command.\"\"\"\n\nif __name__ == \"__main__\":\n import utils\n utils.import_depends()\n\nimport unittest2 as unittest\nfrom brokertest import TestBrokerCommand\n\n\nclass TestAddShare(TestBrokerCommand):\n def testaddnasshares(self):\n # Creates shares test_share_1 through test_share_9\n for i in range(1, 9):\n self.noouttest([\"add_share\", \"--cluster=utecl1\",\n \"--share=test_share_%s\" % i])\n\n self.noouttest([\"add_share\", \"--cluster=utecl2\",\n \"--share=test_share_1\"])\n self.noouttest([\"add_share\", \"--cluster=utecl3\",\n \"--share=test_share_1\"])\n self.noouttest([\"add_share\", \"--cluster=utecl13\",\n \"--share=test_share_1\"])\n\n def testaddnotinnasobjects(self):\n self.noouttest([\"add_share\", \"--cluster\", \"utecl1\",\n \"--share\", \"not_in_nasobjects\"])\n\n # test_share_1 must appear once.\n def testverifyshowutmc1(self):\n command = [\"show_metacluster\", \"--metacluster=utmc1\"]\n out = self.commandtest(command)\n self.searchoutput(out,\n r\"Share: not_in_nasobjects\\s*\"\n r\"Share: test_share_1\\s*\"\n r\"Share: test_share_2\\s*\"\n r\"Share: test_share_3\\s*\"\n r\"Share: test_share_4\\s*\"\n r\"Share: test_share_5\\s*\"\n r\"Share: test_share_6\\s*\"\n r\"Share: test_share_7\\s*\"\n r\"Share: test_share_8\", command)\n\n def testadd10gigshares(self):\n for i in range(5, 11):\n self.noouttest([\"add_share\", \"--cluster=utecl%d\" % i,\n \"--share=utecl%d_share\" % i])\n\n def testaddhashares(self):\n for i in range(11, 13):\n self.noouttest([\"add_share\", \"--cluster=utecl%d\" % i,\n \"--share=utecl%d_share\" % i])\n self.noouttest([\"add_share\", \"--cluster=npecl%d\" % i,\n \"--share=npecl%d_share\" % i])\n\n def testverifyshowshare(self):\n command = [\"show_share\", \"--cluster=utecl1\", \"--share=test_share_1\"]\n out = self.commandtest(command)\n self.matchoutput(out, \"Share: test_share_1\", command)\n self.matchoutput(out, \"Bound to: ESX Cluster utecl1\", command)\n\n self.matchoutput(out, \"Server: lnn30f1\", command)\n self.matchoutput(out, \"Mountpoint: /vol/lnn30f1v1/test_share_1\",\n command)\n self.matchoutput(out, \"Disk Count: 0\", command)\n self.matchoutput(out, \"Machine Count: 0\", command)\n self.matchclean(out, \"Latency\", command)\n self.matchclean(out, \"Comments\", command)\n self.matchclean(out, \"Share: test_share_2\", command)\n\n def testupdatesharefail_1(self):\n command = [\"update_share\", \"--share=doesnotexist\", \"--latency_threshold=10\",\n \"--comments=updated comment\"]\n out = self.badrequesttest(command)\n self.matchoutput(out, \"Share doesnotexist is not used on any resource\"\n \" and cannot be modified\", command)\n\n def testupdatesharefail_2(self):\n command = [\"update_share\", \"--share=test_share_1\", \"--latency_threshold=10\",\n \"--comments=updated comment\"]\n out = self.badrequesttest(command)\n self.matchoutput(out, 'The value of latency_threshold must be either zero, or at least 20.', command)\n\n def testupdateshare_1(self):\n command = [\"update_share\", \"--share=test_share_1\", \"--latency_threshold=0\",\n \"--comments=updated comment\"]\n out = self.commandtest(command)\n\n command = [\"show_share\", \"--share=test_share_1\"]\n out = self.commandtest(command)\n self.matchclean(out, \"Latency\", command)\n\n for cluster in (\"utecl1\", \"utecl2\", \"utecl3\", \"utecl13\"):\n command = [\"show_share\", \"--share=test_share_1\", \"--cluster=%s\" % cluster]\n out = self.commandtest(command)\n self.matchclean(out, \"Latency\", command)\n\n command = [\"cat\", \"--share=test_share_1\", \"--cluster=%s\" % cluster,\n \"--generate\"]\n out = self.commandtest(command)\n self.matchoutput(out, '\"name\" = \"test_share_1\";', command)\n self.matchclean(out, 'latency_threshold', command)\n\n\n def testupdateshare_2(self):\n command = [\"update_share\", \"--share=test_share_1\", \"--latency_threshold=20\",\n \"--comments=updated comment\"]\n out = self.commandtest(command)\n command = [\"show_share\", \"--share=test_share_1\"]\n out = self.commandtest(command)\n self.matchoutput(out, \"Latency threshold: 20\", command)\n\n def testupdateshare_3(self):\n self.noouttest([\"update_share\", \"--share=test_share_1\", \"--latency_threshold=30\",\n \"--comments=updated comment\"])\n\n for cluster in (\"utecl1\", \"utecl2\", \"utecl3\", \"utecl13\"):\n command = [\"show_share\", \"--share=test_share_1\", \"--cluster=%s\" % cluster]\n out = self.commandtest(command)\n self.matchoutput(out, \"Share: test_share_1\", command)\n self.matchoutput(out, \"Bound to: ESX Cluster %s\" % cluster, command)\n self.matchoutput(out, \"Comments: updated comment\", command)\n self.matchoutput(out, \"Latency threshold: 30\", command)\n\n command = [\"cat\", \"--share=test_share_1\", \"--cluster=%s\" % cluster,\n \"--generate\"]\n out = self.commandtest(command)\n self.matchoutput(out, '\"name\" = \"test_share_1\";', command)\n self.matchoutput(out, '\"latency_threshold\" = 30;', command)\n\n def testverifynotinnasobjects(self):\n command = [\"show_share\", \"--cluster\", \"utecl1\",\n \"--share\", \"not_in_nasobjects\"]\n out = self.commandtest(command)\n self.matchoutput(out, \"Share: not_in_nasobjects\", command)\n self.matchoutput(out, \"Server: None\", command)\n self.matchoutput(out, \"Mountpoint: None\", command)\n\n def testverifyshowshareproto(self):\n command = [\"show_share\", \"--cluster=utecl1\", \"--share=test_share_1\",\n \"--format\", \"proto\"]\n out = self.commandtest(command)\n reslist = self.parse_resourcelist_msg(out, expect=1)\n resource = reslist.resources[0]\n self.failUnlessEqual(resource.name, \"test_share_1\")\n self.failUnlessEqual(resource.type, \"share\")\n self.failUnlessEqual(resource.share.server, \"lnn30f1\")\n self.failUnlessEqual(resource.share.mount,\n \"/vol/lnn30f1v1/test_share_1\")\n self.failUnlessEqual(resource.share.disk_count, 0)\n self.failUnlessEqual(resource.share.machine_count, 0)\n\n def testverifyshownotinnasobjectsproto(self):\n command = [\"show_share\", \"--cluster\", \"utecl1\",\n \"--share\", \"not_in_nasobjects\", \"--format\", \"proto\"]\n out = self.commandtest(command)\n reslist = self.parse_resourcelist_msg(out, expect=1)\n resource = reslist.resources[0]\n self.failUnlessEqual(resource.name, \"not_in_nasobjects\")\n self.failUnlessEqual(resource.type, \"share\")\n self.failIf(hasattr(resource, 'server'))\n self.failIf(hasattr(resource, 'mount'))\n self.failUnlessEqual(resource.share.disk_count, 0)\n self.failUnlessEqual(resource.share.machine_count, 0)\n\n def testverifyshowshareall(self):\n command = [\"show_share\", \"--all\"]\n out = self.commandtest(command)\n self.matchoutput(out, \"Share: test_share_1\", command)\n self.matchoutput(out, \"Share: test_share_2\", command)\n self.matchoutput(out, \"Server: lnn30f1\", command)\n self.matchoutput(out, \"Mountpoint: /vol/lnn30f1v1/test_share_1\",\n command)\n self.matchoutput(out, \"Disk Count: 0\", command)\n self.matchoutput(out, \"Machine Count: 0\", command)\n\n # only backward compatibility - to be removed later.\n def testverifyshowshare(self):\n command = [\"show_nas_disk_share\", \"--share=test_share_1\"]\n out = self.commandtest(command)\n self.matchoutput(out, \"NAS Disk Share: test_share_1\", command)\n self.matchoutput(out, \"Server: lnn30f1\", command)\n self.matchoutput(out, \"Mountpoint: /vol/lnn30f1v1/test_share_1\",\n command)\n self.matchoutput(out, \"Disk Count: 0\", command)\n self.matchoutput(out, \"Machine Count: 0\", command)\n self.matchclean(out, \"Comments\", command)\n self.matchclean(out, \"NAS Disk Share: test_share_2\", command)\n\n # only backward compatibility - to be removed later.\n def testverifyshowshareall(self):\n command = [\"show_nas_disk_share\", \"--all\"]\n out = self.commandtest(command)\n self.matchoutput(out, \"NAS Disk Share: test_share_1\", command)\n self.matchoutput(out, \"NAS Disk Share: test_share_2\", command)\n self.matchoutput(out, \"Server: lnn30f1\", command)\n self.matchoutput(out, \"Mountpoint: /vol/lnn30f1v1/test_share_1\",\n command)\n self.matchoutput(out, \"Disk Count: 0\", command)\n self.matchoutput(out, \"Machine Count: 0\", command)\n\n def testcatshare(self):\n command = [\"cat\", \"--cluster=utecl1\", \"--share=test_share_1\"]\n out = self.commandtest(command)\n self.matchoutput(out, \"structure template resource/cluster/utecl1/\"\n \"share/test_share_1/config;\",\n command)\n self.matchoutput(out, '\"name\" = \"test_share_1\";', command)\n self.matchoutput(out, '\"server\" = \"lnn30f1\";', command)\n self.matchoutput(out, '\"mountpoint\" = \"/vol/lnn30f1v1/test_share_1\";',\n command)\n\n\nif __name__ == '__main__':\n suite = unittest.TestLoader().loadTestsFromTestCase(TestAddShare)\n unittest.TextTestRunner(verbosity=2).run(suite)\n","sub_path":"tests/broker/test_add_share.py","file_name":"test_add_share.py","file_ext":"py","file_size_in_byte":10761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"298123298","text":"import argparse\nimport json\nimport requests\nfrom bs4 import BeautifulSoup\n\n\ndef fetch_lyrics(author, song):\n author = author.replace(\" \", \"-\")\n song = song.replace(\" \", \"-\")\n url = f'https://genius.com/{author}-{song}-lyrics'\n result = requests.get(url).text\n\n soup = BeautifulSoup(result, \"html.parser\")\n content = soup.find('p').text\n\n return content\n\n\ndef add_song_text(author, song):\n\n \"\"\"If a song exists in json file, adds text in key['Lyrics']\"\"\"\n\n text = fetch_lyrics(author, song)\n with open(\"Database.json\", \"r\") as file:\n content = json.load(file)\n for key in content['data']['Songs']:\n if key['artist'] == author and key['name'] == song:\n key['Lyrics'] = text\n\n with open(\"Database.json\", \"w\") as file1:\n json.dump(content, file1, indent=2)\n\n\ndef to_file(author, song):\n\n \"\"\"Checks if the song is already in JSON file, copies song text\n and saves it to a .txt file. If the text does not exist yet,\n parses it, adds to data base and to file\"\"\"\n\n with open(\"Database.json\", \"r\") as file:\n content = json.load(file)\n for key in content['data']['Songs']:\n if key['artist'] == author and key['name'] == song:\n if key['lyrics'] != 'text':\n text_to_download = key['Lyrics']\n else:\n text_to_download = fetch_lyrics(author, song)\n\n with open(f\"{author}_{song}.txt\", \"w\") as file:\n file.write(f'{author}\\n{text_to_download}')\n\n\nif __name__ == \"__main__\":\n to_file('Nirvana', 'In Bloom')\n to_file('Adele', 'Hello')\n add_song_text('Adele', 'Hello')\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument('-a',\n '--artist',\n type=str,\n default=None)\n parser.add_argument('-s',\n '--song',\n type=str,\n default=None)\n parser.add_argument('-f',\n '--to_file',\n type=str,\n default=None)\n parser.add_argument('-d', '--to_db',\n type=str,\n default=None)\n\n args = parser.parse_args()","sub_path":"lyrics/lyrics.py","file_name":"lyrics.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"607370846","text":"\"\"\"The Voice over IP integration.\"\"\"\nfrom __future__ import annotations\n\nimport asyncio\nfrom collections.abc import Callable\nimport logging\n\nfrom voip_utils import SIP_PORT\n\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.const import CONF_IP_ADDRESS\nfrom homeassistant.core import HomeAssistant\n\nfrom .const import DOMAIN\nfrom .voip import HassVoipDatagramProtocol\n\n_LOGGER = logging.getLogger(__name__)\n_IP_WILDCARD = \"0.0.0.0\"\n\n__all__ = [\n \"DOMAIN\",\n \"async_setup_entry\",\n \"async_unload_entry\",\n]\n\n\nasync def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:\n \"\"\"Set up VoIP integration from a config entry.\"\"\"\n ip_address = entry.data[CONF_IP_ADDRESS]\n _LOGGER.debug(\n \"Listening for VoIP calls from %s (port=%s)\",\n ip_address,\n SIP_PORT,\n )\n hass.data[DOMAIN] = await _create_sip_server(\n hass,\n lambda: HassVoipDatagramProtocol(hass, {str(ip_address)}),\n )\n\n return True\n\n\nasync def _create_sip_server(\n hass: HomeAssistant,\n protocol_factory: Callable[\n [],\n asyncio.DatagramProtocol,\n ],\n) -> asyncio.DatagramTransport:\n transport, _protocol = await hass.loop.create_datagram_endpoint(\n protocol_factory,\n local_addr=(_IP_WILDCARD, SIP_PORT),\n )\n\n return transport\n\n\nasync def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:\n \"\"\"Unload VoIP.\"\"\"\n transport = hass.data.pop(DOMAIN, None)\n if transport is not None:\n transport.close()\n _LOGGER.debug(\"Shut down VoIP server\")\n\n return True\n","sub_path":"homeassistant/components/voip/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"622767766","text":"import datetime\n\nimport boto3\nimport configparser\n\nconfig = configparser.ConfigParser(interpolation=None)\nconfig.read('./vars.ini')\n\nprint('Starting EBS snapshots')\n\n\ndef lambda_handler(event, context):\n regions_str = config.get('regions', 'regionList')\n regions_list = regions_str.split(',')\n ec2_instance_tag_value = config.get('main', 'EC2_INSTANCE_TAG_VALUE')\n ec2_instance_tag_name = config.get('main', 'EC2_INSTANCE_TAG_NAME')\n volume_tag_names_to_retain = config.get('main', 'VOLUME_TAG_NAMES_TO_RETAIN').split(',')\n retention_days = config.getint('main', 'RETENTION_DAYS')\n\n def snapshot_region(aws_region):\n print(\"Snapshotting EBS volumes in %s\" % aws_region)\n account = event['account']\n ec = boto3.client('ec2', region_name=aws_region)\n instances = find_all_eligible_instances(ec)\n print(\"Found \" + str(len(instances)) + \" eligible instances to snapshot.\");\n\n for instance in instances:\n snapshot_instance(ec, instance)\n\n print(\"Backups complete, preparing to delete snapshots.\")\n purge_old_snapshots(account, ec)\n print(\"Purge of previous backups complete.\")\n\n def find_all_eligible_instances(ec):\n reservations = ec.describe_instances(\n Filters=[\n {'Name': 'tag:%s' % ec2_instance_tag_name, 'Values': [ec2_instance_tag_value]},\n ]\n )['Reservations']\n return sum(\n [\n [i for i in reservation['Instances']]\n for reservation in reservations\n ], [])\n\n def snapshot_instance(ec, instance):\n for dev in instance['BlockDeviceMappings']:\n if dev.get('Ebs', None) is None:\n # skip non EBS volumes\n continue\n snapshot_ebs_volume(ec, instance, dev)\n\n def snapshot_ebs_volume(ec, instance, dev):\n instance_id = instance['InstanceId']\n instance_name = find_name_tag(instance)\n tag_kind = find_kind_tag(instance)\n tag_environment = find_environment_tag(instance)\n\n vol_id = dev['Ebs']['VolumeId']\n vol_tags_response = ec.describe_tags(\n Filters=[{'Name': 'resource-id', 'Values': [vol_id]}],\n )\n vol_name = find_name_tag(vol_tags_response)\n\n print(\"Found EBS volume %s (%s) on instance %s (%s), creating snapshot\" % (\n vol_name, vol_id, instance_name, instance_id))\n\n snap = ec.create_snapshot(\n Description=\"%s from instance %s (%s)\" % (vol_name or vol_id, instance_name, instance_id),\n VolumeId=vol_id,\n )\n\n today_string = str(datetime.date.today())\n\n snapshot_name = \"%s_%s\" % (vol_name or vol_id, today_string)\n snapshot_tags = [\n {'Key': 'Name', 'Value': snapshot_name},\n {'Key': 'InstanceId', 'Value': instance_id},\n {'Key': 'InstanceName', 'Value': instance_name},\n {'Key': 'Kind', 'Value': tag_kind},\n {'Key': 'environment', 'Value': tag_environment},\n {'Key': 'VolumeName', 'Value': vol_name},\n {'Key': 'DeviceName', 'Value': dev['DeviceName']},\n {'Key': 'BackupDate', 'Value': today_string},\n {'Key': 'LambdaManagedSnapshot', 'Value': 'true'},\n ]\n\n transfer_eligible_tags_from_volume(snapshot_tags, vol_tags_response)\n\n ec.create_tags(\n Resources=[snap['SnapshotId']],\n Tags=snapshot_tags,\n )\n\n def find_name_tag(object_with_tags):\n name = ''\n for tag in object_with_tags['Tags']:\n if tag[\"Key\"] == 'Name':\n name = tag[\"Value\"]\n return name\n\n def find_kind_tag(object_with_tags):\n kind = ''\n for tag in object_with_tags['Tags']:\n if tag[\"Key\"] == 'Kind':\n kind = tag[\"Value\"]\n return kind\n\n\n def find_environment_tag(object_with_tags):\n environment = ''\n for tag in object_with_tags['Tags']:\n if tag[\"Key\"] == 'environment':\n environment = tag[\"Value\"]\n return environment\n\n def transfer_eligible_tags_from_volume(snapshot_tags, vol_tags_response):\n for vol_tag_name in volume_tag_names_to_retain:\n for tag in vol_tags_response['Tags']:\n if tag['Key'] == vol_tag_name:\n snapshot_tags.append({'Key': tag['Key'], 'Value': tag['Value']})\n\n def purge_old_snapshots(account, ec):\n all_managed_snapshots = ec.describe_snapshots(\n OwnerIds=['%s' % account],\n Filters=[\n {'Name': 'tag:LambdaManagedSnapshot', 'Values': ['true']},\n ],\n )\n\n print(\"Found %d snapshots to delete.\" % (len(all_managed_snapshots['Snapshots'])))\n ascending_start_dates_to_delete = find_start_dates_to_delete(all_managed_snapshots)\n\n if len(ascending_start_dates_to_delete) > 0:\n last_start_date_to_delete = ascending_start_dates_to_delete[-1]\n\n delete_snapshots_older_than(ec, last_start_date_to_delete, all_managed_snapshots)\n\n def find_start_dates_to_delete(all_managed_snapshots):\n print(\"Determining from which dates to delete.\");\n start_dates_set = set()\n for snap in all_managed_snapshots['Snapshots']:\n start_dates_set.add(snap['StartTime'].date())\n\n ascending_start_dates_to_delete = sorted(start_dates_set)[:-retention_days]\n\n print(\"Found distinct days: %d, retention is set at %d days, deleting snapshots made on or before day: %s\" % (\n len(start_dates_set), retention_days, str(ascending_start_dates_to_delete)))\n\n return ascending_start_dates_to_delete\n\n def delete_snapshots_older_than(ec, last_start_date_to_delete, all_managed_snapshots):\n deleted_snapshots_count = 0\n\n for snap in all_managed_snapshots['Snapshots']:\n if snap['StartTime'].date() <= last_start_date_to_delete:\n print(\"Deleting old snapshot %s (started on: %s)\" % (snap['SnapshotId'], str(snap['StartTime'])))\n ec.delete_snapshot(SnapshotId=snap['SnapshotId'])\n deleted_snapshots_count += 1\n\n print(\"Deleted %d snapshots older than %s\" % (deleted_snapshots_count, str(last_start_date_to_delete)))\n\n for r in regions_list:\n snapshot_region(r)\n","sub_path":"ebs_bckup/ebs_bckup.py","file_name":"ebs_bckup.py","file_ext":"py","file_size_in_byte":6336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"105206295","text":"import os\nimport urllib.request\nimport tarfile\nimport zipfile\n\n\ndef report_hook(block_num, block_size, total_size):\n if total_size <= 0:\n return\n\n part_size = block_size * block_num\n if part_size > total_size:\n part_size = total_size\n progress = (part_size / total_size) * 100.0\n print(\"\\r{:.0f}%({}/{})\".format(progress, part_size, total_size), end=\"\")\n\n\ndata_dir = \"data\"\nif not os.path.exists(data_dir):\n os.mkdir(data_dir)\n\n# Word2Vecの日本語学習済みモデル\nurl = \"http://www.cl.ecei.tohoku.ac.jp/~m-suzuki/jawiki_vector/data/20170201.tar.bz2\"\nsave_path = \"./data/20170201.tar.bz2\"\nextract_path = \"./data/entity_vector\"\nif not os.path.exists(save_path):\n print(\"Download: {0}\".format(url))\n urllib.request.urlretrieve(url, save_path, report_hook)\n print()\nif not os.path.exists(extract_path):\n print(\"Extract: {0}\".format(save_path))\n tar = tarfile.open(save_path, \"r|bz2\")\n tar.extractall(\"./data\")\n tar.close()\n\n# fastTextの英語学習済みモデル\nurl = \"https://dl.fbaipublicfiles.com/fasttext/vectors-english/wiki-news-300d-1M.vec.zip\"\nsave_path = \"./data/wiki-news-300d-1M.vec.zip\"\nextract_path = \"./data/wiki-news-300d-1M\"\nif not os.path.exists(save_path):\n print(\"Download: {0}\".format(url))\n urllib.request.urlretrieve(url, save_path, report_hook)\n print()\nif not os.path.exists(extract_path):\n print(\"Extract: {0}\".format(save_path))\n zip = zipfile.ZipFile(save_path)\n zip.extractall(extract_path)\n zip.close()\n\n# IMDbデータセット\nurl = \"http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz\"\nsave_path = \"./data/aclImdb_v1.tar.gz\"\nextract_path = \"./data/aclImdb\"\nif not os.path.exists(save_path):\n print(\"Download: {0}\".format(url))\n urllib.request.urlretrieve(url, save_path, report_hook)\n print()\nif not os.path.exists(extract_path):\n print(\"Extract: {0}\".format(save_path))\n tar = tarfile.open(save_path)\n tar.extractall(\"./data\")\n tar.close()\n\n# fastTextの日本語学習済みモデル\n# https://drive.google.com/open?id=0ByFQ96A4DgSPUm9wVWRLdm5qbmc\nsave_path = \"./data/vector_neologd.zip\"\nextract_path = \"./data/vector_neologd\"\nif not os.path.exists(extract_path):\n print(\"Extract: {0}\".format(save_path))\n zip = zipfile.ZipFile(save_path)\n zip.extractall(extract_path)\n zip.close()\n","sub_path":"machine_learning/nlp/data_download.py","file_name":"data_download.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"274670792","text":"#-*- coding:utf -8 -*-\nimport win32gui,win32con\nimport time\n \ndef click(identificador): #para simular el click del mouse \n win32gui.SendMessage(identificador, win32con.WM_LBUTTONDOWN, 0, 0) #señal de presionar el botón \n win32gui.SendMessage(identificador, win32con.WM_LBUTTONUP, 0, 0) #señal de soltar el botón \n \nnombre = \"Enigma Group - App Challenge 2\" #acá va el título de la ventana\nventana = win32gui.FindWindow(None,nombre) #asigno a la variable ventana un valor entero que sería el identificador\nif ventana != 0: #si el valor es distinto de 0 es que la encontró \n print(\"Encontrada\")\n win32gui.SetForegroundWindow(ventana) #traigo la ventana al frente para ver que hace,aunque no es necesario \n boton1 = win32gui.FindWindowEx(ventana,None,None,\"Submit\") #el identificador del botón submit \n boton2 = win32gui.FindWindowEx(ventana,None,None,\"Cancel\") #el identificador del botón cancel \n texto= win32gui.FindWindowEx(ventana,None,\"ThunderRT6TextBox\",\"\") # lo bueno de conocer otros lenguajes y sus clases ThunderRT6TextBox\n texto1= win32gui.FindWindowEx(ventana,None,None,\"\") #no tiene nada como titulo y se obtiene igual el identificador \n clave=\"topgun\"\n time.sleep(2) #espero para poner la clave, porque quiero nada más\n win32gui.SendMessage(texto1,win32con.EM_SETPASSWORDCHAR,None,3) #cambio el \"*\" por su caracter\n win32gui.SendMessage(texto, win32con.WM_SETTEXT, 8, clave) #envío la clave al textbox, también podría usar texto1\n time.sleep(2) #otra espera porque si\n click(boton1) #aunque no este activado ejecuta las sentencias igual\n time.sleep(5) #ya sabemos\n click(boton2) #cerramos la aplicación \nelse:\n print(\"No encontrada\")\n ","sub_path":"Enigmagroup/Reversing/Solucion Retos/solucion_app2.tincopasan.py","file_name":"solucion_app2.tincopasan.py","file_ext":"py","file_size_in_byte":2133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"25893921","text":"from .window_system import *\nfrom .utils import *\nfrom clay.shared.py_utils import *\nimport traceback\n\ndef state_for_exception(exp, msg):\n exp_str = traceback.format_exc()\n return (exp_str, msg)\n\ndef show_exception_viewer(exp_state):\n exp_str, msg = exp_state\n\n _, keep_open = begin('Exception:', True)\n text(msg)\n separator()\n should_continue = button('continue')\n separator()\n text(exp_str)\n end()\n\n return (not keep_open) or should_continue\n\n","sub_path":"clay/core/gui/exception_viewer.py","file_name":"exception_viewer.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"19879188","text":"# ## Make predictions\n\n\n\n#Import statements\nimport json\nimport requests\nimport pandas as pd\nimport numpy as np\nimport datetime\nfrom datetime import date\nfrom pandas.io.json import json_normalize\nfrom pathlib import Path\nimport pytz\nfrom datetime import timedelta\nimport os\nimport os.path\nfrom os import path\nimport csv\nimport time\nimport re\nimport string\nfrom dateutil import tz\nimport demoji\nfrom collections import Counter\nimport ast\ndemoji.download_codes()\n\n\n# In[143]:\n\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import balanced_accuracy_score, accuracy_score, precision_score, recall_score, roc_auc_score \nfrom sklearn.metrics import confusion_matrix,roc_curve, auc\n\n\n# In[144]:\n\n\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import KFold\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import MinMaxScaler\nfrom tensorflow.python.keras.models import Sequential\nfrom tensorflow.python.keras.layers import Dense\nfrom tensorflow.python.keras.wrappers.scikit_learn import KerasRegressor\n\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping\nfrom tensorflow.python.keras.layers import Dropout\n\nstockSymbol = [\"AAPL\", \"AMZN\", \"GOOGL\", \"MSFT\", \"DELL\", \"IBM\", \"INTC\", \"HPQ\", \"FB\",\n\t \"CSCO\", \"ORCL\", \"HPE\", \"MU\", \"DXC\", \"TMO\"]\n\n\n# In[145]:\n\n\n#from_zone = tz.gettz('UTC')\n#to_zone = tz.gettz('America/New_York')\n\n# This is the current list the NYSE will be shut down to observe holidays\nholidayList = [datetime.date(2020, 4, 10), datetime.date(2020, 5, 25), datetime.date(2020, 7, 3), datetime.date(2020, 9, 7), datetime.date(2020, 11, 26), datetime.date(2020, 12, 25),\n datetime.date(2021, 1, 1), datetime.date(2021, 1, 18), datetime.date(2021, 2, 15), datetime.date(2021, 4, 2), datetime.date(2021, 5, 31), datetime.date(2021, 7, 5),\n datetime.date(2021, 9, 6), datetime.date(2021, 11, 25), datetime.date(2021, 12, 24), datetime.date(2022, 1, 17), datetime.date(2022, 2, 21), datetime.date(2022, 4, 15),\n datetime.date(2022, 5, 30), datetime.date(2022, 7, 4), datetime.date(2022, 9, 5), datetime.date(2022, 11, 24), datetime.date(2022, 12, 26)]\n\n\n\n# In[152]:\n\n\ndef tokenize(s): \n return re_tok.sub(r' \\1 ', s).split()\n\n\n# In[153]:\n\n\ndef start_predictions():\n #re_tok = re.compile(f'([{string.punctuation}“”¨«»®´·º½¾¿¡§£₤‘’])')\n\n\n fullDf = pd.DataFrame(columns=['id', 'cleanSents', 'tag', 'created'])\n currentFolder = os.getcwd()\n\n #Will need to switch file path to / instead of \\\\ for deployment \n for symbol in stockSymbol:\n df = pd.read_csv(currentFolder+\"/{}folder/{}_twits.csv\".format(symbol, symbol))[{'id', 'cleanSents', 'tag', 'created'}]\n fullDf = fullDf.append(df)\n fullDf = fullDf.drop_duplicates('id')\n fullDf = fullDf.reset_index()[{'id','cleanSents','tag', 'created'}]\n\n bullish = fullDf[fullDf['tag'] == 'Bullish'].reset_index()[{'id','cleanSents','tag', 'created'}]\n bearish = fullDf[fullDf['tag'] == 'Bearish'].reset_index()[{'id','cleanSents','tag', 'created'}]\n none = fullDf[fullDf['tag'] == 'none'].reset_index()[{'id','cleanSents','tag', 'created'}]\n taggedDf = bullish.append(bearish)\n\n X_train, X_test, y_train, y_test = train_test_split(taggedDf['cleanSents'].values, taggedDf['tag'].values, test_size=0.2)\n vect = TfidfVectorizer()\n\n tf_train = vect.fit_transform(X_train)\n tf_test = vect.transform(X_test)\n\n NLPmodel = LogisticRegression(random_state=0, solver='liblinear', multi_class='ovr', class_weight='balanced').fit(tf_train, y_train)\n\n predictions = NLPmodel.predict(tf_test)\n\n # Report the predctive performance metrics\n # evaluate predictions\n accuracy = accuracy_score(y_test, predictions)\n balanced_accuracy = balanced_accuracy_score(y_test, predictions)\n\n if not (path.exists(currentFolder+\"nlpDailyPerformance.csv\")):\n NLPdailyPerformance = pd.DataFrame(columns = [\"Accuracy\", \"Balanced_Accuracy\", \"Date\"])\n NLPdailyPerformance = NLPdailyPerformance.append({\"Accuracy\" : accuracy,\n \"Balanced_Accuracy\" : balanced_accuracy,\n \"Date\" : datetime.datetime.today().date()}, ignore_index=True)\n else:\n NLPdailyPerformance = pd.read_csv(\"nlpDailyPerformance.csv\")\n NLPdailyPerformance = NLPdailyPerformance.append({\"Accuracy\" : accuracy,\n \"Balanced_Accuracy\" : balanced_accuracy,\n \"Date\" : datetime.datetime.today().date()}, ignore_index=True)\n NLPdailyPerformance.to_csv(\"nlpDailyPerformance.csv\", index=False)\n make_datasets(NLPmodel, vect)\n\n\n# In[154]:\n\n\ndef count_predict(df, NLPmodel, vect):\n if len(df) == 0:\n return 0\n tf_new = vect.transform(df['cleanSents'])\n # get probabilities for positive class\n probs = NLPmodel.predict_proba(tf_new)[:,1]\n preds = NLPmodel.predict(tf_new)\n return len(preds[preds=='Bullish'])\n\n\n# In[155]:\n\n\ndef make_prediction(company, companyDf, newDataDf, lastClose):\n currentFolder = os.getcwd()\n #Setup Neural Network\n #Variables\n x=companyDf[{'prePct_traded_vol', 'prePct_close_val', 'percent_bullish', 'pct_twits_volume'}]\n y=companyDf['percentChange']\n y=np.reshape(y.values, (-1,1))\n scaler_x = MinMaxScaler()\n scaler_y = MinMaxScaler()\n scaler_x.fit(x)\n scaler_y.fit(y)\n xscale=scaler_x.transform(x)\n yscale=scaler_y.transform(y)\n \n #Split data\n X_train, X_test, y_train, y_test = train_test_split(xscale, yscale, test_size=.30)\n \n #Build Neural Network\n NNmodel = Sequential()\n NNmodel.add(Dense(50, input_dim=X_train.shape[1], kernel_initializer='normal', activation='relu'))\n NNmodel.add(Dropout(0.5))\n NNmodel.add(Dense(100, activation='relu'))\n NNmodel.add(Dropout(0.2))\n NNmodel.add(Dense(10, activation='relu'))\n NNmodel.add(Dropout(0.5))\n NNmodel.add(Dense(1, activation='relu'))\n NNmodel.compile(loss='mse', optimizer='adam', metrics=['mse','mae'])\n \n #Recall the best validation loss and reduced learning rate and stop training\n reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=20, \n min_delta=1e-4, mode='min')\n\n stop_alg = EarlyStopping(monitor='val_loss', patience=100, restore_best_weights=True)\n\n history = NNmodel.fit(X_train, y_train, batch_size=50, verbose=0, validation_split=0.2, epochs=1000, \n callbacks=[stop_alg, reduce_lr])\n \n #Used to see the loss of both validation and training over the course of training\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'validation'], loc='upper left')\n plt.savefig(currentFolder+\"/{}folder/{}nnLoss.png\".format(company, company))\n \n plt.close()\n \n #Absolute error historgram\n pred = scaler_y.inverse_transform(NNmodel.predict(X_test))\n actual = scaler_y.inverse_transform(y_test)\n #AvgError = plt.hist(np.abs(actual-pred), bins=11)\n #AvgError.savefig(currentFolder+\"/{}folder/{}nnAE.png\".format(company, company))\n \n meanAbsError = np.mean(np.abs(actual-pred))\n meanError = np.mean(actual-pred)\n stdError = np.std(actual-pred)\n \n if (path.exists(currentFolder+\"/{}folder/{}nnDailyPerformance.csv\".format(company, company))):\n NNdailyPerformance = pd.read_csv(currentFolder+\"/{}folder/{}nnDailyPerformance.csv\".format(company, company))\n NNdailyPerformance = NNdailyPerformance.append({\"MeanAbsError\" : meanAbsError,\n \"MeanError\" : meanError,\n \"StdError\" : stdError,\n \"Date\" : datetime.datetime.today().date()}, ignore_index=True)\n \n else:\n NNdailyPerformance = pd.DataFrame(columns = [\"MeanAbsError\", \"MeanError\", \"StdError\", \"Date\"])\n NNdailyPerformance = NNdailyPerformance.append({\"MeanAbsError\" : meanAbsError,\n \"MeanError\" : meanError,\n \"StdError\" : stdError,\n \"Date\" : datetime.datetime.today().date()}, ignore_index=True)\n \n NNdailyPerformance.to_csv(currentFolder+\"/{}folder/{}nnDailyPerformance.csv\".format(company, company), index=False)\n \n #Compute the newest prediction\n \n newData = scaler_y.transform(newDataDf)\n newPrediction = scaler_y.inverse_transform(NNmodel.predict(newData))[0]\n \n \n \n diff = lastClose*newPrediction\n newClosePred = lastClose+diff\n \n #df = pd.DataFrame([newPrediction], columns=['prediction'], \n # index=['{}'.format(company)])\n #df['positive'] = df['prediction']>0\n \n df = pd.DataFrame([{'lastClose' : lastClose, 'prediction': round(newClosePred[0], 2)}], \n index=['{} Last Close'.format(company), '{} Prediciton'.format(company)])\n df['positive'] = ((df['prediction']-df['lastClose'])>0)\n \n columns = ('Last Close', 'Prediciton')\n y_pos = np.arange(len(columns))\n values = [lastClose, round(newClosePred[0], 2)]\n \n x=np.arange(len(columns))\n width = .8\n \n fig, ax = plt.subplots()\n rects1 = ax.bar(x, values, width, color =df.positive.map({True: 'g', False:'r'}))\n\n # Add some text for labels, title and custom x-axis tick labels, etc.\n ax.set_ylabel('Stock Value')\n ax.set_title('{} Stock Prediction for {}'.format(company, date.today()))\n ax.set_xticks(x)\n ax.set_xticklabels(columns)\n\n \"\"\"Attach a text label above each bar in *rects*, displaying its height.\"\"\"\n for rect in rects1:\n height = rect.get_height()\n ax.annotate('{}'.format(round(height, 2)),\n xy=(rect.get_x() + rect.get_width() / 2, height),\n xytext=(0, -25), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='bottom',\n fontsize = 20) \n \n #plt.bar(y_pos, values, align='center', alpha=0.5, color=df.positive.map({True: 'g', False:'r'}))\n #plt.xticks(y_pos, columns)\n \n #plt.text(, lastClose*.5, str(lastClose))\n #plt.text(1, newClosePred*.5, str(newClosePred))\n\n #ax = df.plot(kind='bar', color=df.positive.map({True:'g', False:'r'}), alpha=.65) \n #x_offset = -0.5\n #y_offset = 0.02\n #for p in ax.patches:\n # ax.annotate(str(p.get_height()), (p.get_x()*0.6, p.get_height() * .5), fontsize=20)\n\n plt.savefig(currentFolder+\"/{}folder/{}nnPrediction.png\".format(company, company))\n plt.close()\n \n #print(newPrediction)\n \n\n\n# In[178]:\n\n\n#This function makes the correct dataframes inorder to make a prediction\ndef make_datasets(nlpmodel, vect):\n \n currentFolder = os.getcwd()\n\n est = pytz.timezone('US/Eastern')\n\n for symbol in stockSymbol:\n\n #Format twits data to prefered times and types.\n dfTwits = pd.read_csv(currentFolder+\"/{}folder/{}_twits.csv\".format(symbol, symbol))\n dfTwits['created'] = pd.to_datetime(dfTwits['created'])\n\n estList = []\n for index, row in dfTwits.iterrows():\n estList.append(est.localize(dfTwits['created'][index].to_pydatetime()))\n dfTwits['estTime'] = estList\n\n #Format daily stock market values to preferred \n dfDaily = pd.read_csv(currentFolder+\"/{}folder/{}Daily.csv\".format(symbol, symbol))\n dfDaily['time'] = pd.to_datetime(dfDaily['time'])\n\n lowest = '2019-12-20'\n twits_vol = []\n pct_bullish = []\n preModeldf = dfDaily[dfDaily['time']>=lowest]\n preModeldf = preModeldf.sort_values(by='time')\n preModeldf = preModeldf.set_index('time')\n \n lastClose = preModeldf['close'][-1]\n\n preModeldf['prePct_traded_vol'] = preModeldf['percentVol'].shift(1)\n preModeldf['prePct_close_val'] = preModeldf['percentChange'].shift(1)\n preModeldf = preModeldf[{'prePct_traded_vol', 'prePct_close_val', 'percentChange'}]\n\n\n for row in preModeldf.index[:]:\n upper = row.to_pydatetime().replace(tzinfo= est) + timedelta(hours = 8, minutes = 30)\n lower = row.to_pydatetime().replace(tzinfo = est) + timedelta(days = -1, hours = 8, minutes = 30)\n windowTwits = dfTwits[(dfTwits['estTime']>=lower) & (dfTwits['estTime']<=upper)]\n volume = len(windowTwits)\n twits_vol.append(volume)\n\n if(volume<1):\n pct_bullish.append(.5)\n volume = 1\n else:\n bullish_count = len(windowTwits[windowTwits['tag']=='Bullish']) + count_predict(windowTwits[windowTwits['tag']=='none'],\n nlpmodel,\n vect)\n pct_bullish.append(bullish_count/volume)\n preModeldf['percent_bullish'] = pct_bullish\n preModeldf['twits_volume'] = twits_vol\n modeldf = preModeldf\n modeldf['pct_twits_volume'] = modeldf['twits_volume'].pct_change(1)\n modeldf = modeldf[{'percentChange', 'prePct_traded_vol', 'prePct_close_val', 'percent_bullish', 'pct_twits_volume'}]\n modeldf=modeldf.replace([np.inf, -np.inf], 0.0).dropna()\n\n \n #gather newest row for predictions makes a separate dataframe\n predictRow = pd.DataFrame( columns = ['prePct_traded_vol', 'prePct_close_val', 'percent_bullish', 'pct_twits_volume'])\n dt = date.today()\n newUpper= datetime.datetime.combine(dt, datetime.datetime.min.time()).replace(tzinfo=est) + timedelta(hours=8, minutes=30)\n newLower=datetime.datetime.combine(dt, datetime.datetime.min.time()).replace(tzinfo=est) + timedelta(days=-1, hours=8, minutes=30)\n newWindowTwits = dfTwits[(dfTwits['estTime']>=newLower) & (dfTwits['estTime']<=newUpper)]\n newVolume = len(newWindowTwits)\n newBullish = .5\n if (newVolume <1):\n newBullish = .5\n newVolume = 1\n else:\n new_bullish_count = len(newWindowTwits[newWindowTwits['tag']=='Bullish']) + count_predict(newWindowTwits[newWindowTwits['tag']=='none'],\n nlpmodel,\n vect)\n newBullish = new_bullish_count/newVolume\n previousPctTradeVol = dfDaily[0:1][\"percentVol\"][0]\n previousPctTradeChange = dfDaily[0:1][\"percentChange\"][0]\n percentTwitsVolume = (newVolume - volume)/volume\n\n predictRow = predictRow.append(\n {'prePct_traded_vol':previousPctTradeVol,\n 'prePct_close_val':previousPctTradeChange,\n 'percent_bullish':newBullish,\n 'pct_twits_volume':percentTwitsVolume}, ignore_index=True)\n \n #Make predicitons for the current day\n make_prediction(symbol, modeldf, predictRow, lastClose)\n\n\n# ## Visualizations\n\n# In[186]:\n\n\ndef MakeDonutChart(data,symbol,timeSeries, script, images):\n print(timeSeries)\n getCount = Counter(k['symbol'] for k in data if dict(k).get('symbol'))\n symbolCount = dict(getCount)\n symbolCount[symbol] = 0\n symbolCount = {k: v for k, v in sorted(symbolCount.items(), key=lambda item: item[1])}\n fig, ax = plt.subplots(figsize=(11, 10), subplot_kw=dict(aspect=\"equal\"))\n\n cnt = 0\n data = []\n symbols = []\n recipe = []\n\n for sign, count in getCount.most_common():\n if cnt >= 1:\n data.append(count)\n symbols.append(sign)\n recipe.append(sign +' - '+str(count)+' twits')\n cnt += 1\n if cnt >= 6:\n break\n\n\n# for key in symbolCount.keys():\n# data.append(symbolCount[key])\n# symbols.append(key)\n# recipe.append(key + ' - ' + str(symbolCount[key]) + ' twits')\n# cnt += 1\n# if cnt >= 5:\n# break\n\n if sum(data) < 15:\n print('Not enough data for given time frame')\n fig.suptitle('Not enough data for given time frame', fontsize=20)\n os.chdir(images)\n plt.savefig(symbol+'TopFiveOtherCompanies'+timeSeries+'.png', optimize=True)\n #print('saved '+symbol+'TopFiveOtherCompanies'+timeSeries+'.png to '+os.getcwd())\n plt.close()\n os.chdir(script)\n #print('returning to '+os.getcwd())\n return\n\n def explode():\n try:\n exp = (0.1,0,0,0,0)\n except:\n exp=None\n return(exp)\n\n wedges, texts = ax.pie(data, \n explode=explode(), \n shadow=True, wedgeprops=dict(width=0.5), startangle=-40)\n\n bbox_props = dict(boxstyle=\"square,pad=0.3\", fc=\"w\", ec=\"k\", lw=0.72)\n kw = dict(arrowprops=dict(arrowstyle=\"-\"),\n bbox=bbox_props, zorder=0, va=\"center\")\n\n for i, p in enumerate(wedges):\n ang = (p.theta2 - p.theta1)/2. + p.theta1\n y = np.sin(np.deg2rad(ang))\n x = np.cos(np.deg2rad(ang))\n horizontalalignment = {-1: \"right\", 1: \"left\"}[int(np.sign(x))]\n connectionstyle = \"angle,angleA=0,angleB={}\".format(ang)\n kw[\"arrowprops\"].update({\"connectionstyle\": connectionstyle})\n ax.annotate(recipe[i], xy=(x, y), xytext=(1.35*np.sign(x), 1.4*y),\n horizontalalignment=horizontalalignment, **kw)\n\n ax.legend(wedges, symbols,\n fontsize='large',\n title_fontsize='large',\n title=\"Symbols\",\n loc=\"center\",\n frameon=False)\n #bbox_to_anchor=(1, 0, 0.5, 1))\n #ax.set_title(\"Top Ten Companies Mentioned in \" + symbol + \" Twits\", fontsize=30, pad=50)\n\n os.chdir(images)\n plt.savefig(symbol+'TopFiveOtherCompanies'+timeSeries+'.png', optimize=True)\n #print('saved '+symbol+'TopFiveOtherCompanies'+timeSeries+'.png to '+os.getcwd())\n plt.close()\n os.chdir(script)\n #print('returning to '+os.getcwd())\n\n\n# In[187]:\n\n\ndef GetOtherCompanies(fname, days, script, images):\n to_ignore = fname[:-10]\n # set wd to Symbolfolder\n symbolFolder = os.path.join(script, to_ignore+'folder')\n os.chdir(symbolFolder)\n #print('Pulling data from ' +os.getcwd())\n print(days)\n df = pd.read_csv(fname)\n df['Date'] = pd.to_datetime(df['created']) # save time string as datetime\n stock_ds = []\n if days == 'lastWeek':\n lastweekdate = pd.to_datetime('today').floor('D') - timedelta(7)\n df = df[df.Date >= lastweekdate]\n for row in df.newSymbols:\n lists = ast.literal_eval(row)\n for diction in lists:\n stock_ds.append(diction)\n MakeDonutChart(stock_ds, to_ignore, 'LastWeek', script, images)\n elif days == 'lastMonth':\n lastmonthdate = pd.to_datetime('today').floor('D') - timedelta(30)\n df = df[df.Date >= lastmonthdate]\n for row in df.newSymbols:\n lists = ast.literal_eval(row)\n for diction in lists:\n stock_ds.append(diction)\n print(len(stock_ds))\n MakeDonutChart(stock_ds, to_ignore, 'LastMonth', script, images)\n elif days == 'lastYear':\n lastyeardate = pd.to_datetime('today').floor('D') - timedelta(365)\n df = df[df.Date >= lastyeardate]\n for row in df.newSymbols:\n lists = ast.literal_eval(row)\n for diction in lists:\n stock_ds.append(diction)\n print(len(stock_ds))\n MakeDonutChart(stock_ds, to_ignore, 'LastYear', script, images)\n else:\n for row in df.newSymbols:\n lists = ast.literal_eval(row)\n for diction in lists:\n stock_ds.append(diction)\n MakeDonutChart(stock_ds, to_ignore, 'AllTime', script, images)\n\n\n# In[188]:\n\n\ndef MakeBarChart(tags,symbol,timeSeries, script, images):\n data = []\n tag = []\n for key in tags.keys():\n data.append(tags[key])\n tag.append(key)\n \n df = pd.DataFrame({'Tags':tag, 'val':data})\n ax = df.plot.barh('Tags', 'val', color=['y', 'r', 'g'], fontsize=15, figsize=(11,10), legend=False)\n ax.set_ylabel('Tags', fontsize=20)\n for i, v in enumerate(data):\n ax.text(v, i, str(v), fontsize=15, fontweight='bold')\n \n os.chdir(images)\n plt.savefig(symbol+'Tags'+timeSeries+'.png', optimize=True)\n #print('saved '+symbol+'Tags'+timeSeries+'.png to '+os.getcwd())\n plt.close()\n os.chdir(script)\n #print('returning to '+os.getcwd())\n\n\n# In[189]:\n\n\ndef GetTags(fname, days, script, images):\n \n symbol = fname[:-10]\n # set wd to Symbolfolder\n symbolFolder = os.path.join(script, symbol+'folder')\n os.chdir(symbolFolder)\n #print('Pulling data from ' +os.getcwd())\n df = pd.read_csv(fname)\n df['Date'] = pd.to_datetime(df['created']) # save time string as datetime\n tags = {\n 'Bullish': 0,\n 'Bearish': 0,\n 'none': 0\n }\n\n if days == 'lastWeek':\n lastweekdate = pd.to_datetime('today').floor('D') - timedelta(7)\n df = df[df.Date >= lastweekdate]\n for row in df.tag:\n tags[row] += 1\n MakeBarChart(tags,symbol,'LastWeek', script, images)\n elif days == 'lastMonth':\n lastmonthdate = pd.to_datetime('today').floor('D') - timedelta(30)\n df = df[df.Date >= lastmonthdate]\n for row in df.tag:\n tags[row] += 1\n MakeBarChart(tags,symbol,'LastMonth', script, images)\n elif days == 'lastYear':\n lastyeardate = pd.to_datetime('today').floor('D') - timedelta(365)\n df = df[df.Date >= lastyeardate]\n for row in df.tag:\n tags[row] += 1\n MakeBarChart(tags,symbol,'LastYear', script, images)\n else:\n for row in df.tag:\n tags[row] += 1\n MakeBarChart(tags,symbol,'AllTime', script, images)\n\n\n# In[190]:\n\n\ndef GetVolume(fname, days, script, images):\n \n if 'Values' in fname:\n symbol = fname[:-10]\n else:\n symbol = fname[:-9]\n symbolFolder = os.path.join(script, symbol+'folder')\n os.chdir(symbolFolder)\n #print('Pulling data from ' +os.getcwd())\n df = pd.read_csv(fname)\n df['Date'] = pd.to_datetime(df['time'])\n df[\"SMA1\"] = df['close'].rolling(window=25).mean()\n df[\"SMA2\"] = df['close'].rolling(window=100).mean()\n \n if days == 'lastWeek':\n lastweekdate = pd.to_datetime('today').floor('D') - timedelta(7)\n df = df[df.Date >= lastweekdate]\n ax = df.plot('Date', 'volume', figsize=(15,10), fontsize=15)\n ax.set_xlabel('')\n ax.set_ylabel('Volume', fontsize=20)\n plt.ticklabel_format(style='plain', axis='y')\n plt.grid(True)\n os.chdir(images)\n plt.savefig(symbol+'VolumeLastWeek.png', optimize=True)\n #print('saved '+symbol+'VolumeLastWeek.png to '+os.getcwd())\n plt.close()\n os.chdir(symbolFolder)\n #print('returning to '+os.getcwd())\n ax = df.plot('Date', 'close', figsize=(11,10), fontsize=15)\n ax.set_xlabel('')\n ax.set_ylabel('Price', fontsize=20)\n plt.legend()\n plt.ticklabel_format(style='plain', axis='y')\n plt.grid(True)\n os.chdir(images)\n plt.savefig(symbol+'PriceLastWeek.png', optimize=True)\n #print('saved '+symbol+'PriceLastWeek.png to '+os.getcwd())\n plt.close()\n os.chdir(script)\n #print('Done - returning to '+os.getcwd())\n\n elif days == 'lastMonth':\n lastmonthdate = pd.to_datetime('today').floor('D') - timedelta(30)\n df = df[df.Date >= lastmonthdate]\n ax = df.plot('Date', 'volume', figsize=(15,10), fontsize=15)\n ax.set_xlabel('')\n ax.set_ylabel('Volume', fontsize=20)\n plt.ticklabel_format(style='plain', axis='y')\n plt.grid(True)\n os.chdir(images)\n plt.savefig(symbol+'VolumeLastMonth.png', optimize=True)\n #print('saved '+symbol+'VolumeLastMonth.png to '+os.getcwd())\n os.chdir(symbolFolder)\n #print('returning to '+os.getcwd())\n plt.close()\n ax = df.plot('Date', 'close', figsize=(11,10), fontsize=15)\n ax.set_xlabel('')\n ax.set_ylabel('Price', fontsize=20)\n plt.ticklabel_format(style='plain', axis='y')\n plt.grid(True)\n os.chdir(images)\n plt.savefig(symbol+'PriceLastMonth.png', optimize=True)\n #print('saved '+symbol+'PriceLastMonth.png to '+os.getcwd())\n os.chdir(script)\n #print('Done - returning to '+os.getcwd())\n plt.close()\n\n elif days == 'lastYear':\n lastyeardate = pd.to_datetime('today').floor('D') - timedelta(365)\n df = df[df.Date >= lastyeardate]\n ax = df.plot('Date', 'volume', figsize=(15,10), fontsize=15)\n ax.set_xlabel('')\n ax.set_ylabel('Volume', fontsize=20)\n plt.ticklabel_format(style='plain', axis='y')\n plt.grid(True)\n os.chdir(images)\n plt.savefig(symbol+'VolumeLastYear.png', optimize=True)\n #print('saved '+symbol+'VolumeLastYear.png to '+os.getcwd())\n os.chdir(symbolFolder)\n #print('returning to '+os.getcwd())\n plt.close()\n ax = df.plot('Date', 'close', figsize=(11,10), fontsize=15)\n plt.plot(df.Date, df['SMA1'], 'g--', label=\"Simple Moving Average - 25 Days\")\n plt.plot(df.Date, df['SMA2'], 'r--', label=\"Simple Moving Average - 100 Days\")\n ax.set_xlabel('')\n ax.set_ylabel('Price', fontsize=20)\n plt.legend()\n plt.ticklabel_format(style='plain', axis='y')\n plt.grid(True)\n os.chdir(images)\n plt.savefig(symbol+'PriceLastYear.png', optimize=True)\n #print('saved '+symbol+'PriceLastYear.png to '+os.getcwd())\n plt.close()\n os.chdir(script)\n #print('Done - returning to '+os.getcwd())\n \n else:\n ax = df.plot('Date', 'volume', figsize=(15,10), fontsize=15)\n ax.set_xlabel('')\n ax.set_ylabel('Volume', fontsize=20)\n plt.ticklabel_format(style='plain', axis='y')\n plt.grid(True)\n os.chdir(images)\n plt.savefig(symbol+'VolumeAllTime.png', optimize=True)\n #print('saved '+symbol+'VolumeAllTime.png to '+os.getcwd())\n plt.close()\n os.chdir(symbolFolder)\n #print('returning to '+os.getcwd())\n ax = df.plot('Date', 'close', figsize=(11,10), fontsize=15)\n plt.plot(df.Date, df['SMA1'], 'g--', label=\"Simple Moving Average - 25 Days\")\n plt.plot(df.Date, df['SMA2'], 'r--', label=\"Simple Moving Average - 100 Days\")\n ax.set_xlabel('')\n ax.set_ylabel('Price', fontsize=20)\n plt.legend()\n plt.ticklabel_format(style='plain', axis='y')\n plt.grid(True)\n os.chdir(images)\n plt.savefig(symbol+'PriceAllTime.png', optimize=True)\n #print('saved '+symbol+'PriceAllTime.png to '+os.getcwd())\n os.chdir(script)\n #print('Done - returning to '+os.getcwd())\n plt.close()\n\n\n# In[191]:\n\n\ndef start_visualizations():\n\n\n stockSymbol = [\"AAPL\", \"AMZN\", \"GOOGL\",\"MSFT\", \"DELL\", \"IBM\", \"INTC\", \"HPQ\",\n \"FB\", \"CSCO\", \"ORCL\", \"HPE\", \"MU\", \"DXC\", \"TMO\"]\n\n # initalize relative path directory\n script = os.getcwd()\n images = os.path.join(script, 'visualization', 'WebsitePNGs')\n \n for i in stockSymbol:\n days='lastWeek'\n GetOtherCompanies('{}_twits.csv'.format(i), days, script, images)\n days='lastMonth'\n GetOtherCompanies('{}_twits.csv'.format(i), days, script, images)\n days='lastYear'\n GetOtherCompanies('{}_twits.csv'.format(i), days, script, images)\n days='all'\n GetOtherCompanies('{}_twits.csv'.format(i), days, script, images)\n print('GetOtherCompaniesOver')\n days='lastWeek'\n GetVolume('{}Daily.csv'.format(i), days, script, images)\n days='lastMonth'\n GetVolume('{}Daily.csv'.format(i), days, script, images)\n days='lastYear'\n GetVolume('{}Daily.csv'.format(i), days, script, images)\n days='all'\n GetVolume('{}Daily.csv'.format(i), days, script, images)\n days='lastWeek'\n GetTags('{}_twits.csv'.format(i), days, script, images)\n days='lastMonth'\n GetTags('{}_twits.csv'.format(i), days, script, images)\n days='lastYear'\n GetTags('{}_twits.csv'.format(i), days, script, images)\n days='all'\n GetTags('{}_twits.csv'.format(i), days, script, images)\n print(i)\n\n#print('predictions')\n#start_predictions()\n#print(\"compute predictions\")\n#print(nowEST)\n#print(i)\nprint(\"visuals\")\nstart_visualizations()\n","sub_path":"VM/testingNNandVisuals.py","file_name":"testingNNandVisuals.py","file_ext":"py","file_size_in_byte":28972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"623608273","text":"from django.conf.urls import url\nfrom . import views\n\n\nurlpatterns = [\n url(r'^$', views.index, name='user_display'),\n url(r'^register', views.register, name='register'),\n url(r'^login', views.login, name='login'),\n url(r'^success/(?P\\w+)', views.success, name='success')\n]","sub_path":"course_manager/user_manager/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"58638113","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Сумма простых чисел меньше 10 равна 2 + 3 + 5 + 7 = 17.\n# Найдите сумму всех простых чисел меньше двух миллионов.\nimport time\nfrom math import sqrt\ndef is_prime(n):\n if n % 2 == 0:\n return False\n d = 3\n while d <= n**(1/2) and n % d != 0:\n d += 2\n return d <= n and n % d != 0\n\nn = 1000000\nstart = time.time()\ns = 3\nfor i in range(n):\n if is_prime(i):\n s += i\nprint(s, 'for', time.time() - start)\n\n\nstart = time.time()\nmas = [True]*n\nfor p in range(2, n):\n if p:\n for j in range(p*p, n, p):\n mas[j]=False\ns = 0\nfor el, m in enumerate(mas):\n if m:\n s += el\nprint(s, 'for', time.time() - start)\n","sub_path":"Python/p010.py","file_name":"p010.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"437666343","text":"import numpy as np\nnp.random.seed(2018) # for reproducibility\nimport itertools\nimport nltk\nimport pickle\n \n\n \nquestions_file = 'train_data_context.from'\nanswers_file = 'train_data_reply.to'\nvocabulary_file = 'vocabs'\n\nvocabulary_size = 7000\n\nprint (\"Reading the context data...\")\nq = open(questions_file, 'r')\nquestions = q.read()\nprint (\"Reading the answer data...\")\na = open(answers_file, 'r')\nanswers = a.read()\ncombined = answers + questions\nlines = [p for p in combined.split('\\n')]\n\nlines = ['BOS '+p+' EOS' for p in lines]\ntext = ' '.join(lines)\ntokenized_text = text.split()\n\n\n# Counting the word frequencies:\n\nword_freq = nltk.FreqDist(itertools.chain(tokenized_text))\nprint (\"Found %d unique words tokens.\" % len(word_freq.items()))\n\n\nvocab = word_freq.most_common(vocabulary_size-1)\n\n# Saving vocabulary:\nwith open(vocabulary_file, 'w') as v:\n pickle.dump(vocab, v)","sub_path":"create_vocabulary.py","file_name":"create_vocabulary.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"88413477","text":"import os\nimport numpy as np\nimport pandas as pd\n\n\ndef load_specific_prem_sheet(mixing_location, country):\n \"\"\"\n Load a mixing matrix sheet, according to name of the sheet (i.e. country)\n\n :param: mixing_location: str\n One of the four mixing locations - ('all_locations', 'home', 'other_locations', 'school', 'work')\n :param: country: str\n Name of the country of interest\n \"\"\"\n if country == \"victoria\":\n country = \"australia\"\n\n # Files with name ending with _1 have a header, but not those ending with _2 - plus need to determine file to read\n sheet_number, header_argument = (\"1\", 0) if country.title() < \"Mozambique\" else (\"2\", None)\n\n file_dir = os.path.join(\n os.path.abspath(os.path.dirname(__file__)),\n \"social_mixing_data\",\n \"MUestimates_\" + mixing_location + \"_\" + sheet_number + \".xlsx\",\n )\n\n return np.array(pd.read_excel(file_dir, sheet_name=country.title(), header=header_argument))\n\n\ndef load_all_prem_types(country):\n \"\"\"\n Collate the matrices of different location types for a given country\n\n :param country: str\n Name of the requested country\n \"\"\"\n matrices = {}\n for sheet_type in (\"all_locations\", \"home\", \"other_locations\", \"school\", \"work\"):\n matrices[sheet_type] = load_specific_prem_sheet(sheet_type, country)\n return matrices\n\n\ndef load_age_calibration():\n \"\"\"\n converts the age group specific cases to covid_19 agegroup\n 0–9, 10–19, 20–29, 30–39, 40–49, 50–59, 60–69, 70–79, 80+\n 2, 2,\t 13,\t 11,\t 11,\t 14,\t 8,\t 6,\t 4\n\n Returns:\n a pandas series\n \"\"\"\n\n age_breakpoints = [int(i_break) for i_break in list(range(0, 80, 5))]\n\n # split the case numbers into 5 year groups\n case_numbers = [2, 2, 13, 11, 11, 14, 8, 6, 4]\n case_numbers = [each / 2 for each in case_numbers for y in range(2)]\n\n # create case numbers for 75+\n y = case_numbers[:-3]\n y.append(sum(case_numbers[-3:]))\n\n return pd.Series(y, index=age_breakpoints)\n\n\ndef update_mixing_with_multipliers(mixing_matrix, multipliers):\n \"\"\"\n Updates the mixing matrix using some age-specific multipliers\n :param mixing_matrix: the baseline mixing-matrix\n :param multipliers: a matrix with the ages-specific multipliers\n :return: the updated mixing-matrix\n \"\"\"\n assert mixing_matrix.shape == multipliers.shape\n\n return np.multiply(mixing_matrix, multipliers)\n\n\ndef apply_age_specific_contact_multipliers(mixing_matrix, age_specific_multipliers):\n \"\"\"\n Update a mixing matrix using age-specific multipliers specified through a dictionary\n :param mixing_matrix: the original mixing matrix\n :param age_specific_multipliers: dict\n keys are age indices between 0 and 15, values are multipliers\n :return: the updated mixing matrix\n \"\"\"\n mixing_multipliers_matrix = np.ones((16, 16))\n for age_index, multiplier in age_specific_multipliers.items():\n assert(0 <= age_index <= 15)\n mixing_multipliers_matrix[age_index, :] *= multiplier\n mixing_multipliers_matrix[:, age_index] *= multiplier\n return update_mixing_with_multipliers(mixing_matrix, mixing_multipliers_matrix)\n\n\ndef get_all_prem_countries():\n \"\"\"\n Return the list of countries for which Prem et al provide contact matrices\n \"\"\"\n sheet_names = []\n for file_number in (\"1\", \"2\"):\n filepath = os.path.join(\n os.path.abspath(os.path.dirname(__file__)),\n \"social_mixing_data\",\n \"MUestimates_all_locations_\" + file_number + \".xlsx\",\n )\n xl = pd.ExcelFile(filepath)\n sheet_names += xl.sheet_names\n return sheet_names\n\n\ndef get_total_contact_rates_by_age(mixing_matrix, direction='horizontal'):\n \"\"\"\n Sum the contact-rates by age group\n :param mixing_matrix: the input mixing matrix\n :param direction: either 'horizontal' (infectee's perspective) or 'vertical' (infector's perspective)\n :return: dict\n keys are the age categories and values are the aggregated contact rates\n \"\"\"\n assert direction in ['horizontal', 'vertical'], \"direction should be in ['horizontal', 'vertical']\"\n aggregated_contact_rates = {}\n for i in range(16):\n if direction == 'horizontal':\n aggregated_contact_rates[str(5 * i)] = mixing_matrix[i, :].sum()\n else:\n aggregated_contact_rates[str(5 * i)] = mixing_matrix[:, i].sum()\n return aggregated_contact_rates\n","sub_path":"autumn/demography/social_mixing.py","file_name":"social_mixing.py","file_ext":"py","file_size_in_byte":4495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"126027904","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom collections import namedtuple\n\nfrom karbor.common import constants\nfrom karbor import exception\nfrom karbor.services.protection import graph\nfrom oslo_log import log as logging\n\nLOG = logging.getLogger(__name__)\n\n\nHOOKS = (\n HOOK_PRE_BEGIN,\n HOOK_PRE_FINISH,\n HOOK_MAIN,\n HOOK_COMPLETE\n) = (\n 'on_prepare_begin',\n 'on_prepare_finish',\n 'on_main',\n 'on_complete'\n)\n\nResourceHooks = namedtuple('ResourceHooks', [\n HOOK_PRE_BEGIN,\n HOOK_PRE_FINISH,\n HOOK_MAIN,\n HOOK_COMPLETE,\n])\n\n\nOPERATION_EXTRA_ARGS = {\n constants.OPERATION_RESTORE: ['restore', 'new_resources'],\n}\n\n\ndef noop_handle(*args, **kwargs):\n pass\n\n\nclass ResourceFlowGraphWalkerListener(graph.GraphWalkerListener):\n def __init__(self, resource_flow, operation_type, context, parameters,\n plugins, workflow_engine):\n super(ResourceFlowGraphWalkerListener, self).__init__()\n self.operation_type = operation_type\n self.context = context\n self.parameters = parameters or {}\n self.plugins = plugins\n self.workflow_engine = workflow_engine\n self.flow = resource_flow\n\n self.node_tasks = {}\n self.task_stack = []\n self.current_resource = None\n\n def _create_hook_tasks(self, operation_obj, resource):\n pre_begin_task = self._create_hook_task(operation_obj, resource,\n HOOK_PRE_BEGIN)\n pre_finish_task = self._create_hook_task(operation_obj, resource,\n HOOK_PRE_FINISH)\n main_task = self._create_hook_task(operation_obj, resource,\n HOOK_MAIN)\n post_task = self._create_hook_task(operation_obj, resource,\n HOOK_COMPLETE)\n\n return ResourceHooks(pre_begin_task, pre_finish_task, main_task,\n post_task)\n\n def _create_hook_task(self, operation_obj, resource, hook_type):\n method = getattr(operation_obj, hook_type, noop_handle)\n assert callable(method), (\n 'Resource {} method \"{}\" is not callable'\n ).format(resource.type, hook_type)\n\n task_name = \"{operation_type}_{hook_type}_{type}_{id}\".format(\n type=resource.type,\n id=resource.id,\n hook_type=hook_type,\n operation_type=self.operation_type,\n )\n\n parameters = {}\n parameters.update(self.parameters.get(resource.type, {}))\n resource_id = '{}#{}'.format(resource.type, resource.id)\n parameters.update(self.parameters.get(resource_id, {}))\n injects = {\n 'context': self.context,\n 'parameters': parameters,\n 'resource': resource,\n }\n requires = OPERATION_EXTRA_ARGS.get(self.operation_type, [])\n requires.append('operation_log')\n task = self.workflow_engine.create_task(method,\n name=task_name,\n inject=injects,\n requires=requires)\n return task\n\n def on_node_enter(self, node, already_visited):\n resource = node.value\n LOG.debug(\n \"Enter node (type: %(type)s id: %(id)s visited: %(visited)s)\",\n {\"type\": resource.type, \"id\": resource.id, \"visited\":\n already_visited}\n )\n self.current_resource = resource\n if already_visited:\n self.task_stack.append(self.node_tasks[resource.id])\n return\n\n if resource.type not in self.plugins:\n raise exception.ProtectionPluginNotFound(type=resource.type)\n\n protection_plugin = self.plugins[resource.type]\n operation_getter_name = 'get_{}_operation'.format(self.operation_type)\n operation_getter = getattr(protection_plugin, operation_getter_name)\n assert callable(operation_getter)\n operation_obj = operation_getter(resource)\n hooks = self._create_hook_tasks(operation_obj, resource)\n LOG.debug(\"added operation %s hooks\", self.operation_type)\n self.node_tasks[resource.id] = hooks\n self.task_stack.append(hooks)\n self.workflow_engine.add_tasks(self.flow, hooks.on_prepare_begin,\n hooks.on_prepare_finish, hooks.on_main,\n hooks.on_complete)\n self.workflow_engine.link_task(self.flow, hooks.on_prepare_begin,\n hooks.on_prepare_finish)\n self.workflow_engine.link_task(self.flow, hooks.on_prepare_finish,\n hooks.on_main)\n self.workflow_engine.link_task(self.flow, hooks.on_main,\n hooks.on_complete)\n\n def on_node_exit(self, node):\n resource = node.value\n LOG.debug(\n \"Exit node (type: %(type)s id: %(id)s)\",\n {\"type\": resource.type, \"id\": resource.id}\n )\n child_hooks = self.task_stack.pop()\n if len(self.task_stack) > 0:\n parent_hooks = self.task_stack[-1]\n self.workflow_engine.link_task(self.flow,\n parent_hooks.on_prepare_begin,\n child_hooks.on_prepare_begin)\n self.workflow_engine.link_task(self.flow,\n child_hooks.on_prepare_finish,\n parent_hooks.on_prepare_finish)\n self.workflow_engine.link_task(self.flow, child_hooks.on_complete,\n parent_hooks.on_complete)\n\n\ndef build_resource_flow(operation_type, context, workflow_engine,\n plugins, resource_graph, parameters):\n LOG.info(\"Build resource flow for operation %s\", operation_type)\n\n resource_graph_flow = workflow_engine.build_flow(\n 'ResourceGraphFlow_{}'.format(operation_type),\n 'graph',\n )\n resource_walker = ResourceFlowGraphWalkerListener(resource_graph_flow,\n operation_type,\n context,\n parameters,\n plugins,\n workflow_engine)\n walker = graph.GraphWalker()\n walker.register_listener(resource_walker)\n LOG.debug(\"Starting resource graph walk (operation %s)\", operation_type)\n walker.walk_graph(resource_graph)\n LOG.debug(\"Finished resource graph walk (operation %s)\", operation_type)\n return resource_graph_flow\n","sub_path":"karbor/services/protection/resource_flow.py","file_name":"resource_flow.py","file_ext":"py","file_size_in_byte":7326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"308248357","text":"import re, os\nfrom datetime import datetime\nfrom ConfigParser import ConfigParser\n\n# Standard timestamp format for serlialization\ntime_hfmt = '%A, %d %B %Y'\ntime_isofmt = '%Y-%m-%dT%H:%M:%SZ'\n\n# List of valid headers to extract from context\nheader_table = [\n 'view',\n 'permalink',\n 'draft',\n 'pubdate',\n 'title',\n 'author',\n 'static',\n 'snip',\n ]\n\n# Dictionary of views\nview_mapper = {\n 'default' : 'default.html',\n 'single' : 'single.html',\n 'index' : 'index.html',\n }\n\ndef build_slug(text):\n slug = re.sub(r'\\W+', '-', text.lower())\n return re.sub(r'-+', '-', slug).strip('-')[:30]\n\ndef parse_config(filename):\n \"\"\"Uses ConfigParser to parse core.cfg configuration file\"\"\"\n\n config = {}\n parser = ConfigParser()\n parser.read(filename)\n for (k, v) in parser.items('Main'):\n config[k] = v\n return config\n\ndef parse_header(raw_header):\n \"\"\"Parses raw header string into context\"\"\"\n \n context = {}\n for line in raw_header.split('\\n'):\n (key, value) = line.split(': ')\n context[key] = value\n return context\n\ndef build_timestamp_h(self, pubdate = None):\n \"\"\"Builds timestamp to be displayed in rendered page\"\"\"\n \n if pubdate is not None:\n t = datetime.strptime(pubdate, util.time_isofmt)\n return t.strftime(util.time_hfmt)\n return '[Unpublished]'\n\ndef build_path(basedir, permalink):\n \"\"\"Given a basedir and permalink, use os.join to build the path of\n the final file to write\"\"\"\n \n return os.path.join(basedir, permalink + '.html')\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"376974706","text":"\"\"\"\n105. Construct Binary Tree from Preorder and Inorder Traversal \nhttps://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/\n\"\"\"\nfrom typing import List\nfrom binary_tree import BinaryTreeNode, print_binary_tree\n\nclass Solution:\n def buildTree(self, preorder: List[int], inorder: List[int]) -> BinaryTreeNode:\n if not preorder or not inorder or len(preorder) != len(inorder):\n return None\n\n def build(preorder_left, preorder_right, inorder_left, inorder_right):\n # base\n if preorder_left > preorder_right:\n return None\n\n # process\n preorder_root = preorder_left\n inorder_root = index[preorder[preorder_root]]\n root = BinaryTreeNode(preorder[preorder_root])\n\n # drill down\n size_left_subtree = inorder_root - inorder_left\n root.left = build(preorder_left + 1, preorder_left + size_left_subtree, inorder_left, inorder_root + 1)\n root.right = build(preorder_left + size_left_subtree + 1, preorder_right, inorder_root + 1, inorder_right)\n\n # return\n return root\n\n # preorder = [root, [left subtree], [right subtree]]\n # inorder = [[left subtree], root, [right subtree]]\n n = len(preorder)\n index = { elem: i for i, elem in enumerate(inorder) }\n return build(0, n-1, 0, n-1)\n\nsolution = Solution()\npreorder = [3,9,20,15,7]\ninorder = [9,3,15,20,7]\nans = solution.buildTree(preorder, inorder)\nprint_binary_tree(ans)\n","sub_path":"03/construct_binary_tree.py","file_name":"construct_binary_tree.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"521345457","text":"import gym\nimport collections\nimport tensorboard\nfrom tensorboardX import SummaryWriter\n\nENV_name = \"FrozenLake-v0\"\ngamma = 0.9\ntest_episodes = 20\n\nclass Agent:\n def __init__(self):\n self.env = gym.make(ENV_name)\n self.state = self.env.reset()\n self.rewards = collections.defaultdict(float) #it will assign default value 0.0 to a new key\n self.transits = collections.defaultdict(collections.Counter) # to keep a count of hashable items\n self.values = collections.defaultdict(float)\n\n def play_n_random_steps(self, count):\n for i in range(count):\n action = self.env.action_space.sample() #choosing a random action\n #updating the reward and transition tables\n new_state, reward, is_done, _ = self.env.step(action)\n self.rewards[(self.state,action,new_state)] = reward\n self.transits[(self.state,action)][new_state]+=1\n self.state = self.env.reset() if is_done else new_state\n\n def calc_action_value(self, state, action):\n target_counts = self.transits[(state,action)]\n total = sum(target_counts.values())\n action_value = 0.0\n for tgt_state, count in target_counts.items():\n reward = self.rewards[(state,action,tgt_state)]\n action_value += (count/total)*(reward + gamma*self.values[tgt_state])\n return action_value\n\n def select_action(self,state): #choose the best action to take for given state\n best_action, best_value = None, None\n for action in range(self.env.action_space.n):\n action_value = self.calc_action_value(state, action)\n if best_value is None or best_value < action_value:\n best_value = action_value\n best_action = action\n return best_action\n\n def play_episode(self, env):\n total_reward = 0.0\n state = env.reset()\n while True:\n action = self.select_action(state)\n new_state, reward, is_done, __ = env.step(action)\n self.rewards[(state,action,new_state)] = reward\n self.transits[(state,action)][new_state] += 1\n total_reward += reward\n if is_done: break\n state = new_state\n return total_reward\n\n def value_iteration(self):\n for state in range(self.env.observation_space.n):\n state_values = [self.calc_action_value(state,action) for action in range(self.env.action_space.n)]\n self.values[state] = max(state_values)\n\nif __name__ == \"__main__\":\n test_env = gym.make(ENV_name)\n agent = Agent()\n writer = SummaryWriter('value_iteration_fl/exp1')\n\n iter_no = 0\n best_reward = 0.0\n while True:\n iter_no += 1\n agent.play_n_random_steps(100)\n agent.value_iteration()\n reward = 0.0\n for _ in range(test_episodes):\n reward += agent.play_episode(test_env)\n \n reward /= test_episodes\n writer.add_scalar(\"reward\", reward, iter_no)\n if reward > best_reward:\n print(\"Best reward updated %.3f -> %.3f\"%(best_reward,reward))\n best_reward = reward\n if reward > 0.80:\n print(\"Solved in %d iterations!\"%(iter_no))\n break\n writer.close()","sub_path":"Value Iteration/value_iteration_on_frozenlake.py","file_name":"value_iteration_on_frozenlake.py","file_ext":"py","file_size_in_byte":3267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"309282774","text":"\"\"\"\n\n Goes through all the interesting sources that the server knows\n about and downloads new articles saving them in the DB. \n\n\n\"\"\"\nfrom datetime import datetime\n\nimport newspaper\nimport re\n\nimport zeeguu_core\n\nfrom zeeguu_core import model\nfrom zeeguu_core.content_retriever.content_cleaner import cleanup_non_content_bits\nfrom zeeguu_core.content_retriever.quality_filter import sufficient_quality\nfrom zeeguu_core.model import Url, RSSFeed, LocalizedTopic, ArticleWord\nfrom zeeguu_core.constants import SIMPLE_TIME_FORMAT\nimport requests\n\nLOG_CONTEXT = \"FEED RETRIEVAL\"\n\n\ndef log(msg: str):\n zeeguu_core.log(LOG_CONTEXT + \" \" + msg)\n\n\ndef _url_after_redirects(url):\n # solve redirects and save the clean url\n response = requests.get(url)\n return response.url\n\n\ndef _date_in_the_future(time):\n from datetime import datetime\n return time > datetime.now()\n\n\ndef download_from_feed(feed: RSSFeed, session, limit=1000):\n \"\"\"\n\n Session is needed because this saves stuff to the DB.\n\n\n last_crawled_time is useful because otherwise there would be a lot of time\n wasted trying to retrieve the same articles, especially the ones which\n can't be retrieved, so they won't be cached.\n\n\n \"\"\"\n log(feed.title)\n\n downloaded = 0\n skipped = 0\n skipped_due_to_low_quality = dict()\n skipped_already_in_db = 0\n\n last_retrieval_time_from_DB = None\n last_retrieval_time_seen_this_crawl = None\n\n if feed.last_crawled_time:\n last_retrieval_time_from_DB = feed.last_crawled_time\n log(f\"last retrieval time from DB = {last_retrieval_time_from_DB}\")\n\n try:\n items = feed.feed_items()\n except:\n log(\"Failed to connect to feed\")\n return\n\n for feed_item in items:\n\n if downloaded >= limit:\n break\n\n try:\n url = _url_after_redirects(feed_item['url'])\n except requests.exceptions.TooManyRedirects:\n log(f\"Too many redirects for: {url}\")\n continue\n except Exception:\n log(f\"could not get url after redirects for: {url}\")\n continue\n\n try:\n this_article_time = datetime.strptime(feed_item['published'], SIMPLE_TIME_FORMAT)\n this_article_time = this_article_time.replace(tzinfo=None)\n except:\n log(f\"can't get time from {url}: {feed_item['published']}\")\n continue\n\n if _date_in_the_future(this_article_time):\n log(\"article from the future...\")\n continue\n\n if last_retrieval_time_from_DB:\n\n if this_article_time < last_retrieval_time_from_DB:\n skipped += 1\n continue\n\n title = feed_item['title']\n summary = feed_item['summary']\n\n log(url)\n\n try:\n art = model.Article.find(url)\n except:\n import sys\n ex = sys.exc_info()[0]\n log(f\" {LOG_CONTEXT}: For some reason excepted during Article.find \\n{str(ex)}\")\n continue\n\n if (not last_retrieval_time_seen_this_crawl) or (this_article_time > last_retrieval_time_seen_this_crawl):\n last_retrieval_time_seen_this_crawl = this_article_time\n\n if art:\n skipped_already_in_db += 1\n log(\"- already in db\")\n else:\n try:\n\n art = newspaper.Article(url)\n art.download()\n art.parse()\n log(\"- succesfully parsed\")\n\n cleaned_up_text = cleanup_non_content_bits(art.text)\n\n quality_article = sufficient_quality(art, skipped_due_to_low_quality)\n if quality_article:\n from zeeguu_core.language.difficulty_estimator_factory import DifficultyEstimatorFactory\n\n try:\n # Create new article and save it to DB\n new_article = zeeguu_core.model.Article(\n Url.find_or_create(session, url),\n title,\n ', '.join(art.authors),\n cleaned_up_text,\n summary,\n this_article_time,\n feed,\n feed.language\n )\n session.add(new_article)\n session.commit()\n downloaded += 1\n\n add_topics(new_article, session)\n log(\"- added topics\")\n add_searches(title, url, new_article, session)\n log(\"- added keywords\")\n session.commit()\n\n if last_retrieval_time_seen_this_crawl:\n feed.last_crawled_time = last_retrieval_time_seen_this_crawl\n session.add(feed)\n\n except Exception as e:\n log(f'Something went wrong when creating article and attaching words/topics: {e}')\n log(\"rolling back the session... \")\n session.rollback()\n\n except Exception as e:\n # raise e\n import sys\n ex = sys.exc_info()[0]\n log(f\"Failed to create zeeguu.Article from {url}\\n{str(ex)}\")\n\n log(f' Skipped due to time: {skipped} ')\n log(f' Downloaded: {downloaded}')\n log(f' Low Quality: {skipped_due_to_low_quality}')\n log(f' Already in DB: {skipped_already_in_db}')\n\n\ndef add_topics(new_article, session):\n for loc_topic in LocalizedTopic.query.all():\n if loc_topic.language == new_article.language and loc_topic.matches_article(new_article):\n new_article.add_topic(loc_topic.topic)\n session.add(new_article)\n\n\ndef add_searches(title, url, new_article, session):\n \"\"\"\n This method takes the relevant keywords from the title\n and URL, and tries to properly clean them.\n It finally adds the ArticleWord to the session, to be committed as a whole.\n :param title: The title of the article\n :param url: The url of the article\n :param new_article: The actual new article\n :param session: The session to which it should be added.\n \"\"\"\n\n # Split the title, path and url netloc (sub domain)\n all_words = title.split()\n from urllib.parse import urlparse\n\n # Parse the URL so we can call netloc and path without a lot of regex\n parsed_url = urlparse(url)\n all_words += re.split('; |, |\\*|-|%20|/', parsed_url.path)\n all_words += parsed_url.netloc.split('.')[0]\n\n for word in all_words:\n # Strip the unwanted characters\n word = strip_article_title_word(word)\n # Check if the word is of proper length, not only digits and not empty or www\n if word in ['www', '', ' '] or word.isdigit() or len(word) < 3 or len(word) > 25:\n continue\n else:\n # Find or create the ArticleWord and add it to the session\n article_word_obj = ArticleWord.find_by_word(word)\n if article_word_obj is None:\n article_word_obj = ArticleWord(word)\n article_word_obj.add_article(new_article)\n session.add(article_word_obj)\n\n\ndef strip_article_title_word(word: str):\n \"\"\"\n\n Used when tokenizing the titles of articles\n in order to index them for search\n\n \"\"\"\n return word.strip('\":;?!<>\\'').lower()\n","sub_path":"zeeguu_core/content_retriever/article_downloader.py","file_name":"article_downloader.py","file_ext":"py","file_size_in_byte":7473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"140938930","text":"import tensorflow as tf\nimport numpy as np\n\nx_data = np.array([[0,0],[0,1],[1,0],[1,1]],dtype=np.float32)\ny_data = np.array([[0],[1],[1],[0]],dtype=np.float32)\n\n# XOR with logistic regression? why?\n# y는 0 or 1 이니까 굳이 복잡한 softmax안쓰고 binary classification\n\nX = tf.placeholder(tf.float32)\nY = tf.placeholder(tf.float32)\nW = tf.Variable(tf.random.normal(([2,1]),name='weight'))\nb = tf.Variable(tf.random.normal(([1]),name='bias'))\n\n# logits = tf.matmul(X,W)+b\n# hypothesis = tf.sigmoid(logits)\nhypothesis = tf.sigmoid(tf.matmul(X,W)+b)\n\ncost = -tf.reduce_mean(Y*tf.log(hypothesis)+(1-Y)*tf.log(1-hypothesis))\ntrain = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)\n\n# True if hypothesis>0.5 else False\npredicted = tf.cast(hypothesis > 0.5,dtype=tf.float32)\naccuracy = tf.reduce_mean(tf.cast(tf.equal(predicted,Y),dtype=tf.float32))\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n\n for step in range(10001):\n sess.run(train,feed_dict={X:x_data,Y:y_data})\n if step % 100 == 0:\n print(\"step:\",step,\"cost:\",sess.run(cost,feed_dict={X:x_data,Y:y_data}))\n h,c,a = sess.run([hypothesis,cost,accuracy],feed_dict={X:x_data,Y:y_data})\n print(\"hypothesis:\",h)\n print(\"cost:\",c)\n print(\"accuracy:\",a)\n\n #result: not good.\n","sub_path":"practice/11_NeuralNetsForXORLab.py","file_name":"11_NeuralNetsForXORLab.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"110146656","text":"import tensorflow as tf\n\nwith tf.device('/gpu:0'):\n a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')\n b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')\n c = tf.matmul(a, b)\nwith tf.device('/cpu:0'):\n e = tf.constant([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18], shape=[2, 9], dtype=tf.float32,\n name='e')\n f = tf.matmul(c, e)\nsess = tf.Session(config=tf.ConfigProto(log_device_placement=True))\nprint(sess.run(f))\n","sub_path":"sandbox/gpu_cpu.py","file_name":"gpu_cpu.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"640614068","text":"#!/usr/bin/env python\n#-*- coding: UTF-8 -*-\n\nimport logging.handlers\nimport os\nfrom utils import config\n\nLOG_FOLDER = config.LOG_FOLDER\nLOG_FILE = config.LOG_FILE\nDAYS_FOR_ROTATE = config.DAYS_FOR_ROTATE\nLOG = LOG_FOLDER + LOG_FILE\n\ntry:\n os.stat(LOG_FOLDER)\nexcept:\n os.mkdir(LOG_FOLDER)\n\ntry:\n logger = logging.getLogger('sync')\n loggerHandler = logging.handlers.TimedRotatingFileHandler(filename=LOG, when='midnight', interval=1, backupCount=DAYS_FOR_ROTATE)\n formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')\n loggerHandler.setFormatter(formatter)\n logger.addHandler(loggerHandler)\n logger.setLevel(logging.DEBUG)\nexcept:\n print('------------------------------------------------------------------')\n print('[ERROR] Error writing log at %s' % LOG)\n print('[ERROR] Please verify path folder exits and write permissions')\n print('------------------------------------------------------------------')\n exit()\n\ndef get_logger():\n \"\"\" Return an instance of logger to write log at dispatcher.log file \"\"\"\n return logger\n","sub_path":"Workspace/KyrosX/kyrosx_sync/logUtils/loggerSync.py","file_name":"loggerSync.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"162895662","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('articles', '0005_auto_20150216_1530'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='article',\n name='code',\n field=models.TextField(default=datetime.datetime(2015, 2, 16, 16, 26, 19, 385659), blank=b'True'),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='article',\n name='ending',\n field=models.TextField(blank=b'True'),\n preserve_default=True,\n ),\n ]\n","sub_path":"articles/migrations/0006_auto_20150216_1626.py","file_name":"0006_auto_20150216_1626.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"20840693","text":"import asyncio\nfrom random import choice, randint\nfrom typing import Literal, Optional\n\nfrom asciimatics.effects import Mirage, Print, Stars\nfrom asciimatics.particles import (\n PalmFirework, RingFirework, SerpentFirework, StarFirework\n)\nfrom asciimatics.renderers import FigletText, Rainbow, SpeechBubble\nfrom asciimatics.scene import Scene\nfrom asciimatics.screen import Screen\n\nfrom app.types.events import Event\n\n_victory_key: Optional[Literal[\"n\", \"q\"]] = None\n\n\ndef update_screen(\n end_time: int, loop: asyncio.AbstractEventLoop, screen: Screen\n) -> None:\n \"\"\"Checks if the user input matches with keys s or q.\"\"\"\n event = screen.get_event()\n screen.draw_next_frame()\n global _victory_key\n try:\n if event is not None and chr(event.key_code) == \"n\":\n _victory_key = \"n\"\n loop.stop()\n elif event is not None and chr(event.key_code) == \"q\":\n _victory_key = \"q\"\n loop.stop()\n else:\n if loop.time() < end_time:\n loop.call_later(0.05, update_screen, end_time, loop, screen)\n else:\n loop.stop()\n\n except: # noqa: E722\n if loop.time() < end_time:\n loop.call_later(0.05, update_screen, end_time, loop, screen)\n else:\n loop.stop()\n\n\ndef victory(screen: Screen) -> Event:\n \"\"\"Displays the victory screen.\"\"\"\n scenes = []\n effects = [\n Stars(screen, screen.width),\n Print(\n screen,\n SpeechBubble(\"Press q to return to main menu.\"),\n x=screen.width // 2 - 40,\n y=screen.height // 2 + 3,\n start_frame=5,\n transparent=True,\n ),\n ]\n effects.append(\n Print(\n screen,\n SpeechBubble(\"Press n to move to next level.\"),\n x=screen.width // 2 + 10,\n y=screen.height // 2 + 3,\n start_frame=5,\n transparent=False,\n )\n )\n\n # display fireworks\n for _ in range(20):\n fireworks = [\n (PalmFirework, 25, 30),\n (PalmFirework, 25, 30),\n (StarFirework, 25, 35),\n (StarFirework, 25, 35),\n (StarFirework, 25, 35),\n (RingFirework, 20, 30),\n (SerpentFirework, 30, 35),\n ]\n firework, start, stop = choice(fireworks)\n effects.insert(\n 1,\n firework(\n screen,\n randint(0, screen.width),\n randint(screen.height // 8, screen.height * 3 // 4),\n randint(start, stop),\n start_frame=randint(0, 250),\n ),\n )\n\n effects.append(\n Mirage(\n screen,\n Rainbow(screen, FigletText(\"Victory\", font=\"banner3\")),\n screen.height // 2 - 17,\n colour=7,\n )\n )\n effects.append(\n Print(\n screen,\n SpeechBubble(\"Congratulations you have cleared this level!\"),\n screen.height // 2 - 8,\n speed=1,\n start_frame=5,\n transparent=False,\n )\n )\n\n scenes.append(Scene(effects, -1))\n screen.set_scenes(scenes)\n loop = asyncio.new_event_loop()\n end_time = loop.time() + 500.0\n loop.call_soon(update_screen, end_time, loop, screen)\n loop.run_forever()\n loop.close()\n screen.clear()\n screen.close()\n if _victory_key == \"n\":\n return Event.ToNextLevel\n elif _victory_key == \"q\":\n return Event.ToMainMenu\n else:\n return Event.ToNextLevel\n","sub_path":"app/menus/victory_menu.py","file_name":"victory_menu.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"120776559","text":"import json\nimport requests\n\nURL = 'https://api.fitbit.com'\n\ndef getHeaders():\n\n readToken = open(\"lib/api/refreshToken.rt\",\"r\")\n refreshToken = readToken.read()\n GET_BEARER = '/oauth2/token'\n api_url = URL + GET_BEARER\n\n headers = {\n 'Authorization': 'Basic MjJDWUNQOmRhZTc3OGUxM2IzNDE2NjJmM2JjYmM5NDMzMDQ0NmU1',\n 'Content-Type': 'application/x-www-form-urlencoded'\n }\n args = {\n 'grant_type' : 'refresh_token',\n 'refresh_token' : refreshToken\n }\n\n response = requests.post(api_url,\n headers=headers,\n params=args)\n\n responseObj = json.loads(response.content)\n\n try:\n newRefreshToken = responseObj['refresh_token']\n saveToken = open(\"lib/api/refreshToken.rt\",\"w\")\n saveToken.write(newRefreshToken)\n except:\n return responseObj\n\n return {\n 'Authorization': ('Bearer {0}').format(responseObj['access_token'])\n }\n\ndef apiRequest(uri, opts, reqType):\n\n uri = uri.format_map(opts)\n headers = getHeaders()\n\n print(\"\\nPOST TO : \" + uri)\n #print(\"HEADERS : \" + json.dumps(headers))\n print(\"ARGS : \" + json.dumps(opts) + \"\\n\")\n \n postUrl = URL + uri\n\n if(reqType == \"POST\"):\n response = requests.post(postUrl,\n headers = headers, \n params = opts)\n elif(reqType == \"GET\"):\n response = requests.get(postUrl,\n headers = headers, \n params = opts)\n\n else :\n return {'success':False}\n\n return json.loads(response.content)\n\n# Collection of API URLS\nGET_HEART = '/1/user/-/activities/heart/date/{date}/1d/{detail-level}/time/{start-time}/{end-time}.json'\n\n#getHeart method\n#opts.date (today)\n#opts.detail-level (1sec)\n#opts.start-time (00:00)\n#opts.end-time (00:01)\ndef getHeart(opts):\n return apiRequest(\n GET_HEART,\n opts, \"GET\"\n )","sub_path":"src/lib/api/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"77352024","text":"import random\ndef sorting(z):\n r=1\n while r<=50:\n for i in range(0, len(z)-1):\n if z[i]>z[i+1]:\n t=z[i];v=z[i+1];z[i]=v;z[i+1]=t\n i+=1\n i=1\n r+=1\n#main\ngroup=set()\nn=len(group)\nwhile n<50:\n p=random.randint(0,1000)\n group.add(p)\n n=len(group)\ngroup=list(group)\nprint()\nsorting(group)\ne=0\nwhile e<50:\n print(group[e],end=\" \")\n e+=1\nprint()\nprint(\"max value: \",max(group[0:n]))\nprint(\"min value: \",min(group[0:n]))\n","sub_path":"190403_w5/190403_w5_3.py","file_name":"190403_w5_3.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"494590033","text":"from qgis.core import (QgsProcessing, QgsProcessingAlgorithm, QgsProcessingParameterFeatureSource,\n QgsProcessingParameterFeatureSink, QgsProcessingParameterField, QgsField,\n QgsFeature, QgsWkbTypes, QgsFields, QgsProcessingUtils,\n QgsProcessingException)\n\nfrom qgis.PyQt.QtCore import QVariant\nfrom los_tools.constants.field_names import FieldNames\nfrom los_tools.utils import get_doc_file\n\n\nclass AzimuthPointPolygonAlgorithm(QgsProcessingAlgorithm):\n\n POINT_LAYER = \"PointLayer\"\n POINT_LAYER_FIELD_ID = \"PointLayerID\"\n OBJECT_LAYER = \"ObjectLayer\"\n OBJECT_LAYER_FIELD_ID = \"ObjectLayerID\"\n OUTPUT_TABLE = \"OutputTable\"\n\n def initAlgorithm(self, config=None):\n\n self.addParameter(\n QgsProcessingParameterFeatureSource(self.POINT_LAYER, \"Point layer\",\n [QgsProcessing.TypeVectorPoint]))\n\n self.addParameter(\n QgsProcessingParameterField(self.POINT_LAYER_FIELD_ID,\n \"Point layer ID field\",\n parentLayerParameterName=self.POINT_LAYER,\n type=QgsProcessingParameterField.Numeric,\n optional=False))\n\n self.addParameter(\n QgsProcessingParameterFeatureSource(\n self.OBJECT_LAYER, \"Object layer\",\n [QgsProcessing.TypeVectorLine, QgsProcessing.TypeVectorPolygon]))\n\n self.addParameter(\n QgsProcessingParameterField(self.OBJECT_LAYER_FIELD_ID,\n \"Object layer ID field\",\n parentLayerParameterName=self.OBJECT_LAYER,\n type=QgsProcessingParameterField.Numeric,\n optional=False))\n\n self.addParameter(QgsProcessingParameterFeatureSink(self.OUTPUT_TABLE, \"Output table\"))\n\n def checkParameterValues(self, parameters, context):\n\n return super().checkParameterValues(parameters, context)\n\n def processAlgorithm(self, parameters, context, feedback):\n\n point_layer = self.parameterAsVectorLayer(parameters, self.POINT_LAYER, context)\n\n if point_layer is None:\n raise QgsProcessingException(self.invalidSourceError(parameters, self.POINT_LAYER))\n\n point_field_id = self.parameterAsString(parameters, self.POINT_LAYER_FIELD_ID, context)\n\n object_layer = self.parameterAsVectorLayer(parameters, self.OBJECT_LAYER, context)\n\n if object_layer is None:\n raise QgsProcessingException(self.invalidSourceError(parameters, self.OBJECT_LAYER))\n\n object_field_id = self.parameterAsString(parameters, self.OBJECT_LAYER_FIELD_ID, context)\n\n fields = QgsFields()\n fields.append(QgsField(FieldNames.ID_POINT, QVariant.Int))\n fields.append(QgsField(FieldNames.ID_OBJECT, QVariant.Int))\n fields.append(QgsField(FieldNames.AZIMUTH, QVariant.Double))\n\n sink, dest_id = self.parameterAsSink(parameters, self.OUTPUT_TABLE, context, fields,\n QgsWkbTypes.NoGeometry, point_layer.sourceCrs())\n\n if sink is None:\n raise QgsProcessingException(self.invalidSinkError(parameters, self.OUTPUT_TABLE))\n\n total = point_layer.dataProvider().featureCount() * object_layer.dataProvider(\n ).featureCount()\n i = 0\n\n object_layer_features = object_layer.getFeatures()\n\n for object_layer_feature_count, object_layer_feature in enumerate(object_layer_features):\n\n for point_layer_feature_count, point_layer_feature in enumerate(\n point_layer.getFeatures()):\n\n if feedback.isCanceled():\n break\n\n azimuth = point_layer_feature.geometry().centroid().asPoint().azimuth(\n object_layer_feature.geometry().centroid().asPoint())\n\n if azimuth < 0:\n azimuth = 360 + azimuth\n\n f = QgsFeature(fields)\n f.setAttribute(f.fieldNameIndex(FieldNames.ID_POINT),\n point_layer_feature.attribute(point_field_id))\n f.setAttribute(f.fieldNameIndex(FieldNames.ID_OBJECT),\n object_layer_feature.attribute(object_field_id))\n f.setAttribute(f.fieldNameIndex(FieldNames.AZIMUTH), azimuth)\n\n sink.addFeature(f)\n\n i += 1\n feedback.setProgress((i / total) * 100)\n\n return {self.OUTPUT_TABLE: dest_id}\n\n def name(self):\n return \"azimuth\"\n\n def displayName(self):\n return \"Extract Azimuth between Points and Centroids\"\n\n def group(self):\n return \"Azimuths\"\n\n def groupId(self):\n return \"azimuths\"\n\n def createInstance(self):\n return AzimuthPointPolygonAlgorithm()\n\n def helpUrl(self):\n return \"https://jancaha.github.io/qgis_los_tools/tools/Angles/tool_azimuth/\"\n\n def shortHelpString(self):\n return QgsProcessingUtils.formatHelpMapAsHtml(get_doc_file(__file__), self)\n","sub_path":"los_tools/processing/azimuths/tool_azimuth.py","file_name":"tool_azimuth.py","file_ext":"py","file_size_in_byte":5212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"12855796","text":"from __future__ import division, print_function\nimport numpy as np\nfrom scipy.signal import fftconvolve, convolve\nimport itertools\n\n\nclass Polynomial(object):\n def __init__(self, coeff, order='degrevlex', lead_term=None):\n '''\n terms, int- number of chebyshev polynomials each variable can have. Each dimension will have term terms\n dim, int- number of different variables, how many dim our tensor will be\n order, string- how you want to order your polynomials. Grevlex is default\n '''\n self.coeff = coeff\n self.dim = self.coeff.ndim\n self.terms = np.prod(self.coeff.shape)\n self.order = order\n self.shape = self.coeff.shape\n self.max_term = np.max(self.shape) -1\n\n if lead_term is None:\n self.update_lead_term()\n else:\n self.lead_term = lead_term\n\n def check_column_overload(self, max_values, current, column):\n '''\n Checks to make sure that we aren't going into the negatives, aka the current value can't ever be greater\n than the max_values value. We check at the column where we have just added stuff and might have an\n overflow\n Return true if the whole thing is full and needs to increment i again. False otherwise.\n '''\n initial_column = column\n if(current[column] > max_values[column]):\n initial_amount = current[column]\n extra = current[column] - max_values[column]\n current[column] = max_values[column]\n while(extra>0):\n if(column==0):\n current[0] += extra\n #Sets all the stuff back in the initial row, needed if the while loop is used.\n for i in range(0, initial_column):\n current[i+1] += current[i]\n current[i] = 0\n return True\n else:\n column -=1\n allowed = max_values[column] - current[column]\n if(allowed > extra):\n current[column] += extra\n extra = 0\n else:\n current[column] += allowed\n extra -= allowed\n return False\n else:\n return False\n\n def degrevlex_gen(self):\n '''\n yields grevlex ordering co-ordinates in order to find\n the leading coefficent\n '''\n max_values = tuple(self.shape)-np.ones_like(self.shape)\n base = max_values\n current = np.zeros(self.dim)\n yield base-current\n while True:\n for i in range(1, sum(max_values)+1):\n onward = True\n #set the far right column to i\n current = np.zeros(self.dim)\n current[self.dim-1] = i\n #This can't return false, as we start at the begenning. Always has enough room to spill over.\n self.check_column_overload(max_values, current, self.dim-1)\n yield base - current\n while onward:\n #Find the leftmost thing\n for j in range(0, self.dim):\n if(current[j] != 0):\n left_most_spot = j\n break\n if(left_most_spot != 0):\n #Slide it to the left\n current[left_most_spot] -= 1\n current[left_most_spot-1] += 1\n yield base - current\n elif(current[j] == i):\n #Reset it for the next run\n current[0] = 0\n onward = False\n else:\n #if I'm at the end push back everything to the next leftmost thing and slide it plus 1\n amount = current[0]\n for j in range(1,self.dim):\n if(current[j] != 0):\n next_left_most_spot = j\n break\n current[0] = 0\n current[next_left_most_spot] -= 1\n current[next_left_most_spot-1] += amount+1\n\n spot_to_check = next_left_most_spot-1\n #Loops throught this until everything is balanced all right or we need to increase i\n while(self.check_column_overload(max_values, current, spot_to_check)):\n new_spot_to_check = -1\n for j in range(spot_to_check+1, self.dim):\n if(current[j] != 0):\n new_spot_to_check = j\n break\n if(new_spot_to_check == -1):\n onward = False\n break\n else:\n amount = current[spot_to_check]\n current[spot_to_check] = 0\n current[new_spot_to_check] -=1\n current[new_spot_to_check-1] += (amount+1)\n spot_to_check = new_spot_to_check-1\n if(onward):\n yield base-current\n return\n\n def update_lead_term(self,start = None):\n #print('Updating Leading Coeff...')\n if self.order == 'degrevlex':\n gen = self.degrevlex_gen()\n for idx in gen:\n if self.coeff[tuple(idx)] != 0:\n self.lead_term = idx\n self.lead_coeff = self.coeff[tuple(idx)]\n break\n #print('Leading Coeff is {}'.format(self.lead_term))\n","sub_path":"groebner/polynomial.py","file_name":"polynomial.py","file_ext":"py","file_size_in_byte":5865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"552597389","text":"from flask import request, redirect, url_for, render_template, flash, session # 後使用も含め必要パッケージインストール\nfrom flask import current_app as app # __init__.pyで作成したappをインポート\nfrom functools import wraps\nfrom flask import Blueprint\n\nview = Blueprint('view', __name__)\n\n\ndef login_required(view):\n\t@wraps(view)\n\tdef inner(*args, **kwargs):\n\t\tif not session.get('logged_in'):\n\t\t\treturn redirect(url_for('view.login'))\n\t\treturn view(*args, **kwargs)\n\treturn inner\n\n# 当初ここに書いたshow_entriesをflask_blog/views/entries.pyに移動\n\n\n@view.route('/login', methods=['GET', 'POST'])\ndef login():\n\terror = None\n\tif request.method == 'POST':\n\t\tif request.form['username'] != app.config['USERNAME']:\n\t\t\tflash('ユーザー名が異なります')\n\t\telif request.form['password'] != app.config['PASSWORD']:\n\t\t\tflash('パスワードが異なります')\n\t\telse:\n\t\t\tsession['logged_in'] = True\n\t\t\tflash('ログインしました')\n\t\t\treturn redirect(url_for('entry.show_entries')) # 直接リンク名では無く、ビューに定義しているメソッド名を指定↓したコードが下記。\n\treturn render_template('login.html')\n# 正しい場合には/にリダイレクト、そうで無い場合はrender_template('login.html')のログインフォームを再度表示。\n\n\n@view.route('/logout')\ndef logout():\n\tsession.pop('logged_in', None)\n\tflash('ログアウトしました')\n\treturn redirect(url_for('entry.show_entries')) # 直接リンク名では無く、ビューに定義しているメソッド名を指定↓したコードが下記。\n\n\n@view.app_errorhandler(404) # 存在しないURLにアクセスした時など、404エラーが発生した時に行わせる処理を定義する(Blueprint使用時は\"app_〜\"を使う必要\ndef non_existant_route(error):\n\treturn redirect(url_for('view.login')) # これでログインURLにリダイレクトさせる\n","sub_path":"flask_blog/views/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"109957740","text":"import pymel.core as pm\n\n'''\n Note: this should only be run in Maya\n\n after constructing the object,\n call showDiaglogWindow to show the window\n'''\n\n'''\nThis creates a very simple one message one button dialog.\n\nparams:\ntitle (type string) = windows title\nmessage (type string) = the message to display to the user\ncallback (type function) = the callback to call when the window button is\npressed\n\nwhen the window button is pressed, it will pass in the string input\nof the input field into the callback given by the user\n'''\nclass SimpleDialog():\n def __init__(self, title, message, callback):\n self.inputField = None\n self.windowTitle = title\n self.message = message\n self.diagWindow = None\n self.callback = callback \n \n def constructWindow(self):\n if self.message == None:\n raise Exception('Must be a message to display for a simple dialog')\n if self.callback == None:\n raise Exception('Must be a callback for button to call; set --> SimpleDialog.callback')\n \n self.diagWindow = pm.window(w=330, h=180, title=self.windowTitle)\n pm.rowColumnLayout(nr=5)\n pm.separator(h=30, style='none')\n self.inputField = pm.textFieldGrp(l=self.message, cw=[(1,200), (2,200)], cal=[(1,\"left\"), (2, \"center\")], pht=self.message)\n pm.separator(h=40)\n pm.rowColumnLayout(nr=1)\n pm.setParent('..')\n pm.button(label='Search', command=self.execCallback, h=50, w=150)\n \n \n def showDiaglogWindow(self):\n pm.showWindow(self.diagWindow)\n \n def execCallback(self, *args):\n input = self.inputField.getText()\n self.callback(input)\n","sub_path":"MathTools/CrazyHair/SimpleDialog.py","file_name":"SimpleDialog.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"115616278","text":"#Version 2: some optimization\n\nfrom collections import namedtuple\nfrom datetime import datetime\nfrom math import ceil\n\n\ndef solve_it(input_data):\n # parse the input\n def rescale(x,scale):\n return int(ceil(x / scale))\n \n lines = input_data.split('\\n')\n\n firstLine = lines[0].split()\n item_count = int(firstLine[0])\n capacity = int(firstLine[1])\n scale = 1\n if capacity*item_count > 100000000:\n scale = 13\n\n capacity = capacity // scale\n \n items = []\n\n Item = namedtuple(\"Item\", ['index', 'value', 'weight'])\n for i in range(1, item_count+1):\n line = lines[i]\n parts = line.split()\n items.append(Item(i-1, int(parts[0]), rescale(int(parts[1]),scale)))\n items = sorted(items, key=lambda tup: tup.value, reverse=False)\n \n #function to compute value based on selected\n #takes in the taken objects and the itmes\n #return value of taken items\n def takenValue(taken,items):\n items = sorted(items, key=lambda tup: tup.index, reverse=False)\n value = 0\n for i in range(0,item_count):\n value += taken[i]*items[i].value\n return value\n \n \n #dynamic programming search\n def fillingCol():\n lowest_weight = items[0].weight\n table_value= []\n col_value = [0]*(capacity+1)\n table_value.append(col_value[:])\n for i in range(item_count):\n item = items[i]\n col_value = [0]*(capacity+1)\n value = item.value\n weight = item.weight\n for w in range(lowest_weight,capacity+1):\n if weight > w:\n col_value[w] = table_value[i][w]\n elif value + table_value[i][w-weight] > table_value[i][w]:\n col_value[w] = value + table_value[i][w-weight]\n else:\n col_value[w] = max(value, table_value[i][w])\n table_value.append(col_value[:])\n return table_value\n\n def rollBack(table_value):\n col = item_count\n row = capacity\n used = []\n for i in range(item_count):\n if table_value[col][row] > table_value[col-1][row]:\n used.append(items[col-1].index)\n row -= items[col-1].weight\n col -= 1\n return used\n \n start = datetime.now()\n table_value = fillingCol()\n used = rollBack(table_value)\n end = datetime.now()\n print(\"time:\"+str(end - start))\n print(\"items:\"+str(item_count))\n solution = [0]*item_count\n for index in used:\n solution[index] = 1\n \n perfect = 0\n if scale == 1:\n perfect = 1\n # prepare the solution in the specified output format\n output_data = str(takenValue(solution,items[:])) + ' ' + str(perfect) + '\\n'\n output_data += ' '.join(map(str, solution))\n \n return output_data\n\nimport sys\nif len(sys.argv) > 1:\n if __name__ == '__main__':\n if len(sys.argv) > 1:\n file_location = sys.argv[1].strip()+\"/data\"\n with open(file_location, 'r') as input_data_file:\n input_data = input_data_file.read()\n print(solve_it(input_data))\n else:\n print('This test requires an input file. Please select one from the data directory. (i.e. python solver.py ./data/ks_4_0)')\nelse:\n path = \"C:/Users/Heyyou/Dropbox/Private/Code/Discrete Optimization/Week 2/data/\"\n file_location = path+\"ks_4_0\"\n with open(file_location, 'r') as input_data_file:\n input_data = input_data_file.read()\n print(solve_it(input_data))","sub_path":"Week 2/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":3564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"441523939","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\nfrom bookspider.items import BookspiderItem\nfrom pymongo import MongoClient\n\n#使用MongoDB数据库存储当当网中的图书数据\nclient = MongoClient()\ncollection = client[\"book\"][\"dangdang\"]\n\nclass BookspiderPipeline(object):\n def process_item(self, item, spider):\n if isinstance(item,BookspiderItem):\n collection.insert(dict(item))\n print(item)\n\n\n","sub_path":"pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"396946604","text":"import time\nimport tflite_runtime.interpreter as tflite\nimport numpy as np\n\n\ninterpreter = tflite.Interpreter('/home/pi/tflite/CNN_quan_float_in.tflite')\ninterpreter.allocate_tensors()\n\ninput_details = interpreter.get_input_details()\noutput_details = interpreter.get_output_details()\n\nprint ('---------------------------------------------')\n#print (input_details)\nprint ('---------------------------------------------')\n#print (output_details)\nprint ('---------------------------------------------')\n# Load data\ndata = np.loadtxt(open('/home/pi/tflite/gear_s.csv', 'rb'), delimiter=',', skiprows=0)\nfor i in range(10):\n\ttime.sleep(1)\n\tstart = time.time()\n\tx = data[(500*i):(500*(i+1))].reshape(40, 100)\n\tx = x[np.newaxis, :, :, np.newaxis].astype('float32')\n\t#print ('x: ', x)\n\n\tinterpreter.set_tensor(input_details[0]['index'],x)\n\n\t# Call lite model\n\tinterpreter.invoke()\n\tout = interpreter.get_tensor(output_details[0]['index'])\n\tend = time.time()\n\t\n\t#out = out.tolist()\n\t#predict = out.index(max(out))\n\t#if out >= 0.5:\n\t#\tprint('Bearing condition: Normal')\n\t#if out < 0.5:\n\t#\tprint('Bearing condition: Fault')\n\tprint('Inference time: ', (end - start))\n\t\n","sub_path":"Nasa_bearing_CNN.py","file_name":"Nasa_bearing_CNN.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"418075241","text":"import math\r\nusuario = int (input('Para gerar a tabuada até 10, adicione o valor ao lado: '))\r\ndef tabuada (usuario):\r\n for i in range (0,11):\r\n res = str(usuario * i)\r\n i+=1\r\n print(usuario,\"x\", i , '=', res)\r\n\r\n \r\n\r\ntabuada(usuario)","sub_path":"Python/Aulas/tabuadas_.py","file_name":"tabuadas_.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"176085252","text":"\"\"\"\nCopyright 2016-2017 Daylon Crider\nPlease refer any comments or questions about the program\nand/or code to 'support@dayloncrider.com'.\nAlternatively, you can visit www.dayloncrider.com for\nmore information and means of contact.\n\"\"\"\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nimport urllib.request\nimport os\nimport random\nimport smtplib\n\t\t\ndef check_email(email):\n\t\"\"\"Simple verification of a valid email address\"\"\"\n\tif '@' in email:\n\t\tsend_email(email)\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef send_email(email):\n\t\"\"\"Generates and sends the email\"\"\"\n\t# User credentials\n\tuser = 'email@test.com'\n\tpwd = '******'\n\t# Configure email parts\n\tsender = user\n\treceiver = email\n\tmsg = MIMEMultipart()\n\tmsg['From'] = sender\n\tmsg['To'] = receiver\n\tmsg['Subject'] = 'Dinner Ideas from Menu Helper\\u00A9' \n\t\n\thead = 'Here are some options for the week:\\n\\n'\n\ttail = '\\n\\nIf you have any problems or questions, please send an email to menuhelper@dayloncrider.com'\n\tbody = head + self.display_options.get() + tail\n\tmsg.attach(MIMEText(body, 'plain'))\n\t\n\t# Send the email\n\tserver = smtplib.SMTP_SSL('smtpout.secureserver.net',465)\n\tserver.ehlo()\n\tserver.login(user, pwd)\n\ttext = msg.as_string()\n\tserver.sendmail(sender, receiver, text)\n\tserver.quit()\n","sub_path":"MenuHelper/Email Version/email_handler.py","file_name":"email_handler.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"415631674","text":"import dash_html_components as html\nimport dash_core_components as dcc\n\ndef Header():\n return html.Div([\n get_header(),\n html.Br([]),\n get_menu()\n ])\n\n\ndef get_header():\n header = html.Div([\n\n html.Div([\n html.H5(\n 'Awamo Monthly Report')\n ], className=\"twelve columns padded\")\n\n ], className=\"row gs-header gs-text-header\")\n return header\n\n\ndef get_menu():\n menu = html.Div([\n\n dcc.Link('Overview - First ', href='/downloads/', className=\"tab first\"),\n\n dcc.Link('Overview - GA ', href='/downloads/', className=\"tab\"),\n\n ], className=\"row \")\n return menu\n","sub_path":"components/header.py","file_name":"header.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"286490207","text":"from termcolor import cprint, colored\r\nfrom random import randint\r\n\r\nu = \" \"\r\n\r\ndef pedir_nome(id):\r\n return input(colored(f'Informe o nome do jogador {id}: ', 'yellow'))\r\n\r\n\r\ndef criar_jogador(id):\r\n nome = pedir_nome(id)\r\n return {\r\n 'id': id,\r\n 'nome': nome,\r\n 'pontos': 0,\r\n 'vez': False,\r\n 'token': None\r\n }\r\n\r\n\r\ndef criar_jogadores():\r\n cprint('=-' * 75, 'blue')\r\n player1 = criar_jogador(1)\r\n cprint('=-' * 75, 'blue')\r\n player2 = criar_jogador(2)\r\n cprint('=-' * 75, 'blue')\r\n return player1, player2\r\n\r\n\r\ndef criartabuleiro():\r\n tabuleiro = [\r\n [u, u, u],\r\n [u, u, u],\r\n [u, u, u],\r\n ]\r\n return tabuleiro\r\n\r\n\r\ndef sortear_vez(player1, player2):\r\n players = player1, player2\r\n numero_vez = randint(0,1)\r\n players[numero_vez]['vez'] = True\r\n if player1.get('vez'):\r\n cprint(f'{player1.get(\"nome\")} começa!', 'green')\r\n else:\r\n cprint(f'{player2.get(\"nome\")} começa!', 'green')\r\n return players\r\n\r\n\r\ndef trocar_vez(player1, player2):\r\n if player1['vez']:\r\n player2['vez'] = True\r\n player1['vez'] = False\r\n else:\r\n player2['vez'] = False\r\n player1['vez'] = True\r\n\r\n\r\ndef mostrar_tabuleiro(tabuleiro):\r\n for i in range(3):\r\n cprint((\" | \".join(tabuleiro[i])), 'yellow')\r\n if (i < 2):\r\n cprint(\"-------------\", 'red')\r\n\r\n\r\ndef pedir_jogada(texto):\r\n try:\r\n n = int(input(texto))\r\n if(n >= 1 and n <= 3):\r\n return n - 1\r\n else:\r\n print(\"O número informado precisa estar entre 1 e 3\")\r\n return pedir_jogada(texto)\r\n except:\r\n print(\"Valor informado não é válido\")\r\n return pedir_jogada(texto)\r\n\r\n\r\ndef validacao_da_jogada(tabuleiro, linha, coluna):\r\n if tabuleiro[linha][coluna] == u:\r\n return True\r\n else:\r\n return False\r\n\r\ndef posicionar_token_no_tabuleiro(tabuleiro, linha, coluna, jogadores):\r\n for jogador in jogadores:\r\n if jogador['vez']:\r\n tabuleiro[linha][coluna] = jogador['token']\r\n\r\n\r\n\r\n\r\ndef verificar_vitória(tabuleiro, player1, player2):\r\n\r\n # linhas\r\n for i in range(3):\r\n if (tabuleiro[i][0] == tabuleiro[i][1] and tabuleiro[i][1] == tabuleiro[i][2] and tabuleiro[i][0] == 'X'):\r\n player1['pontos'] += 1\r\n return tabuleiro[i][0]\r\n\r\n # coluna\r\n for i in range(3):\r\n if (tabuleiro[0][i] == tabuleiro[1][i] and tabuleiro[1][i] == tabuleiro[2][i] and tabuleiro[0][i] == 'X'):\r\n player1['pontos'] += 1\r\n return tabuleiro[0][i]\r\n\r\n\r\n # diagonal principal\r\n if (tabuleiro[0][0] == 'X' and tabuleiro[0][0] == tabuleiro[1][1] and tabuleiro[1][1] == tabuleiro[2][2]):\r\n player1['pontos'] += 1\r\n return tabuleiro[0][0]\r\n\r\n # diagonal secundaria\r\n if (tabuleiro[0][2] == 'X' and tabuleiro[0][2] == tabuleiro[1][1] and tabuleiro[1][1] == tabuleiro[2][0]):\r\n player1['pontos'] += 1\r\n return tabuleiro[0][2]\r\n\r\n #Jogador 2\r\n\r\n # linhas\r\n for i in range(3):\r\n if (tabuleiro[i][0] == tabuleiro[i][1] and tabuleiro[i][1] == tabuleiro[i][2] and tabuleiro[i][0] == 'O'):\r\n player2['pontos'] += 1\r\n return tabuleiro[i][0]\r\n\r\n\r\n # coluna\r\n for i in range(3):\r\n if (tabuleiro[0][i] == tabuleiro[1][i] and tabuleiro[1][i] == tabuleiro[2][i] and tabuleiro[0][i] == 'O'):\r\n player2['pontos'] += 1\r\n return tabuleiro[0][i]\r\n\r\n\r\n # diagonal principal\r\n if (tabuleiro[0][0] == 'O' and tabuleiro[0][0] == tabuleiro[1][1] and tabuleiro[1][1] == tabuleiro[2][2]):\r\n player2['pontos'] += 1\r\n return tabuleiro[0][0]\r\n\r\n # diagonal secundaria\r\n if (tabuleiro[0][2] == 'O' and tabuleiro[0][2] == tabuleiro[1][1] and tabuleiro[1][1] == tabuleiro[2][0]):\r\n player2['pontos'] += 1\r\n return tabuleiro[0][2]\r\n\r\n\r\n for i in range(3):\r\n for j in range(3):\r\n if (tabuleiro[i][j] == u):\r\n return False\r\n\r\n return \"EMPATE\"\r\n\r\ndef mostrar_vez(player1, player2):\r\n if player1.get('vez'):\r\n cprint(f'Vez de {player1.get(\"nome\")}', 'green')\r\n else:\r\n cprint(f'Vez de {player2.get(\"nome\")}', 'green')\r\n\r\nplayer1 = None\r\nplayer2 = None\r\n\r\ndef anunciar_vencedor(player1, player2):\r\n if player1['pontos'] != 0:\r\n cprint('=-' * 75, 'blue')\r\n cprint(f'{player1[\"nome\"]} VENCEU!', 'green')\r\n cprint('=-' * 75, 'blue')\r\n if player2['pontos'] != 0:\r\n cprint('=-' * 75, 'blue')\r\n cprint(f'{player2[\"nome\"]} VENCEU!', 'green')\r\n cprint('=-' * 75, 'blue')\r\n if player2['pontos'] == 0 and player1['pontos'] == 0:\r\n cprint('=-' * 75, 'blue')\r\n cprint('DEU EMPATE!')\r\n cprint('=-' * 75, 'blue')\r\ndef rodar_game():\r\n tabuleiro = criartabuleiro()\r\n player1, player2 = criar_jogadores()\r\n player1['token'] = \"X\"\r\n player2['token'] = \"O\"\r\n verificar_vitória(tabuleiro, player1, player2)\r\n sortear_vez(player1, player2)\r\n while not verificar_vitória(tabuleiro, player1, player2):\r\n mostrar_tabuleiro(tabuleiro)\r\n mostrar_vez(player1, player2)\r\n linha = pedir_jogada('Informe o valor da linha: ')\r\n coluna = pedir_jogada('Informe o valor da coluna: ')\r\n if validacao_da_jogada(tabuleiro, linha, coluna):\r\n posicionar_token_no_tabuleiro(tabuleiro, linha, coluna, (player1, player2))\r\n trocar_vez(player1, player2)\r\n anunciar_vencedor(player1, player2)\r\n mostrar_tabuleiro(tabuleiro)\r\n\r\nrodar_game()\r\n\r\n\r\n\r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"396147245","text":"import sys\n\ndef Hello(name):\n if name == 'Alice' or name == 'Nick':\n name = name + '???'\n else:\n name = name + '!!!!'\n print ('Hello', name)\n\n\n# Defining function\ndef main():\n Hello(sys.argv[1])\n\n# Boilerplate code to run the function \nif __name__ == '__main__':\n main()\n\n","sub_path":"samCmdProgram.py","file_name":"samCmdProgram.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"445618225","text":"from flask import Flask, jsonify, request\n# import nltk\nfrom waitress import serve\n\n# import paddlehub as hub\nfrom senta import Senta\n\n# senta = hub.Module(name=\"senta_bilstm\")\nsenta = Senta()\nuse_cuda = False\n\napp = Flask(__name__)\napp.config.from_object('configure')\n\n\ndef init_server():\n global senta, use_cuda # 要修改全局变量的话,需要保留这句\n senta.init_model(model_class=\"ernie_1.0_skep_large_ch\",\n task=\"sentiment_classify\",\n use_cuda=use_cuda)\n\n\n@app.route('/')\ndef hello_world():\n return 'Nobody Likes Problem'\n\n\n@app.route('/query_server', methods=['POST'])\ndef query_server():\n if request.method == 'POST':\n source = request.form['source']\n\n # jsentences = nltk.sent_tokenize(source)\n # jtokens = [nltk.word_tokenize(jsentence) for jsentence in jsentences]\n\n result = senta.predict(source)\n print('result', result)\n jsana = '未知'\n\n if result[0][1] == 'positive':\n jsana = '积极'\n elif result[0][1] == 'negative':\n jsana = '消极'\n\n return jsonify({'jserver': jsana})\n return jsonify({'jserver': ''})\n\n\nif __name__ == \"__main__\":\n init_server()\n # app.run(host='0.0.0.0', port=2339, debug=False)\n serve(app, host=\"0.0.0.0\", port=2339) # 请在2335~2400之间选择一个端口\n","sub_path":"nlp/applicaitons/sana/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"468775070","text":"import sys, StringIO\n\n\n#this will flip all pancakes until the last pancape is 0 and the current is 1.\ndef flip(pancake):\n i = 1\n while i1:\n input = file(sys.argv[1])\n else:\n input = StringIO.StringIO(\"\"\"5\n-\n-+\n+-\n+++\n--+-\"\"\")\n cases = int(input.readline())\n for case in range(cases):\n p = [x=='+' and 1 or 0 for x in input.readline().strip()]\n print(\"Case #%d: %s\" % (case+1, solve(p)))\n","sub_path":"codes/CodeJamCrawler/16_0_2_neat/16_0_2_Wingi_qb.py","file_name":"16_0_2_Wingi_qb.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"241967657","text":"\nimport numpy as np\n\n\nclass FadingFilter:\n '''\n Implement a fading filter of the first and second order. \n input: \n -`filter_memory`: float (0, 1), memory factor of the filter. \n -`sample_time`: sample time of the input signal. \n '''\n\n def __init__(self, filter_memory: float, sample_time: float):\n self.homography_old = np.zeros([3, 3])\n self.Dhomography_old = np.zeros([3, 3])\n self.beta = filter_memory\n self.Ts = sample_time\n\n def I_order_ff(self, homography):\n '''\n First order fading filter:\n x_{n} = x_{n-1} + (1 - filter_memory) * (x_{new} - x_{n-1})\n '''\n # filter\n H_dif = homography - self.homography_old\n gain = 1 - self.beta\n homography_filtered = self.homography_old + (gain * H_dif)\n # update filter homography, old step value\n self.homography_old = homography_filtered\n return homography_filtered\n\n def II_order_ff(self, homography):\n '''\n Second order fading filter: \n model prediction: \n p = x_{n-1} + (dx_{n-1} * Ts) \n error between measure and prediction: \n x_dif = x_{new} - p \n Filter:\n x_{n} = p + (1 - filter_memory^2) * x_dif \n dx_{n} = dx_{n-1} + [(1 - filter_memory)^2 / Ts] * x_dif \n\n '''\n # filter\n gain = 1 - np.power(self.beta, 2)\n Dgain = np.power((1 - self.beta), 2) / self.Ts\n # model prediction\n prediction = self.homography_old + (self.Dhomography_old * self.Ts)\n H_dif = homography - prediction\n homography_filtered = prediction + (gain * H_dif)\n Dhomography_filtered = self.Dhomography_old + (Dgain * H_dif)\n # update filter homography, old step value\n self.homography_old = homography_filtered\n self.Dhomography_old = Dhomography_filtered\n return homography_filtered\n","sub_path":"src/filter_simple.py","file_name":"filter_simple.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"119270209","text":"import requests\n\nclass Provider(object):\n def get(self, book_title, *args, **kwargs):\n return {}\n\nclass Adapter(object):\n @staticmethod\n def _build_good_reads_opinion(review):\n result = {}\n return result\n\n @staticmethod\n def to_model(results, *args, **kwargs):\n model = {\n 'provider': 'good_reads',\n 'opinions': []\n }\n if 'reviews' in results:\n for review in results[\"reviews\"]:\n model['opinions'].append(Adapter._build_good_reads_opinion(review))\n return model","sub_path":"plugins/goodreads/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"109299948","text":"import sys\ndir_map = {'DIAG_LEFT_DOWN': (1, -1), 'RIGHT': (0, 1), 'DIAG_RIGHT_DOWN': (1, 1), 'UP': (-1, 0), 'DOWN': (1, 0), 'DIAG_RIGHT_UP': (-1, 1), 'DIAG_LEFT_UP': (-1, -1), 'LEFT': (0, -1)}\ndir_map_colors = {'DIAG_LEFT_DOWN': 'fuchsia', 'RIGHT': 'greenyellow', 'DIAG_RIGHT_DOWN': 'yellow', 'UP': 'pink', 'DOWN': 'LightCoral', 'DIAG_RIGHT_UP': 'lightgray', 'DIAG_LEFT_UP': 'red', 'LEFT': 'skyblue'}\n\ndir_map_colors_full = {'DIAGONAL LEFT DOWN': 'fuchsia', 'RIGHT': 'greenyellow', 'DIAGONAL RIGHT DOWN': 'yellow', 'UP': 'pink', 'DOWN': 'LightCoral', 'DIAGONAL RIGHT UP': 'lightgray', 'DIAGONAL LEFT UP': 'red', 'LEFT': 'skyblue'}\n\ndef build_frequency_table(word_maze):\n\tfreq_table = {}\n\tfor row_index, row in enumerate(word_maze):\n\t\tfor col_index, col in enumerate(row):\n\t\t\tif col not in freq_table:\n\t\t\t\tfreq_table[col] = {'count' : 1, 'positions' : [(row_index, col_index)]}\n\t\t\telse:\n\t\t\t\tfreq_table[col]['count'] += 1\n\t\t\t\tfreq_table[col]['positions'].append((row_index, col_index))\n\treturn freq_table\n\ndef get_maze_from_file(filename):\n\twith open(filename) as input_file:\n\t\tfile_contents = input_file.readlines()\n\t\tfile_contents = [x.strip() for x in file_contents]\n\t\tword_maze = []\n\t\tfor each in file_contents:\n\t\t\trow = each.split()\n\t\t\tword_maze.append(row)\n\t\tSIZE = len(word_maze[0])\n\t\treturn word_maze\n\ndef get_words_to_find_from_file(filename):\n\twith open(filename) as input_file:\n\t\tfile_contents = input_file.readlines()\n\t\twords_to_find = [x.strip() for x in file_contents]\n\t\treturn words_to_find\n\ndef grid_solver_impl(word_maze, word_to_find, start_position, solve_backwards):\n\tmax_cols, max_rows = len(word_maze[0]), len(word_maze)\n\tif solve_backwards == True:\n\t\tword_to_find = word_to_find[::-1]\n\tletter = word_to_find[0]\n\tlength_of_word = len(word_to_find) - 1\n\tfor direction in dir_map:\n\t\tdir_offsets = dir_map[direction]\n\t\trow_offset, col_offset = dir_offsets[0], dir_offsets[1]\n\t\tcur_row, cur_col = start_position[0], start_position[1]\n\t\tfor l_index, letter in enumerate(word_to_find):\n\t\t\tif (0 <= cur_col < max_cols) and (0 <= cur_row < max_rows):\n\t\t\t\tif letter == word_maze[cur_row][cur_col]:\n\t\t\t\t\tif l_index == length_of_word:\n\t\t\t\t\t\treturn True, direction\n\t\t\t\t\tcur_row = cur_row + row_offset\n\t\t\t\t\tcur_col = cur_col + col_offset\n\t\t\t\telse:\n\t\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tbreak\n\treturn False, 'NONE'\n\ndef grid_solver(word_maze, word_list, freq_table):\n\tword_answers = {}\n\twords_not_found = word_list[:]\n\tfor word_to_find in word_list:\n\t\tsolve_backwards = False\n\t\tstart_letter = word_to_find[0]\n\t\tend_letter = word_to_find[-1]\n\t\tif start_letter in freq_table and end_letter in freq_table:\n\t\t\tif freq_table[start_letter]['count'] > freq_table[end_letter]['count']:\n\t\t\t\tletter = end_letter\n\t\t\t\tsolve_backwards = True\n\t\t\telse:\n\t\t\t\tletter = start_letter\n\t\telse:\n\t\t\tcontinue\n\t\tpositions = freq_table[start_letter]['positions']\n\n\t\tfor each_position in positions:\n\t\t\tfound, direction = grid_solver_impl(word_maze, word_to_find, each_position, False)\n\t\t\tif found == True:\n\t\t\t\twords_not_found.remove(word_to_find)\n\t\t\t\tword_to_find = word_to_find.encode('ascii', 'ignore')\n\t\t\t\tword_answers[word_to_find] = { \n\t\t\t\t\t'word' : word_to_find,\n\t\t\t\t\t'row_position': each_position[0],\n\t\t\t\t\t'col_position': each_position[1],\n\t\t\t\t\t'direction' : direction,\n\t\t\t\t\t'length' : len(word_to_find),\n\t\t\t\t\t'letters' : list(word_to_find)\n\t\t\t\t\t}\n\t\t\t\tbreak\n\n\treturn words_not_found, word_answers\n\ndef construct_new_maze(word_maze, word_answers):\n\tanswer_list = []\n\tanswer_dict = {}\n\n\tfor each_word in word_maze:\n\t\tanswer_row = []\n\t\tfor each_letter in each_word:\n\t\t\tanswer_dict = {\n\t\t\t\t'letter' : each_letter,\n\t\t\t\t'color' : 'white'\n\t\t\t}\n\t\t\tanswer_row.append(answer_dict)\n\t\tanswer_list.append(answer_row)\n\n\n\tfor each_answer, each_answer_dict in word_answers.items():\n\t\trow = each_answer_dict['row_position']\n\t\tcol = each_answer_dict['col_position']\n\t\tdirection = each_answer_dict['direction']\n\t\tdirection_offsets = dir_map[direction]\n\t\tcolor = dir_map_colors[direction]\n\t\tlength = each_answer_dict['length']\n\t\trow_offset, col_offset = direction_offsets[0], direction_offsets[1]\n\t\tanswer_dict = answer_list[row][col]\n\t\t\n\t\tanswer_list[row][col]['color'] = color\n\n\t\t#color in the direction for as long as length\n\t\tfor i in range(0, length-1): #BUG: This is for sure a bug\n\t\t\trow = row + row_offset\n\t\t\tcol = col + col_offset\n\t\t\tanswer_list[row][col]['color'] = color\n\t\teach_answer_dict = answer_dict\n\n\treturn answer_list\n\ndef start(word_maze, word_list):\n\t#word_maze = get_maze_from_file('new_maze.txt')\n\t#word_list = get_words_to_find_from_file('new_words.txt')\n\tnew_word_maze = []\n\tfor each in word_maze:\n\t\teach = [x.upper() for x in each]\n\t\tnew_word_maze.append(each)\n\tword_maze = new_word_maze\n\tword_list = [x.upper() for x in word_list]\n\tfreq_table = build_frequency_table(word_maze)\n\twords_not_found, word_answers = grid_solver(word_maze, word_list, freq_table)\n\tnew_maze = construct_new_maze(word_maze, word_answers)\n\treturn words_not_found, word_answers, new_maze, dir_map_colors_full\n\n\n#start(None, None)\n","sub_path":"hunter.py","file_name":"hunter.py","file_ext":"py","file_size_in_byte":4980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"185785920","text":"import matplotlib.pyplot as plt\nimport cv2\n\n\ndef visualize(image, mask, original_image=None, original_mask=None):\n fontsize = 18\n\n if original_image is None and original_mask is None:\n f, ax = plt.subplots(2, 1, figsize=(12, 12))\n\n ax[0].imshow(image)\n ax[1].imshow(mask)\n print(mask.sum())\n else:\n f, ax = plt.subplots(2, 2, figsize=(12, 12))\n\n ax[0, 0].imshow(original_image)\n ax[0, 0].set_title('Original image', fontsize=fontsize)\n\n ax[1, 0].imshow(original_mask)\n ax[1, 0].set_title('Original mask', fontsize=fontsize)\n\n ax[0, 1].imshow(image)\n ax[0, 1].set_title('Transformed image', fontsize=fontsize)\n\n ax[1, 1].imshow(mask)\n ax[1, 1].set_title('Transformed mask', fontsize=fontsize)\n #print(mask.sum())\n \n \ndef plot_data(img,points,fig_size=(18,12)):\n p_img = img.copy()\n fig, ax = plt.subplots(1, 1, figsize=fig_size)\n for point in points:\n cv2.circle(p_img, tuple(point), radius=0,color=(0, 1, 0), thickness=5)\n ax.imshow(p_img)","sub_path":"nbs/utilis.py","file_name":"utilis.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"3507846","text":"'''\nData App - Previsão do Valor do Imóvel\nPara executar digite: streamlit run App_Previsao_do_Valor_do_Imovel.py\n'''\n\nimport streamlit as st \nimport pandas as pd\nimport plotly.express as px\nfrom sklearn.ensemble import RandomForestRegressor\n\n# Função para carregar o dataset\n@st.cache\ndef get_data():\n return pd.read_csv(\"data.csv\")\n\n# Função para treinar o modelo\ndef train_model():\n data = get_data()\n # Separa os dados\n x = data.drop(\"MEDV\", axis = 1)\n y = data[\"MEDV\"]\n # Instancia o RandomForestRegressor passando alguns parâmetros\n rf_regressor = RandomForestRegressor(n_estimators = 200, max_depth = 7, max_features = 3)\n # Treina o modelo\n rf_regressor.fit(x, y)\n # Retorna o classificador\n return rf_regressor\n\n# Cria um DataFrame\ndata = get_data()\n\n# Treina o modelo\nmodel = train_model()\n\n# Título\nst.title(\"Data App - Previsão do Valor do Imóvel\")\n\n# Subtítulo\nst.markdown(\"Este Data App exibe a solução de Machine Learning na predição de valores de imóveis da cidade de Boston\")\n\n# Verifica o dataset\nst.subheader(\"Mostrando apenas um pequeno conjunto dos atributos\")\n\n# Atributos para serem exibidos por padrão\ndefaultcols = [\"RM\", \"PTRATIO\", \"LSTAT\", \"MEDV\"]\n\n# Define atributos a partir do multiselect e exibe na tela aqueles em 'default'\ncols = st.multiselect(\"Atributos\", data.columns.tolist(), default = defaultcols)\n\n# Exibe os top 10 registros do DataFrame\nst.dataframe(data[cols].head(10))\n\nst.subheader(\"Distribuição de imóveis por preço na escala de US$ 1000\")\n\n# Define a faixa de valores\nfaixa_valores = st.slider(\"Faixa de preço\", float(data.MEDV.min()), 50., (10., 40.))\n\n# Filtra os dados\ndados = data[data['MEDV'].between(left = faixa_valores[0], right = faixa_valores[1])]\n\n# Plota a distribuição dos dados com filtragem dinâmica\nf = px.histogram(dados, x = \"MEDV\", nbins = 50, title = \"Distribuição de Preços\")\nf.update_xaxes(title = \"MEDV (US$ 1000)\")\nf.update_yaxes(title = \"Total Imóveis\")\nst.plotly_chart(f)\n\nst.sidebar.subheader(\"Defina os atributos do imóvel para predição\")\n\n# Mapea dados do usuário para cada atributo\ncrim = st.sidebar.number_input(\"Taxa de criminalidade\", value = data.CRIM.mean())\nindus = st.sidebar.number_input(\"Proporção de hectares de negócio\", value = data.CRIM.mean())\nchas = st.sidebar.selectbox(\"Faz limite com o rio?\", (\"Sim\", \"Não\"))\n# Transforma o dado de entrada em valor binário\nchas = 1 if chas == \"Sim\" else 0\nnox = st.sidebar.number_input(\"Concentração de óxido nítrico\", value = data.NOX.mean())\nrm = st.sidebar.number_input(\"Número de quartos\", value = 1)\nptratio = st.sidebar.number_input(\"Índice de alunos para professores\", value = data.PTRATIO.mean())\nb = st.sidebar.number_input(\"Proporção de pessoas com descendencia afro-americana\", value = data.B.mean())\nlstat = st.sidebar.number_input(\"Porcentagem de status baixo\", value = data.LSTAT.mean())\n\n# Insere um botão na tela\nbtn_predict = st.sidebar.button(\"Realizar predição\")\n\n# Verifica se o botão for acionado\nif btn_predict:\n result = model.predict([[crim, indus, chas, nox, rm, ptratio, b, lstat]])\n st.subheader(\"O valor previsto para o imóvel é:\")\n result = \"US $ \" + str(round(result[0]*1000, 2))\n st.write(result)\n","sub_path":"App_Previsao_do_Valor_do_Imovel.py","file_name":"App_Previsao_do_Valor_do_Imovel.py","file_ext":"py","file_size_in_byte":3254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"578296567","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jun 2 18:11:09 2019\r\n\r\n@author: Deepti.Venugopal\r\n\"\"\"\r\n\r\n'''Create Generators--yield'''\r\n\r\ndef create_cubes(n):\r\n result = []\r\n for x in range(n):\r\n result.append(x**3)\r\n return result\r\n\r\nprint(create_cubes(10))\r\n\r\nfor x in create_cubes(10):\r\n print( x )\r\n\r\n'''It is not necessary to store the list in the memory to get the numbers one by one, instead with the previous number\r\ncan get the next number. Can use \"yield\" keyword'''\r\n\r\ndef create_cubes(n):\r\n \r\n for x in range(n):\r\n yield x**3 \r\n \r\n#In this case, the numbers will not be shown as it is not in the memory as it is a generator object now.\r\n#Below will not print numbers\r\nprint(create_cubes(10)) \r\n\r\n#So to print the value, you need to iterate through the object\r\nfor x in create_cubes(10):\r\n print(x)\r\n\r\n'''Fibonacci Series'''\r\ndef gen_fibon(n):\r\n a = 1\r\n b = 1\r\n for i in range(n):\r\n yield a\r\n a,b = b,a+b\r\n\r\nfor num in gen_fibon(10):\r\n print(num)\r\n\r\n'''Another -- next---'''\r\ndef simple_gen():\r\n for x in range(3):\r\n yield x\r\n\r\nfor number in simple_gen():\r\n print(number)\r\n\r\ng = simple_gen()\r\n\r\nprint(next(g))\r\n\r\n'''iter()---'''\r\ns = 'hello'\r\n\r\nfor letter in s:\r\n print(letter)\r\n\r\n#In the above case we cant use next function to iterate like in previous object\r\nnext(s)\r\n\r\n#convert the string s into iterate object\r\ns_iter = iter(s)\r\nnext(s_iter)\r\n\r\n'''Homework assignment'''\r\n'''Generate square of numbers until a number'''\r\ndef square_gen(n):\r\n for num in range(n):\r\n yield num**2\r\n\r\nfor n in square_gen(10):\r\n print(n)\r\n\r\n'''generate random number using yield'''\r\nimport random \r\nprint(random.randint(1,10))\r\n\r\ndef gen_rand(low,high,n):\r\n for i in range(n):\r\n yield random.randint(low,high)\r\n \r\nfor num in gen_rand(1,10,12):\r\n print(num)\r\n\r\n'''gencomp???'''\r\n'''gencomp - Generator Comprehension'''\r\nmy_list = [1,2,3,4,5]\r\n\r\ngencomp = (item for item in my_list if item > 3)\r\n\r\nprint(gencomp)\r\n\r\nfor num in gencomp:\r\n print(num)","sub_path":"Generators.py","file_name":"Generators.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"266786282","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Sep 6 07:20:33 2019\r\n\r\n@author: Imam Ahasan\r\n\"\"\"\r\n\r\nli = []\r\nT = int(input())\r\n\r\nfor i in range(T):\r\n first_input = input()\r\n second_input = input()\r\n \r\n c = first_input.count(second_input)\r\n\r\n p = \"Occurrence of \\'{}\\' in \\'{}\\' = {}\".format(second_input, first_input, c)\r\n \r\n p2 = \"\\'{}\\' is not present\".format(second_input)\r\n \r\n if c != 0:\r\n li.append(p)\r\n else:\r\n li.append(p2)\r\n \r\n for j in li:\r\n print(j)\r\n ","sub_path":"OOP_and_Other/problem-14_৫২ সমস্যা বই.py","file_name":"problem-14_৫২ সমস্যা বই.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"441588784","text":"import pymysql.cursors\nfrom datetime import date\nimport plotly.graph_objects as go\nimport plotly.express as px\nimport pandas as pd\n\nconnection = pymysql.connect(host='192.168.0.37',\n user='root',\n password='12345',\n db='testbase',\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor)\n\nfig = go.Figure()\n\ntry:\n with connection.cursor() as cursor:\n\n sql_circle = \"select category.name, count(petition.no) from category inner join petition on category.code = petition.code where subdate = (select subdate from petition order by subdate desc limit 1) group by category.name\"\n cursor.execute(sql_circle)\n circle=cursor.fetchall()\n\n\n df = pd.DataFrame(circle)\n df.rename(columns={'name' : '카테고리', 'count(petition.no)' : '글 수'}, inplace=True)\n fig = px.pie(df, values='글 수', names='카테고리')\n fig.update_traces(textposition='inside' , textinfo='percent+label')\n #상세페이지용 범례있는 그래프\n pie_json = fig.to_json()\n fig.show()\n\n\n fig.update(layout_showlegend=False)\n #메인용 범례없는 그래프\n main_pie = fig.to_json()\n fig.show()\n\n\n\n\nfinally:\n connection.close()","sub_path":"keywords/day_pie_graph.py","file_name":"day_pie_graph.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"175404030","text":"# -*- coding: utf-8 -*-\n\"\"\"\nOriginally created on Tue Feb 17 2015\nThis script has been repurposed to provide summary counts from class files. May 2020\n\nThis script will grab the biovolume feature data from extracted feature files \nfor all images in an automated class file.\nCan bin data by category or leave each image separate.\n@author: Darren Henrichs\n\"\"\"\n\n# script to extract the biovolume estimates from IFCB V2 feature files\n# and sum them per category for class files\n# this will read a directory of class files and search the feature path for\n# those files, pulling the biovolume from them\n\n# 06/13/2017 DWH\n# this script is a modified version of the biovolume grabber script\n# this script will take the biovolume value for each cell, convert it to\n# units of carbon following formulas from Menden_Deuer and Lessard 2000\n# then sum the total carbon per category\n\nfrom scipy.io import loadmat\nimport os\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\n\n__author__ = 'dhenrichs'\n\n# path to the feature files\n#feature_path = '/data4/processed_data/extracted_features/2014/'\n#feature_path = '/data4/Cruise_data/HRR_cruise/processed_data/extracted_features/'\n\n# path to the class files for binning the biovolumes into categories\n#class_path = '/data4/manual_classify_results/temp_alyssa_manual/' #processed_data/class_files/2014/'\n#class_path = '/data4/Cruise_data/HRR_cruise/manual_corrections_cruise_data_31Jan2019/'\n#class_path = '/data4/Cruise_data/HRR_cruise/class_files_cruise_data_CNN/'\n\n# path to where the outfiles with biovolume will be located\n#outpath = '/data4/test_biovolume/'\n\n# limit files to one particular month/day IMPORTANT: if you don't want to limit the date, just put None\ndate_limiter = None # a string (e.g. 'D20170404') or None (you literally have to type None)\n\n#are you using automated class files or manually corrected mat files?\n#automated_or_manual = 'automated' #can be 'automated' or 'manual'\n\n#are these CNN results\n#CNN = True\n\n\ndef grab_biovolume(in_feature, in_class, automated):\n '''this function is designed to return the total sum of carbon per category.\n this will NOT return the carbon for each image'''\n feature_data = load_feature_file(in_feature)\n if automated == 'automated':\n feature_data['Biovolume'] = convert_biovolume_pixels_to_microns(feature_data['Biovolume'])\n category_list, class_data = load_class_file_automated(in_class)\n if 'unclassified' not in category_list:\n category_list.append('unclassified')\n outdata = pd.DataFrame([0]*len(category_list), index=category_list, columns=['Biovolume']).T\n for image_cat, feat_size in zip(class_data, feature_data['Biovolume']):\n carbon_value = calculate_carbon_from_biovolume(feat_size, image_cat)\n outdata[image_cat] += carbon_value\n return outdata.T\n \n elif automated == 'manual':\n category_list, class_data, roinums = load_class_file_manual(in_class)\n converted_data = pd.DataFrame(index=roinums)\n converted_data['Category'] = class_data\n converted_data = converted_data.dropna()\n b = list(map(lambda x: category_list[int(x-1)], converted_data['Category']))\n converted_data['Category'] = b\n outdata = pd.DataFrame([0.]*len(category_list), index=category_list, columns=['Biovolume'])\n converted_data['Biovolume'] = convert_biovolume_pixels_to_microns(feature_data['Biovolume'])\n skipped_imgs = 0\n for image_cat, feat_size in zip(class_data, converted_data['Biovolume']):\n try:\n #if not np.isnan(image_cat):\n carbon_value = calculate_carbon_from_biovolume(feat_size, category_list[int(image_cat)])\n outdata.T[category_list[int(image_cat)-1]] += carbon_value\n #print \"after\", outdata.T[category_list[int(image_cat)-1]]\n #print 'CARBON:',carbon_value\n #print 'FEAT_SIZE:', feat_size\n except:\n #print 'Error occurred, skipping image:', image_cat\n skipped_imgs += 1\n #raise\n print('skipped_images:', skipped_imgs, end = ' ') \n \n #now get the image counts for the categories\n counts = {cat:class_data.count(cat) for cat in sorted(category_list)}\n \n return outdata, counts\n #else:\n # return None\n\ndef grab_class_counts(in_class, automated, main_category_list=None):\n \n if automated == 'automated':\n category_list, class_data = load_class_file_automated(in_class)\n else:\n category_list, class_data, roinums = load_class_file_manual(in_class)\n \n #now get the image counts for the categories\n if main_category_list:\n counts = {cat:class_data.count(cat) for cat in main_category_list}\n else:\n counts = {cat:class_data.count(cat) for cat in category_list}\n return counts\n \ndef convert_biovolume_pixels_to_microns(in_value):\n '''The biovolume values given from the IFCB data processing\n are in pixel units. Need to convert pixels to microns.\n Will use a calculated value from a beads file.'''\n conversion = 0.2 #this is the number of microns per pixel; this value calculated from 6um beads on IFCB130\n new_value = in_value * (conversion**2) #this assumes the incoming value is biovolume \n return new_value\n\ndef calculate_carbon_from_biovolume(invalue, category):\n \"\"\"Calculate the cellular carbon from the given biovolume value based on \n what category the image is assigned and how large it is. Conversion \n formulas are from Table 4 in Menden-Deuer and Lessard (2000).\n \n inputs:\n invalue (float) = the biovolume value from the features file converted to microns\n\n category (str) = the category to which the image was assigned \n \n returns:\n carbon_value (float) = the carbon calculated from the formulas\n \"\"\"\n diatoms = ['Asterionellopsis', 'Centric', 'Ch_simplex', 'Chaetoceros', 'Corethron', 'Cylindrotheca',\n 'Cymatosira', 'DactFragCeratul', 'Ditlyum', 'Eucampia', 'Eucampiacornuta', 'Guinardia',\n 'Hemiaulus', 'Leptocylindrus', 'Licmophora', 'Melosira', 'Odontella', 'Pleurosigma', 'Pseudonitzschia',\n 'Rhizosolenia', 'Skeletonema', 'Thalassionema', 'Thalassiosira', 'centric10', 'pennate', ]\n\n if category in diatoms:\n if invalue > 3000.: # diatoms > 3000 cubic microns (um**3)\n carbon_value = (10**(-0.933)) * (invalue ** 0.881)\n else:\n carbon_value = (10**(-0.541)) * (invalue ** 0.811)\n else:\n if invalue < 3000.: # protist plankton < 3000 cubic microns (um**3)\n carbon_value = (10**(-0.583)) * (invalue ** 0.860)\n else:\n carbon_value = (10**(-0.665)) * (invalue ** 0.939)\n\n return carbon_value\n\n\ndef load_class_file_automated(in_class):\n \"\"\"Load the automated classifier results and list of class names.\n Returns:\n category_list = list of category names\n class_data = list classifications for each roi image\n \"\"\"\n f = loadmat(class_path + in_class)\n category_list = f['class2useTB']\n class_data = f['TBclass_above_threshold'] #use this line for automated classifier results; can be 'TBclass_above_optthresh' if available\n \n if CNN:\n class_data = [category[0] for category in class_data[0]] #un-nest the MATLAB stuff #use this line for automated classifier results\n category_list = [category[0] for category in category_list[0]]\n else: #deal with the Python to MATLAB weirdness\n class_data = [category[0][0] for category in class_data] #un-nest the MATLAB stuff #use this line for automated classifier results\n category_list = [category[0][0] for category in category_list] #un-nest the MATLAB stuff\n return category_list, class_data\n\n\ndef load_class_file_manual(in_class):\n \"\"\"Load the manually classified results and list of class names.\n Returns:\n category_list = list of category names\n class_data = list classifications for each roi image\n roinums = list of roi numbers \n \"\"\"\n #the structure of the mat file variable with the classes is slightly different in manual files\n #classlist is a table of shape (num_rois x 3) with the columns being: roinum, manual category, automated category\n f = loadmat(class_path + in_class)\n roinums = None\n class_data_manual = f['classlist']\n class_data = f['classlist'][:,2]\n roinums = f['classlist'][:,0]\n for index, value in enumerate(class_data):\n if not np.isnan(class_data_manual[index, 1]):\n class_data[index] = class_data_manual[index,1]\n category_list = f['class2use_manual']\n try:\n category_list = [category[0] for category in category_list[0]] #this works with some of the files\n except:\n category_list = [category[0] if len(category) > 0 else '' for category in category_list[0]] #this works with the others\n return category_list, class_data, roinums\n\n\ndef load_feature_file(in_feature):\n f = pd.read_csv(feature_path + in_feature, index_col=0)\n return f\n\n\nif __name__ == '__main__':\n \n #read in config file\n with open('./IFCB_summary.cfg') as f:\n \n config_in = {line[:-1].replace(' ', '').split('=')[0]: line[:-1].replace(' ', '').split('=')[1] \n for line in f if len(line) > 1 if line[0] != '#'}\n\n feature_path = config_in['path_to_features']\n class_path = config_in['path_to_class_files']\n outpath = config_in['path_to_place_output_files']\n automated_or_manual = config_in['automated_or_manual']\n \n #have to convert the string into a boolean\n if config_in['CNN'] == 'True':\n CNN = True\n else:\n CNN = False\n \n if feature_path[-1] != '/':\n feature_path += '/'\n \n if class_path[-1] != '/':\n class_path += '/'\n \n if outpath[-1] != '/':\n outpath += '/'\n \n \n # grab the list of files from each directory\n list_of_feature_files = os.listdir(feature_path)\n list_of_class_files = os.listdir(class_path)\n print(\"Feature files: {}\".format(len(list_of_feature_files)))\n print(\"Class files : {}\".format(len(list_of_class_files)))\n \n #create the output dataframe for counts summary\n #first get the category list\n \n \n temp = grab_class_counts(list_of_class_files[0], automated_or_manual)\n category_list = sorted(temp.keys())\n #now use the index from the first class file year to start the master list of counts\n all_counts = pd.DataFrame(index=category_list)\n all_biovolumes = pd.DataFrame(index=category_list)\n \n # start working through the class files individually\n for class_index, indiv_file in enumerate(list_of_class_files):\n if indiv_file[-3:] == 'mat':\n if not date_limiter or date_limiter == indiv_file[:len(date_limiter)]:\n print(\"Processing {}...\".format(indiv_file), end=' ')\n \n features_found = True\n # try:\n if 1:\n feature_index = 0\n while list_of_feature_files[feature_index][:21] != indiv_file[:21]:\n feature_index += 1\n if feature_index >= len(list_of_feature_files)-1:\n #raise ValueError(\"The feature file was not found\") #this will error out and stop the program\n print(\"feature file not found.\")\n features_found = False\n print(list_of_feature_files[feature_index][:21], indiv_file[:21] )\n continue\n if features_found:\n temp_biovolumes = grab_biovolume(list_of_feature_files.pop(feature_index), list_of_class_files[class_index], automated_or_manual)\n #temp_biovolumes.to_csv(outpath + indiv_file[:-3] + 'csv')\n \n print(\"done!\")\n temp_counts = grab_class_counts(list_of_class_files[class_index], automated_or_manual, category_list)\n temp_timestamp = list_of_class_files[class_index]\n if temp_timestamp[0] == 'D':\n timestamp = datetime.strptime(temp_timestamp[:16], 'D%Y%m%dT%H%M%S')\n else:\n timestamp = datetime.strptime(temp_timestamp[:21], 'IFCB3_%Y_%j_%H%M%S')\n \n temp_counts_df = pd.DataFrame.from_dict(temp_counts, orient='index')\n all_counts[timestamp] = temp_counts_df\n all_biovolumes[timestamp] = temp_biovolumes.Biovolume\n \n \n #except:\n # print \"something went wrong.\"\n #break\n #while list_of_feature_files[feature_index][:21] != indiv_file[:21]:\n # feature_index += 1\n # if feature_index >= len(list_of_feature_files)-1:\n # #raise ValueError(\"The feature file was not found\") #this will error out and stop the program\n # print \"feature file not found.\"; print list_of_feature_files[feature_index][:21], indiv_file[:21] \n # features_found = False\n #if features_found:\n # temp_biovolumes = grab_biovolume(list_of_feature_files.pop(feature_index), list_of_class_files[class_index], automated_or_manual)\n # temp_biovolumes.to_csv(outpath + indiv_file[:-3] + 'csv')\n # print \"done!\"\n else:\n continue\n \n #now output the final files\n all_counts.T.to_csv(outpath+'summary_counts.csv')\n all_biovolumes.T.to_csv(outpath+'summary_biovolumes.csv')\n","sub_path":"IFCB_summarize_class_files.py","file_name":"IFCB_summarize_class_files.py","file_ext":"py","file_size_in_byte":13915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"401884184","text":"import unittest\n\n### Problem 1\ndef is_multiple_of_3(number):\n if number % 3 == 0:\n return True\n else:\n return False\n\ndef is_multiple_of_5(number):\n if number % 5 == 0:\n return True\n else:\n return False\n\ndef problem_1():\n print(\"\"\"Problem 1: Multiples of 3 and 5\nIf we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.\"\"\")\n number = 0\n sum_of_multiples = 0\n for i in range(0, 1000):\n #print(number)\n if (is_multiple_of_3(number) == True) or (is_multiple_of_5(number) == True):\n #print(\"true\")\n sum_of_multiples = sum_of_multiples + number\n number = number + 1\n\n print(sum_of_multiples)\n###\n\n### Problem 2\ndef problem_2():\n print(\"\"\"Problem 2: Even Fibonacci numbers\nEach new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...\nBy considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms\"\"\")\n fib_num1 = 0\n fib_num2 = 1\n fib_num_temp = 1\n fib_sum = 0\n while fib_num_temp <= 4000000:\n if fib_num_temp % 2 == 0:\n fib_sum = fib_sum + fib_num_temp\n fib_num1 = fib_num2\n fib_num2 = fib_num_temp\n fib_num_temp = fib_num1 + fib_num2\n print(fib_sum)\n###\n\n### Problem 3\ndef check_number_prime(number):\n is_prime = True\n for div_number in range(2, number):\n if number % div_number == 0:\n is_prime = False\n return is_prime\n\ndef problem_3():\n print(\"\"\"Problem 3: Largest prime factor\nThe prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?\"\"\")\n\n\n###\n\n### Problem 4\ndef problem_4():\n print(\"\"\"Problem 4: Largest palindrome product\nA palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.\"\"\")\n\n\n###\n\n### Problem 5\ndef problem_5():\n print(\"\"\"Problem 5: Smallest multiple\n2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?\"\"\")\n\n\n###\n\n### Menu\ndef menu():\n menu_loop_flag = False\n while menu_loop_flag != True:\n menu_choice = input(\"Problems:\\nProblem 1: Multiples of 3 and 5\\nProblem 2: Even Fibonacci numbers\\nProblem 3: Largest prime factor\\nProblem 4: Largest palindrome product\\nProblem 5: Smallest multiple\\nPress 'q' to quit\\nEnter choice: \")\n if menu_choice == \"1\":\n problem_1()\n elif menu_choice == \"2\":\n problem_2()\n elif menu_choice == \"3\":\n problem_3()\n elif menu_choice == \"4\":\n problem_4()\n elif menu_choice == \"5\":\n problem_5()\n elif menu_choice == \"q\":\n menu_loop_flag = True\n\n\n###\n\n###\nmenu()\ninput()\n###\n","sub_path":"project-euler.py","file_name":"project-euler.py","file_ext":"py","file_size_in_byte":3197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"214845604","text":"import sys\nfrom Lexer import Lexer\nfrom Formatter import Formatter\n\n# python main.py test2.py log_file.log template.json result.py\n# python main.py test3.py log_file.log template.json result.py\n# python main.py test_import.py log_file.log template.json result.py\n# python main.py test_long_string.py log_file.log template.json result.py\n# python main.py test_op.py log_file.log template.json result.py\n# python main.py D:\\1.Downloads\\Formatter.py log_file.log template.json result.py\n\nif __name__ == \"__main__\":\n lexer = Lexer()\n formatter = Formatter()\n\n if len(sys.argv) == 5:\n tokens = lexer.tokenize_file(sys.argv[1])\n log = open(sys.argv[2], \"w+\")\n formatter.load_template(sys.argv[3])\n result_code = formatter.format(tokens, log)\n log.close()\n result_file = open(sys.argv[4], \"w+\")\n result_file.write(result_code)\n result_file.close()\n print(\"Done!!!\")\n elif len(sys.argv) == 2 and sys.argv[1] == \"--help\":\n print(\"There are 4 parameters:\")\n print(\"1) Python file for processing\")\n print(\"2) Logging file for printing mistakes\")\n print(\"3) JSON file with template data\")\n print(\"4) Python file where result will be written\")\n elif len(sys.argv) == 1:\n print(\"This is Python formatter. Please enter necessary parameters and lauch. Type \\\"--help\\\" for more information.\")\n else:\n print(\"Wrong parameters. Please, type \\\"--help\\\" for more information.\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"304767817","text":"LEFT = 0\nRIGHT = 1\nUP = 2\nDOWN = 3\n\ntiles = []\n\nwith open('file.in', 'rt') as fin:\n lines = list(map(lambda line: line.strip(), fin.readlines()))\n\ni = 0\nwhile i < len(lines):\n tile_id = int(lines[i].split(' ')[1][:-1])\n image = []\n\n i += 1\n\n while i < len(lines) and lines[i] != '':\n image.append(lines[i])\n i += 1\n\n tiles.append((tile_id, image))\n\n i += 1\n\nfor i in range(len(tiles)):\n tile = tiles[i]\n edges = []\n\n edges.append((tile[1][0], UP))\n edges.append((tile[1][-1], DOWN))\n edges.append((tile[1][0][::-1], UP))\n edges.append((tile[1][-1][::-1], DOWN))\n edges.append((''.join([e[0] for e in tile[1]]), LEFT))\n edges.append((''.join([e[-1] for e in tile[1]]), RIGHT))\n edges.append((''.join([e[0] for e in tile[1]][::-1]), LEFT))\n edges.append((''.join([e[-1] for e in tile[1][::-1]]), RIGHT))\n\n tiles[i] = (tiles[i][0], tiles[i][1], edges)\n\nnodes = []\nfor i in range(len(tiles) - 1):\n for j in range(i + 1, len(tiles)):\n edges_i = [e[0] for e in tiles[i][2]]\n edges_j = [e[0] for e in tiles[j][2]]\n\n if len(set(edges_i).intersection(set(edges_j))) != 0:\n nodes.append(tiles[i][0])\n nodes.append(tiles[j][0])\n\nres = 1\nfor i in range(len(tiles)):\n if nodes.count(tiles[i][0]) == 2:\n res *= tiles[i][0]\n\nprint(res)\n","sub_path":"20/part_1.py","file_name":"part_1.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"596588956","text":"\nimport FWCore.ParameterSet.Config as cms\n\n#until we are actually clustering across the EB/EE boundary\n#it is faster to cluster EB and EE as separate\n\nparticleFlowRecHitEK = cms.EDProducer(\"PFRecHitProducer\",\n navigator = cms.PSet(\n name = cms.string(\"PFRecHitShashlikNavigator\"),\n barrel = cms.PSet( ),\n endcap = cms.PSet( )\n ),\n producers = cms.VPSet(\n cms.PSet(\n name = cms.string(\"PFEKRecHitCreator\"),\n src = cms.InputTag(\"ecalRecHit:EcalRecHitsEK\"),\n qualityTests = cms.VPSet( \n cms.PSet(\n name = cms.string(\"PFRecHitQTestThreshold\"),\n threshold = cms.double(0.08)\n ),\n )\n ) \n ) \n)\n","sub_path":"RecoParticleFlow/PFClusterProducer/python/particleFlowRecHitShashlik_cfi.py","file_name":"particleFlowRecHitShashlik_cfi.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"24168178","text":"import random\nimport time\nimport numpy as np\nimport os\nimport json\nimport shutil\nimport cv2\nfrom keras.preprocessing.image import img_to_array\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation, Flatten, Reshape\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D, ZeroPadding2D\nfrom keras.optimizers import SGD, Adam, RMSprop\nfrom keras.callbacks import TensorBoard\nfrom time import time\n\n\nSOURCE_PATH = '../data/experiment001/license plate/artificial/'\nMODEL_PATH = '../data/model_artif/'\nTEST_PATHS = \"../data/experement1/artificial_test/\"\nTRAIN_PATHS = \"../data/experement1/artificial_train/\"\n\nNB_EPOCH = 25\nBATCH_SIZE = 20\nSPLIT_SIZE = 0.25\nVERBOSE = 1\nOPTIM = Adam()\n\ndef split_sources():\n #if os.listdir(TEST_PATHS + 'ann/'):\n # os.remove(TEST_PATHS + 'ann/')\n # os.remove(TEST_PATHS + 'img/')\n #if os.listdir(TRAIN_PATHS + 'ann/'):\n # os.remove(TRAIN_PATHS + 'ann/')\n # os.remove(TRAIN_PATHS + 'img/')\n files = os.listdir(SOURCE_PATH + 'img/')\n split_size = len(files) - int(len(files) * SPLIT_SIZE)\n print(split_size)\n train = files[:split_size]\n test = files[split_size:]\n for file in train:\n out_file = os.path.splitext(file)[0].split('.')\n shutil.copy2(SOURCE_PATH + 'img/' + file, TRAIN_PATHS + 'img/' + file)\n shutil.copy2(SOURCE_PATH + 'ann/' + out_file[0] + '.json', TRAIN_PATHS + 'ann/' + out_file[0] + '.json')\n\n for file in test:\n out_file = os.path.splitext(file)[0].split('.')\n shutil.copy2(SOURCE_PATH + 'img/' + file, TEST_PATHS + 'img/' + file)\n shutil.copy2(SOURCE_PATH + 'ann/' + out_file[0] + '.json', TEST_PATHS + 'ann/' + out_file[0] + '.json')\n\n\ndef load_image(path):\n list_file = os.listdir(path + 'img/')\n random.seed(40)\n random.shuffle(list_file)\n x_data = []\n y_data = []\n for file in list_file:\n flabel = os.path.splitext(file)[0].split('.')\n im = cv2.imread(path + 'img/' + file, cv2.IMREAD_GRAYSCALE)\n im = img_to_array(im)\n x_data.append(im)\n y_data.append(load_annotation(path + 'ann/' + flabel[0] + '.json'))\n x_data = np.array(x_data, dtype='float')/255.0\n y_data = np.array(y_data)\n return x_data, y_data\n\n\ndef load_annotation(path):\n with open(path) as data_file:\n data = json.load(data_file)\n\n left = data[\"objects\"][0][\"points\"][\"exterior\"][0][0]\n top = data[\"objects\"][0][\"points\"][\"exterior\"][0][1]\n right = data[\"objects\"][0][\"points\"][\"exterior\"][2][0]\n bottom = data[\"objects\"][0][\"points\"][\"exterior\"][2][1]\n\n return [left, top, right, bottom]\n\n\ndef model_lp():\n model = Sequential()\n model.add(Conv2D(32, kernel_size=3, padding=\"same\",\n input_shape=(64, 128, 1)))\n model.add(Activation(\"relu\"))\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n model.add(Conv2D(64, kernel_size=2, padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n model.add(Conv2D(128, kernel_size=2, padding=\"same\"))\n model.add(Activation(\"relu\"))\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n model.add(Flatten())\n #model.add(Reshape((-1, 8*16*128)))\n model.add(Dense(500))\n model.add(Activation(\"relu\"))\n model.add(Dense(500))\n model.add(Activation(\"relu\"))\n model.add(Dense(4))\n return model\n\n\n\ndef main():\n split_sources()\n X_train, Y_train = load_image(TRAIN_PATHS)\n X_test, Y_test = load_image(TEST_PATHS)\n print(\"check shapes:\")\n print(\"X_train - \", X_train.shape)\n print(\"Y_train - \", Y_train.shape)\n print(\"X_test - \", X_test.shape)\n print(\"Y_test - \", Y_test.shape)\n tensorboard = TensorBoard(log_dir=\"../logs/{}\".format(time()), write_graph=True, write_grads=True, write_images=True,\n histogram_freq=0)\n # fit\n model = model_lp()\n model.compile(loss='mean_squared_error', optimizer=OPTIM, metrics=['accuracy'])\n history = model.fit(X_train, Y_train, batch_size=BATCH_SIZE, epochs=NB_EPOCH, verbose=VERBOSE,\n validation_data=(X_test, Y_test),\n validation_split=SPLIT_SIZE, callbacks=[tensorboard])\n\n score = model.evaluate(X_test, Y_test, verbose=VERBOSE)\n print('Test score:', score[0])\n print('Test accuracy', score[1])\n model_json = model.to_json()\n with open(\"model_lpd.json\", \"w\") as json_file:\n json_file.write(model_json)\n #serialize weights to HDF5\n model.save_weights(\"model_lpd.h5\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"anpr/src/train_detect_license_plate.py","file_name":"train_detect_license_plate.py","file_ext":"py","file_size_in_byte":4596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"218124328","text":"'''Action controller module.'''\n\nimport cherrypy\nfrom sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound\n\nfrom moira.view.template import DefaultRenderer\nfrom moira.view.action import ActionView, ActionNew, ActionChallenge\nfrom moira.model.db import DBSession\nfrom moira.model.rpg import Action, Scene, Character, Skill, CharacterSkill, Test\nfrom moira.model.dice import DiceRoll\nfrom moira.util.session import auth_user, check_login\n\n\ndef max_order(self, scene_id):\n '''\n Determines maximum order value of a given scene, i.e. number of\n actions completed.\n\n *scene_id*\n the id of the scene in question.\n\n '''\n acc_actions = db.query(Action).filter(\n Action.scene_id == scene_id).filter(\n Action.status == 2).all()\n return max(acc.order for acc in acc_actions) if acc_actions else 0\n\n\nclass ActionController(object):\n\n @cherrypy.expose\n def default(self, action_id):\n db = DBSession()\n try:\n action = db.query(Action).filter(Action.id == int(action_id)).one()\n except NoResultFound:\n raise cherrypy.HTTPError(404, 'Action not found.')\n\n return DefaultRenderer().render(ActionView(action))\n\n @cherrypy.expose\n def new(self, scene_id, char_id=None, text=None):\n '''Add a new action.'''\n db = DBSession()\n # Check login\n user = check_login(db,\n failure='You must be logged in to post an action.')\n\n # Find scene\n try:\n scene = db.query(Scene).filter(Scene.id == int(scene_id)).one()\n except NoResultFound:\n raise cherrypy.HTTPError(404, 'Scene not found')\n\n # Get all characters of user that play in the scene\n characters = db.query(Character).filter(Character.scenes.any(\n id=scene_id)).filter(Character.user_id == user.id).all()\n if not characters:\n raise cherrypy.HTTPError(405, 'User has no characters in the scene.')\n\n # Process submission of new action\n if char_id and text:\n try:\n character = db.query(Character).filter(\n Character.id == char_id).one()\n except NoResultFound:\n raise cherrypy.HTTPError(404, 'No such character.')\n if character.user != user:\n raise cherrypy.HTTPError(403, 'User does not control character.')\n action = Action(text)\n scene.actions.append(action)\n action.character = character\n db.add(action)\n db.commit()\n raise cherrypy.HTTPRedirect('/moira/scene/%s' % scene_id)\n\n return DefaultRenderer().render(ActionNew(scene, characters))\n\n def __get_db_user_action(self, action_id):\n db = DBSession()\n user = check_login(db,\n failure='You must be logged in to approve an action.')\n try:\n action = db.query(Action).filter(Action.id == action_id).one()\n except NoResultFound:\n raise cherrypy.HTTPError(404, 'Action not found.')\n return db, user, action\n\n\n @cherrypy.expose\n def approve(self, action_id):\n '''Approves an action.'''\n db, user, action = self.__get_db_user_action(action_id)\n if user not in action.scene.game_masters:\n raise cherrypy.HTTPError(403, 'Not a game master.')\n if action.complete:\n raise cherrypy.HTTPError(405, 'Action is already complete.')\n action.order = max_order(action.scene_id) + 1\n action.status = 2\n db.merge(action)\n db.commit()\n raise cherrypy.HTTPRedirect('/moira/scene/%d' % action.scene_id)\n\n @cherrypy.expose\n def reject(self, action_id):\n db, user, action = self.__get_db_user_action(action_id)\n if user not in action.scene.game_masters:\n raise cherrypy.HTTPError(403, 'Not a game master.')\n if not action.proposed:\n raise cherrypy.HTTPError(405, 'Only proposed actions can be rejected.')\n action.order = -1\n action.status = 1\n db.merge(action)\n db.commit()\n raise cherrypy.HTTPRedirect('/moira/scene/%d' % action.scene_id)\n\n @cherrypy.expose\n def challenge(self, action_id, skill_id=None, difficulty=None):\n db, user, action = self.__get_db_user_action(action_id)\n if user not in action.scene.game_masters:\n raise cherrypy.HTTPError(403, 'Not a game master.')\n if not action.proposed:\n raise cherrypy.HTTPError(405, 'Only proposed actions can be challenged.')\n if skill_id and difficulty:\n action.order = -1\n action.status = 3\n skill = db.query(Skill).filter(Skill.id == int(skill_id)).one()\n char_skill = db.query(CharacterSkill).\\\n filter(CharacterSkill.char_id == action.character.id).\\\n filter(CharacterSkill.skill_id == int(skill_id)).one()\n test = Test(DiceRoll('4dF'), skill, char_skill.level, int(difficulty), action)\n db.add(test)\n db.merge(action)\n db.commit()\n raise cherrypy.HTTPRedirect('/moira/scene/%d' % action.scene_id)\n else:\n skills = db.query(Skill).all()\n return DefaultRenderer().render(ActionChallenge(action, skills))\n\n","sub_path":"moira/controller/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":5293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"85995500","text":"#!/usr/bin/env python3\n\nimport os\nimport re\nimport sys\n\nfrom collections import defaultdict\nimport numpy as np\n\n\nclass Point(object):\n def __init__(self, x, y, id_num):\n self.x = x\n self.y = y\n self.id_num = id_num\n self.manhattan = 0\n self.on_edge = False\n self.total_dist = 0\n\n def set_total_dist(self, dist):\n self.total_dist = dist\n\n def distance(self, c, d):\n return abs(self.x - c) + abs(self.y - d)\n\n\nclass PointPlane(object):\n def __init__(self, points):\n self.points = points\n self.max_x = max(points, key=lambda c: c.x).x\n self.max_y = max(points, key=lambda c: c.y).y\n self.plane = np.zeros((self.max_x + 1, self.max_y + 1), dtype=np.int16)\n self.on_edge = None\n\n def determine_dists(self):\n for x in range(self.max_x + 1):\n for y in range(self.max_y + 1):\n dists = {}\n for point in self.points:\n dists[point.id_num] = point.distance(x, y)\n if len([x for x in dists.values() if x == min(dists.values())]) == 1:\n self.plane[(x, y)] = min(dists, key=dists.get)\n\n def determine_total_dists(self):\n for x in range(self.max_x + 1):\n for y in range(self.max_y + 1):\n for point in self.points:\n self.plane[(x, y)] += point.distance(x, y)\n\n def determine_on_edge(self):\n on_edge = []\n for y in range(0, self.max_y + 1):\n on_edge.append(self.plane[(0, y)])\n for x in range(0, self.max_x + 1):\n on_edge.append(self.plane[(x, 0)])\n for y in range(0, self.max_y + 1):\n on_edge.append(self.plane[(self.max_x, y)])\n for x in range(0, self.max_x + 1):\n on_edge.append(self.plane[(x, self.max_y)])\n self.on_edge = set(on_edge)\n\n def largest_non_edge(self):\n areas = defaultdict(int)\n for x in range(0, self.max_x + 1):\n for y in range(0, self.max_y + 1):\n if self.plane[(x, y)] not in self.on_edge:\n areas[self.plane[(x, y)]] += 1\n return max(areas.values())\n\n def total_lt1k(self):\n total_size = 0\n for x in range(0, self.max_x + 1):\n for y in range(0, self.max_y + 1):\n if self.plane[(x, y)] < 10000:\n total_size += 1\n return total_size\n\n\ndef solve_p1(points):\n pp = PointPlane(points)\n pp.determine_dists()\n pp.determine_on_edge()\n print(\"PART1: %d\" % pp.largest_non_edge())\n\n\ndef solve_p2(points):\n pp = PointPlane(points)\n pp.determine_total_dists()\n print(\"PART2: %d\" % pp.total_lt1k())\n\n\ndef format_input(f_name):\n with open(f_name, \"r\") as file:\n data_list = file.read().splitlines()\n points = []\n id_num = 1\n for line in data_list:\n m = re.search(r\"(\\d+), (\\d+)\", line.strip('\\n'))\n if m:\n points.append(Point(int(m.group(1)), int(m.group(2)), id_num))\n id_num += 1\n solve_p1(points)\n solve_p2(points)\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2:\n print(\"Usage: ./ \")\n if __debug__:\n print(sys.argv)\n sys.exit(1)\n else:\n f_name = sys.argv[1]\n if __debug__:\n print(\"Passed in filename=%s\" % f_name)\n if not os.path.exists(f_name):\n print(\"Can't locate input file\")\n sys.exit(1)\n else:\n format_input(f_name)\n","sub_path":"Day06/puzzle6.py","file_name":"puzzle6.py","file_ext":"py","file_size_in_byte":3519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"368813562","text":"#coding: utf-8\nimport sys\nimport logging\nimport datetime\nfrom optparse import make_option\nfrom decimal import Decimal\nfrom django.core.management import BaseCommand, CommandError\nfrom uploading.utils import ParseReportFile\nfrom uploading.models import PlatformRate\nfrom external.models import Currencies\nfrom cmon.models import Market\n\n\nclass Command(BaseCommand):\n\n help = u'Загрузка курсов в r2.platform_rate'\n\n def handle(self, *args, **options):\n\n try:\n area = args[0]\n period_date = args[1]\n path = args[2]\n except IndexError:\n logging.error(\"usage: ./manage.py load_rates \")\n sys.exit(0)\n\n try:\n period_date = datetime.date(int(period_date[:4]), int(period_date[4:]), 1)\n except ValueError as e:\n logging.error(e)\n sys.exit(0)\n\n try:\n market = Market.objects.get(name=area)\n except Market.DoesNotExist:\n markets = [m.name for m in Market.objects.all()]\n logging.warn(u\"магазина %s нет в cmon.market. \\nCписок доступных: %s \" % (area, '\\n'.join(markets)))\n sys.exit(0)\n\n cfg = market.get_config\n platform_id = cfg.bd_constants['platform_id']\n\n if market.name == 'google':\n delimiter = '\\t' # разделитель, если используется csv\n #finish_currency_id = 2 # доллар\n needed_columns = {\n '0': 'currency_code', # код валюты\n '1': 'fx_rate', # курс\n }\n elif market.name == 'itunes':\n delimiter = '\\t' # разделитель, если используется csv\n finish_currency_id = 2 # доллар\n needed_columns = {\n '0': 'currency_code', # код валюты\n '8': 'fx_rate', # курс\n }\n try:\n array = ParseReportFile(path, needed_columns, delimiter).array\n except IOError:\n logging.error(u'файла %s не существует' % path)\n sys.exit(0)\n\n for a in array:\n currency_code = a['currency_code']\n\n if market.name == 'google':\n from_, to = a['currency_code'].split('to')\n currency_code = from_.strip()\n finish_currency_code = to.strip()\n finish_currency_id = self.get_currency_id(finish_currency_code).currency_id\n\n currency_obj = self.get_currency_id(currency_code)\n if not currency_obj:\n continue\n\n rate = a['fx_rate']\n\n if ',' in rate:\n rate = rate.replace(',', '.')\n\n fx_rate = float(rate)\n PlatformRate.objects.get_or_create(\n platform_id=platform_id,\n currency_id=currency_obj.currency_id,\n fx_rate=fx_rate,\n period_date=period_date,\n finish_currency_id=finish_currency_id,\n )\n\n logging.info('done')\n\n def get_currency_id(self, currency_code):\n try:\n currency = Currencies.objects.get(currency_code=currency_code)\n return currency\n except Currencies.DoesNotExist:\n logging.warn(u'валюты %s нет в conf.currencies. Continued' % currency_code)\n","sub_path":"apps/uploading/management/commands/load_rates.py","file_name":"load_rates.py","file_ext":"py","file_size_in_byte":3477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"366826388","text":"from datetime import datetime\nfrom sqlalchemy import (\n Column,\n DateTime,\n Enum,\n ForeignKey,\n Integer,\n Unicode,\n UnicodeText,\n)\n\nfrom . import (\n Base,\n DBSession,\n)\n\n\nclass Notification(Base):\n \"\"\"\n Notification model.\n \"\"\"\n __tablename__ = 'notification'\n __table_args__ = {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8'}\n id = Column(Integer, primary_key=True)\n destination_id = Column(Integer, ForeignKey('destination.id'))\n user_id = Column(Integer, ForeignKey('user.id'))\n invitation_id = Column(Integer, ForeignKey('invitation.id', ondelete='CASCADE'))\n\n event = Column(Unicode(30), nullable=False)\n message = Column(UnicodeText(), default=u'', nullable=False)\n priority = Column(Enum('low', 'moderate', 'high', 'urgent'), nullable=False)\n timestamp = Column(DateTime)\n\n def __init__(self, event, message, priority='low', user=None, invitation_id=None):\n if user is not None:\n self.user_id = user.id\n self.event = unicode(event)\n self.message = unicode(message)\n self.priority = unicode(priority)\n self.invitation_id = invitation_id\n self.timestamp = datetime.now()\n\n def __repr__(self):\n return '' % (self.id, self.event, self.message)\n\n @classmethod\n def by_id(cls, id):\n return DBSession.query(cls).filter(cls.id == id).first()\n\n def add(self):\n try:\n DBSession.add(self)\n DBSession.flush()\n except Exception:\n raise\n\n def delete(self):\n try:\n DBSession.delete(self)\n DBSession.flush()\n except Exception:\n raise\n\n def update(self):\n try:\n DBSession.flush()\n except Exception:\n raise\n","sub_path":"mts/models/notification.py","file_name":"notification.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"34973339","text":"import os\nimport json\n\nclass Settings:\n def __init__(self,lastConfig,lastShot,brightness,flashOn):\n self.lastConfig=lastConfig\n self.lastShot=lastShot\n self.lastBrightness=brightness\n self.flashOn=flashOn\n\n\nclass Persist():\n\n #http://stackoverflow.com/a/10352231/810944\n @staticmethod\n def touchopen(filename, *args, **kwargs):\n # Open the file in R/W and create if it doesn't exist. *Don't* pass O_TRUNC\n fd = os.open(filename, os.O_RDWR | os.O_CREAT)\n\n # Encapsulate the low-level file descriptor in a python file object\n return os.fdopen(fd, *args, **kwargs)\n \n @staticmethod\n def readLastConfig(initConfig, initShot, initFlash, filename):\n with Persist.touchopen(filename, \"r+\") as target:\n try:\n settings = json.load(target)\n except ValueError:\n settings = {\n \"lastConfig\": initConfig,\n \"lastShot\": initShot,\n \"flashOn\": initFlash\n }\n return settings\n \n @staticmethod\n def writeLastConfig(lastConfig, initShot, brightness, filename, flashOn):\n with Persist.touchopen(filename, \"r+\") as target:\n \n settings=Settings(lastConfig, initShot, brightness, flashOn)\n json.dump(vars(settings), target, sort_keys=True, indent=4)\n #json.dump('settings': [{'lastConfig': lastConfig, 'lastShot': initShot]}, target, sort_keys=True, indent=4)\n # Write the new value and truncate\n #target.seek(0)\n #target.write(str(lastConfig))\n target.truncate()\n","sub_path":"config_persist.py","file_name":"config_persist.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"68898686","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[3]:\n\n\nprint(\"MULTIPLICACIÓN DE MATRICES- No se pide el numero de filas de la matriz dos porque debe ser el mismo valor de las columnas de la Matriz 1\")\nf1=int(input(\"Matriz 1: introduzca numero de filas\"))\n\n\n# In[4]:\n\n\nc1=int(input(\"Matriz 1: introduzca numero de columnas\"))\n\n\n# In[5]:\n\n\nc2=int(input(\"Matriz 2: introduzca numero de columnas\"))\n\n\n# In[6]:\n\n\nA=[]\nfor i in range(f1):\n A.append([0]*c1)\n\n\n# In[7]:\n\n\nfor i in range(f1):\n print(A[i])\n\n\n# In[8]:\n\n\nB=[]\nfor i in range(c1):\n B.append([0]*c2)\n\n\n# In[9]:\n\n\nfor i in range(c1):\n print(B[i])\n\n\n# In[10]:\n\n\nfor a in range(f1):\n for b in range(c1):\n A[a][b]=int (input(\"Ingrese valor (%d,%d): \" % (a,b)))\n\n\n# In[11]:\n\n\nfor i in range(f1):\n print(A[i])\n\n\n# In[12]:\n\n\nfor a in range(c1):\n for b in range(c2):\n B[a][b]=int (input(\"Ingrese valor (%d,%d): \" % (a,b)))\n\n\n# In[13]:\n\n\nfor i in range(c1):\n print(B[i])\n\n\n# In[14]:\n\n\nC=[]\nfor i in range(f1):\n C.append([0]*c2)\n\n\n# In[15]:\n\n\nfor i in range(f1):\n print(C[i])\n\n\n# In[16]:\n\n\nfor i in range(f1):\n for j in range(c2):\n for k in range(c1):\n C[i][j]+= A[i][k]*B[k][j]\n\n\n# In[17]:\n\n\nfor i in range(f1):\n R=[]\n for j in range(c2):\n R.append(C[i][j])\n print(\"El resultado es:\")\n print(R)\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Deber1-Listas.py","file_name":"Deber1-Listas.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"560970980","text":"import sys\n\nclass mtoK(object):\n def mtokForm(self, distM):\n distK = int(distM * 1.6)\n print(\"%sM = %sK\" % (distM,distK))\n\nclass ktoM(object):\n def ktomForm(self, distK):\n distM = int(distK * 0.6)\n print(\"%sK = %sM\" % (distK,distM))\n\ntry:\n sys.argv[1] == 'mtok' or 'ktom'\nexcept IndexError:\n print(\"Usage: 'mtok/ktom ##'\")\n sys.exit()\n\nif sys.argv[1] == 'mtok':\n userIn = int(sys.argv[2])\n distConv = mtoK()\n distConv.mtokForm(userIn)\n\nelif sys.argv[1] == 'ktom':\n userIn = int(sys.argv[2])\n distConv = ktoM()\n distConv.ktomForm(userIn)\n\nelse:\n print(\"Usage: 'mtok/ktom ##'\")\n","sub_path":"dist.py","file_name":"dist.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"93110020","text":"import time\r\nstart = time.perf_counter()\r\ndef func():\r\n print('durmiendo1')\r\n time.sleep(1)\r\n print(\"terminado1\")\r\n\r\ndef func1():\r\n print('durmiendo2')\r\n time.sleep(1)\r\n print(\"terminado2\")\r\nfunc()\r\nfunc1()\r\n\r\nfinish = time.perf_counter()\r\nprint(f'Terminado en {round(finish-start, 2)} segundo(s)')","sub_path":"sin_hilos.py","file_name":"sin_hilos.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"105779819","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n\n\n# Recursive Solution\nclass Solution:\n def maxDepth(self, root: TreeNode) -> int:\n \n if not root:\n return 0 \n \n self.max_depth = 0 \n self.iterateTree(root, 0) \n return self.max_depth\n \n def iterateTree(self, root, depth):\n \n if root.val or root.val == 0:\n depth += 1\n if self.max_depth < depth:\n self.max_depth = depth\n \n if root.left or root.left == 0:\n self.iterateTree(root.left, depth)\n \n if root.right or root.right == 0:\n self.iterateTree(root.right, depth)\n \n return True\n \n \n \n \n# Solution using Queue ( BFS )\n# class Solution: \n# def maxDepth(self, root: TreeNode) -> int:\n\n# depth = 0\n# level = [root] if root else []\n \n# while level:\n \n# depth += 1\n# queue = []\n \n# for children in level:\n \n# if children.left or children.left == 0:\n# queue.append(children.left)\n \n# if children.right or children.right == 0:\n# queue.append(children.right)\n \n# level = queue\n \n# return depth\n\n\n\n\n\n# Solution using List ( BFS ) ( shorthand )\n# class Solution: \n# def maxDepth(self, root: TreeNode) -> int:\n\n# depth = 0\n# level = [root] if root else []\n \n# while level:\n# depth += 1\n# level = [child for node in level for child in (node.left, node.right) if child]\n \n# return depth\n \n\n \n \n","sub_path":"LeetCode/Maximum-Depth-of-Binary-Tree.py","file_name":"Maximum-Depth-of-Binary-Tree.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"70455075","text":"# coding=utf-8\n# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport functools\nimport logging\nimport os\nimport re\n\nfrom future.utils import PY3, text_type\nfrom twitter.common.collections import OrderedSet\n\nfrom pants.backend.jvm.subsystems.dependency_context import DependencyContext # noqa\nfrom pants.backend.jvm.subsystems.shader import Shader\nfrom pants.backend.jvm.targets.junit_tests import JUnitTests\nfrom pants.backend.jvm.targets.jvm_target import JvmTarget\nfrom pants.backend.jvm.targets.scala_library import ScalaLibrary\nfrom pants.backend.jvm.tasks.classpath_entry import ClasspathEntry\nfrom pants.backend.jvm.tasks.jvm_compile.compile_context import CompileContext\nfrom pants.backend.jvm.tasks.jvm_compile.execution_graph import Job\nfrom pants.backend.jvm.tasks.jvm_compile.zinc.zinc_compile import ZincCompile\nfrom pants.base.build_environment import get_buildroot\nfrom pants.base.exceptions import TaskError\nfrom pants.base.workunit import WorkUnitLabel\nfrom pants.engine.fs import (EMPTY_DIRECTORY_DIGEST, Digest, DirectoryToMaterialize, PathGlobs,\n PathGlobsAndRoot)\nfrom pants.engine.isolated_process import ExecuteProcessRequest, FallibleExecuteProcessResult\nfrom pants.java.jar.jar_dependency import JarDependency\nfrom pants.reporting.reporting_utils import items_to_report_element\nfrom pants.util.contextutil import Timer\nfrom pants.util.dirutil import fast_relpath, fast_relpath_optional, safe_mkdir\nfrom pants.util.memo import memoized_method, memoized_property\nfrom pants.util.objects import enum\n\n\n#\n# This is a subclass of zinc compile that uses both Rsc and Zinc to do\n# compilation.\n# It uses Rsc and the associated tools to outline scala targets. It then\n# passes those outlines to zinc to produce the final compile artifacts.\n#\n#\nlogger = logging.getLogger(__name__)\n\n\ndef fast_relpath_collection(collection):\n buildroot = get_buildroot()\n return [fast_relpath_optional(c, buildroot) or c for c in collection]\n\n\ndef stdout_contents(wu):\n if isinstance(wu, FallibleExecuteProcessResult):\n return wu.stdout.rstrip()\n with open(wu.output_paths()['stdout']) as f:\n return f.read().rstrip()\n\n\ndef _create_desandboxify_fn(possible_path_patterns):\n # Takes a collection of possible canonical prefixes, and returns a function that\n # if it finds a matching prefix, strips the path prior to the prefix and returns it\n # if it doesn't it returns the original path\n # TODO remove this after https://github.com/scalameta/scalameta/issues/1791 is released\n regexes = [re.compile('/({})'.format(p)) for p in possible_path_patterns]\n def desandboxify(path):\n if not path:\n return path\n for r in regexes:\n match = r.search(path)\n if match:\n logger.debug('path-cleanup: matched {} with {} against {}'.format(match, r.pattern, path))\n return match.group(1)\n logger.debug('path-cleanup: no match for {}'.format(path))\n return path\n return desandboxify\n\n\ndef _paths_from_classpath(classpath_tuples, collection_type=list):\n return collection_type(y[1] for y in classpath_tuples)\n\n\nclass CompositeProductAdder(object):\n def __init__(self, *products):\n self.products = products\n\n def add_for_target(self, *args, **kwargs):\n for product in self.products:\n product.add_for_target(*args, **kwargs)\n\n\nclass _CompileWorkflowChoice(enum(['zinc-only', 'guess'])):\n \"\"\"Enum covering the values for the default workflow option.\n\n guess - Try to classify compile targets based on whether they are Scala/Java or test targets.\n zinc-only - Always use zinc.\"\"\"\n\n\nclass _JvmCompileWorkflowType(enum(['zinc-only', 'rsc-then-zinc'])):\n \"\"\"Target classifications used to correctly schedule Zinc and Rsc jobs.\n\n There are some limitations we have to work around before we can compile everything through Rsc\n and followed by Zinc.\n - rsc is not able to outline all scala code just yet (this is also being addressed through\n automated rewrites).\n - javac is unable to consume rsc's jars just yet.\n - rsc is not able to outline all java code just yet (this is likely to *not* require rewrites,\n just some more work on rsc).\n\n As we work on improving our Rsc integration, we'll need to create more workflows to more closely\n map the supported features of Rsc. This enum class allows us to do that.\n\n - zinc-only: compiles targets just with Zinc and uses the Zinc products of their dependencies.\n - rsc-then-zinc: compiles targets with Rsc to create \"header\" jars, then runs Zinc against the\n Rsc products of their dependencies. The Rsc compile uses the Rsc products of Rsc compatible\n targets and the Zinc products of zinc-only targets.\n \"\"\"\n\n @classmethod\n def classify_target(cls, target):\n # NB: Java targets, Scala+Java targets, and some test targets are not currently supported for\n # compile with Rsc.\n # TODO: Rsc's produced header jars don't yet work with javac. Once this is resolved, we may add\n # additional workflow types.\n if target.has_sources('.java') or \\\n isinstance(target, JUnitTests) or \\\n (isinstance(target, ScalaLibrary) and tuple(target.java_sources)):\n target_type = _JvmCompileWorkflowType.zinc_only\n elif target.has_sources('.scala'):\n target_type = _JvmCompileWorkflowType.rsc_then_zinc\n else:\n target_type = None\n return target_type\n\n\nclass RscCompileContext(CompileContext):\n def __init__(self,\n target,\n analysis_file,\n classes_dir,\n rsc_jar_file,\n jar_file,\n log_dir,\n zinc_args_file,\n sources,\n workflow):\n super(RscCompileContext, self).__init__(target, analysis_file, classes_dir, jar_file,\n log_dir, zinc_args_file, sources)\n self.workflow = workflow\n self.rsc_jar_file = rsc_jar_file\n\n def ensure_output_dirs_exist(self):\n safe_mkdir(os.path.dirname(self.rsc_jar_file))\n\n\nclass RscCompile(ZincCompile):\n \"\"\"Compile Scala and Java code to classfiles using Rsc.\"\"\"\n\n _name = 'mixed' # noqa\n compiler_name = 'rsc'\n\n @classmethod\n def implementation_version(cls):\n return super(RscCompile, cls).implementation_version() + [('RscCompile', 172)]\n\n def __init__(self, *args, **kwargs):\n super(RscCompile, self).__init__(*args, **kwargs)\n\n self._rsc_compat_tag = self.get_options().force_compiler_tag_prefix\n self._compiler_tags = {'{}:{}'.format(self._rsc_compat_tag, workflow.value): workflow\n for workflow in _JvmCompileWorkflowType.all_variants}\n self._default_workflow = self.get_options().default_workflow\n\n # If the default workflow is conveyed through a flag, override tag values.\n self._ignore_tags_when_calculating_workflow = self.get_options().is_flagged('default_workflow')\n\n @classmethod\n def register_options(cls, register):\n super(RscCompile, cls).register_options(register)\n register('--force-compiler-tag-prefix', default='use-compiler', metavar='',\n help='Always compile targets marked with this tag with rsc, unless the workflow is '\n 'specified on the cli.')\n register('--default-workflow', type=_CompileWorkflowChoice,\n default=_CompileWorkflowChoice.guess, metavar='',\n help='Defines how a compile workflow is chosen when a tag is not present.')\n\n cls.register_jvm_tool(\n register,\n 'rsc',\n classpath=[\n JarDependency(\n org='com.twitter',\n name='rsc_2.11',\n rev='0.0.0-734-e57e96eb',\n ),\n ],\n custom_rules=[\n Shader.exclude_package('rsc', recursive=True),\n ]\n )\n\n # TODO: allow @memoized_method to convert lists into tuples so they can be hashed!\n @memoized_property\n def _nailgunnable_combined_classpath(self):\n \"\"\"Register all of the component tools of the rsc compile task as a \"combined\" jvm tool.\n\n This allows us to invoke their combined classpath in a single nailgun instance (see #7089 and\n #7092). We still invoke their classpaths separately when not using nailgun, however.\n \"\"\"\n cp = []\n cp.extend(self.tool_classpath('rsc'))\n # Add zinc's classpath so that it can be invoked from the same nailgun instance.\n cp.extend(super(RscCompile, self).get_zinc_compiler_classpath())\n return cp\n\n # Overrides the normal zinc compiler classpath, which only contains zinc.\n def get_zinc_compiler_classpath(self):\n return self.execution_strategy_enum.resolve_for_enum_variant({\n self.HERMETIC: lambda: super(RscCompile, self).get_zinc_compiler_classpath(),\n self.SUBPROCESS: lambda: super(RscCompile, self).get_zinc_compiler_classpath(),\n self.NAILGUN: lambda: self._nailgunnable_combined_classpath,\n })()\n\n def register_extra_products_from_contexts(self, targets, compile_contexts):\n super(RscCompile, self).register_extra_products_from_contexts(targets, compile_contexts)\n def pathglob_for(filename):\n return PathGlobsAndRoot(\n PathGlobs(\n (fast_relpath_optional(filename, get_buildroot()),)),\n text_type(get_buildroot()))\n\n def to_classpath_entries(paths, scheduler):\n # list of path ->\n # list of (path, optional) ->\n path_and_digests = [(p, Digest.load(os.path.dirname(p))) for p in paths]\n # partition: list of path, list of tuples\n paths_without_digests = [p for (p, d) in path_and_digests if not d]\n if paths_without_digests:\n self.context.log.debug('Expected to find digests for {}, capturing them.'\n .format(paths_without_digests))\n paths_with_digests = [(p, d) for (p, d) in path_and_digests if d]\n # list of path -> list path, captured snapshot -> list of path with digest\n snapshots = scheduler.capture_snapshots(tuple(pathglob_for(p) for p in paths_without_digests))\n captured_paths_and_digests = [(p, s.directory_digest)\n for (p, s) in zip(paths_without_digests, snapshots)]\n # merge and classpath ify\n return [ClasspathEntry(p, d) for (p, d) in paths_with_digests + captured_paths_and_digests]\n\n def confify(entries):\n return [(conf, e) for e in entries for conf in self._confs]\n\n # Ensure that the jar/rsc jar is on the rsc_classpath.\n for target in targets:\n rsc_cc, compile_cc = compile_contexts[target]\n if rsc_cc.workflow is not None:\n cp_entries = rsc_cc.workflow.resolve_for_enum_variant({\n 'zinc-only': lambda : confify([compile_cc.jar_file]),\n 'rsc-then-zinc': lambda : confify(\n to_classpath_entries([rsc_cc.rsc_jar_file], self.context._scheduler)),\n })()\n self.context.products.get_data('rsc_classpath').add_for_target(\n target,\n cp_entries)\n\n def _is_scala_core_library(self, target):\n return target.address.spec in ('//:scala-library', '//:scala-library-synthetic')\n\n def create_empty_extra_products(self):\n super(RscCompile, self).create_empty_extra_products()\n\n compile_classpath = self.context.products.get_data('compile_classpath')\n classpath_product = self.context.products.get_data('rsc_classpath')\n if not classpath_product:\n self.context.products.get_data('rsc_classpath', compile_classpath.copy)\n else:\n classpath_product.update(compile_classpath)\n\n def select(self, target):\n if not isinstance(target, JvmTarget):\n return False\n return self._classify_compile_target(target) is not None\n\n def _classify_compile_target(self, target):\n if not target.has_sources('.java') and not target.has_sources('.scala'):\n return None\n\n if not self._ignore_tags_when_calculating_workflow:\n for t in target.tags:\n flow = self._compiler_tags.get(t)\n if flow:\n return _JvmCompileWorkflowType(flow)\n\n return self._default_workflow.resolve_for_enum_variant({\n 'zinc-only': _JvmCompileWorkflowType.zinc_only,\n 'guess': _JvmCompileWorkflowType.classify_target(target)\n })\n\n def _key_for_target_as_dep(self, target, workflow):\n # used for jobs that are either rsc jobs or zinc jobs run against rsc\n return workflow.resolve_for_enum_variant({\n 'zinc-only': lambda: self._zinc_key_for_target(target, workflow),\n 'rsc-then-zinc': lambda: self._rsc_key_for_target(target),\n })()\n\n def _rsc_key_for_target(self, target):\n return 'rsc({})'.format(target.address.spec)\n\n def _zinc_key_for_target(self, target, workflow):\n return workflow.resolve_for_enum_variant({\n 'zinc-only': lambda: 'zinc({})'.format(target.address.spec),\n 'rsc-then-zinc': lambda: 'zinc_against_rsc({})'.format(target.address.spec),\n })()\n\n def create_compile_jobs(self,\n compile_target,\n compile_contexts,\n invalid_dependencies,\n ivts,\n counter,\n runtime_classpath_product):\n\n def work_for_vts_rsc(vts, ctx):\n # Double check the cache before beginning compilation\n hit_cache = self.check_cache(vts, counter)\n target = ctx.target\n tgt, = vts.targets\n\n if not hit_cache:\n counter_val = str(counter()).rjust(counter.format_length(), ' ' if PY3 else b' ')\n counter_str = '[{}/{}] '.format(counter_val, counter.size)\n self.context.log.info(\n counter_str,\n 'Rsc-ing ',\n items_to_report_element(ctx.sources, '{} source'.format(self.name())),\n ' in ',\n items_to_report_element([t.address.reference() for t in vts.targets], 'target'),\n ' (',\n ctx.target.address.spec,\n ').')\n\n # This does the following\n # - Collect the rsc classpath elements, including zinc compiles of rsc incompatible targets\n # and rsc compiles of rsc compatible targets.\n # - Run Rsc on the current target with those as dependencies.\n\n dependencies_for_target = list(\n DependencyContext.global_instance().dependencies_respecting_strict_deps(target))\n\n rsc_deps_classpath_unprocessed = _paths_from_classpath(\n self.context.products.get_data('rsc_classpath').get_for_targets(dependencies_for_target),\n collection_type=OrderedSet)\n\n rsc_classpath_rel = fast_relpath_collection(list(rsc_deps_classpath_unprocessed))\n\n ctx.ensure_output_dirs_exist()\n\n with Timer() as timer:\n # Outline Scala sources into SemanticDB / scalac compatible header jars.\n # ---------------------------------------------\n rsc_jar_file = fast_relpath(ctx.rsc_jar_file, get_buildroot())\n\n sources_snapshot = ctx.target.sources_snapshot(scheduler=self.context._scheduler)\n\n distribution = self._get_jvm_distribution()\n\n def hermetic_digest_classpath():\n jdk_libs_rel, jdk_libs_digest = self._jdk_libs_paths_and_digest(distribution)\n merged_sources_and_jdk_digest = self.context._scheduler.merge_directories(\n (jdk_libs_digest, sources_snapshot.directory_digest))\n classpath_rel_jdk = rsc_classpath_rel + jdk_libs_rel\n return (merged_sources_and_jdk_digest, classpath_rel_jdk)\n def nonhermetic_digest_classpath():\n classpath_abs_jdk = rsc_classpath_rel + self._jdk_libs_abs(distribution)\n return ((EMPTY_DIRECTORY_DIGEST), classpath_abs_jdk)\n\n (input_digest, classpath_entry_paths) = self.execution_strategy_enum.resolve_for_enum_variant({\n self.HERMETIC: hermetic_digest_classpath,\n self.SUBPROCESS: nonhermetic_digest_classpath,\n self.NAILGUN: nonhermetic_digest_classpath,\n })()\n\n target_sources = ctx.sources\n args = [\n '-cp', os.pathsep.join(classpath_entry_paths),\n '-d', rsc_jar_file,\n ] + target_sources\n\n self._runtool(\n 'rsc.cli.Main',\n 'rsc',\n args,\n distribution,\n tgt=tgt,\n input_files=tuple(rsc_classpath_rel),\n input_digest=input_digest,\n output_dir=os.path.dirname(rsc_jar_file))\n\n self._record_target_stats(tgt,\n len(rsc_classpath_rel),\n len(target_sources),\n timer.elapsed,\n False,\n 'rsc'\n )\n # Write any additional resources for this target to the target workdir.\n self.write_extra_resources(ctx)\n\n # Update the products with the latest classes.\n self.register_extra_products_from_contexts([ctx.target], compile_contexts)\n\n rsc_jobs = []\n zinc_jobs = []\n\n # Invalidated targets are a subset of relevant targets: get the context for this one.\n compile_target = ivts.target\n rsc_compile_context, zinc_compile_context = compile_contexts[compile_target]\n\n def all_zinc_rsc_invalid_dep_keys(invalid_deps):\n for tgt in invalid_deps:\n # None can occur for e.g. JarLibrary deps, which we don't need to compile as they are\n # populated in the resolve goal.\n tgt_rsc_cc, tgt_z_cc = compile_contexts[tgt]\n if tgt_rsc_cc.workflow is not None:\n # Rely on the results of zinc compiles for zinc-compatible targets\n yield self._key_for_target_as_dep(tgt, tgt_rsc_cc.workflow)\n\n def make_rsc_job(target, dep_targets):\n return Job(\n self._rsc_key_for_target(target),\n functools.partial(\n work_for_vts_rsc,\n ivts,\n rsc_compile_context),\n # The rsc jobs depend on other rsc jobs, and on zinc jobs for targets that are not\n # processed by rsc.\n list(all_zinc_rsc_invalid_dep_keys(dep_targets)),\n self._size_estimator(rsc_compile_context.sources),\n )\n\n def only_zinc_invalid_dep_keys(invalid_deps):\n for tgt in invalid_deps:\n rsc_cc_tgt, zinc_cc_tgt = compile_contexts[tgt]\n if rsc_cc_tgt.workflow is not None:\n yield self._zinc_key_for_target(tgt, rsc_cc_tgt.workflow)\n\n def make_zinc_job(target, input_product_key, output_products, dep_keys):\n return Job(\n key=self._zinc_key_for_target(target, rsc_compile_context.workflow),\n fn=functools.partial(\n self._default_work_for_vts,\n ivts,\n zinc_compile_context,\n input_product_key,\n counter,\n compile_contexts,\n CompositeProductAdder(*output_products)),\n dependencies=list(dep_keys),\n size=self._size_estimator(zinc_compile_context.sources),\n on_success=ivts.update,\n )\n\n # Create the rsc job.\n # Currently, rsc only supports outlining scala.\n workflow = rsc_compile_context.workflow\n workflow.resolve_for_enum_variant({\n 'zinc-only': lambda: None,\n 'rsc-then-zinc': lambda: rsc_jobs.append(make_rsc_job(compile_target, invalid_dependencies)),\n })()\n\n # Create the zinc compile jobs.\n # - Scala zinc compile jobs depend on the results of running rsc on the scala target.\n # - Java zinc compile jobs depend on the zinc compiles of their dependencies, because we can't\n # generate jars that make javac happy at this point.\n workflow.resolve_for_enum_variant({\n # NB: zinc-only zinc jobs run zinc and depend on zinc compile outputs.\n 'zinc-only': lambda: zinc_jobs.append(\n make_zinc_job(\n compile_target,\n input_product_key='runtime_classpath',\n output_products=[\n runtime_classpath_product,\n self.context.products.get_data('rsc_classpath')],\n dep_keys=only_zinc_invalid_dep_keys(invalid_dependencies))),\n 'rsc-then-zinc': lambda: zinc_jobs.append(\n # NB: rsc-then-zinc jobs run zinc and depend on both rsc and zinc compile outputs.\n make_zinc_job(\n compile_target,\n input_product_key='rsc_classpath',\n output_products=[\n runtime_classpath_product,\n ],\n dep_keys=[\n # TODO we could remove the dependency on the rsc target in favor of bumping\n # the cache separately. We would need to bring that dependency back for\n # sub-target parallelism though.\n self._rsc_key_for_target(compile_target)\n ] + list(all_zinc_rsc_invalid_dep_keys(invalid_dependencies))\n )),\n })()\n\n return rsc_jobs + zinc_jobs\n\n def select_runtime_context(self, ccs):\n return ccs[1]\n\n def create_compile_context(self, target, target_workdir):\n # workdir layout:\n # rsc/\n # - outline/ -- semanticdbs for the current target as created by rsc\n # - m.jar -- reified scala signature jar\n # zinc/\n # - classes/ -- class files\n # - z.analysis -- zinc analysis for the target\n # - z.jar -- final jar for the target\n # - zinc_args -- file containing the used zinc args\n sources = self._compute_sources_for_target(target)\n rsc_dir = os.path.join(target_workdir, \"rsc\")\n zinc_dir = os.path.join(target_workdir, \"zinc\")\n return [\n RscCompileContext(\n target=target,\n analysis_file=None,\n classes_dir=None,\n jar_file=None,\n zinc_args_file=None,\n rsc_jar_file=os.path.join(rsc_dir, 'm.jar'),\n log_dir=os.path.join(rsc_dir, 'logs'),\n sources=sources,\n workflow=self._classify_compile_target(target),\n ),\n CompileContext(\n target=target,\n analysis_file=os.path.join(zinc_dir, 'z.analysis'),\n classes_dir=ClasspathEntry(os.path.join(zinc_dir, 'classes'), None),\n jar_file=ClasspathEntry(os.path.join(zinc_dir, 'z.jar'), None),\n log_dir=os.path.join(zinc_dir, 'logs'),\n zinc_args_file=os.path.join(zinc_dir, 'zinc_args'),\n sources=sources,\n )\n ]\n\n def _runtool_hermetic(self, main, tool_name, args, distribution, tgt=None, input_files=tuple(), input_digest=None, output_dir=None):\n tool_classpath_abs = self.tool_classpath(tool_name)\n tool_classpath = fast_relpath_collection(tool_classpath_abs)\n\n cmd = [\n distribution.java,\n ] + self.get_options().jvm_options + [\n '-cp', os.pathsep.join(tool_classpath),\n main,\n ] + args\n\n pathglobs = list(tool_classpath)\n pathglobs.extend(f if os.path.isfile(f) else '{}/**'.format(f) for f in input_files)\n\n if pathglobs:\n root = PathGlobsAndRoot(\n PathGlobs(tuple(pathglobs)),\n text_type(get_buildroot()))\n # dont capture snapshot, if pathglobs is empty\n path_globs_input_digest = self.context._scheduler.capture_snapshots((root,))[0].directory_digest\n\n epr_input_files = self.context._scheduler.merge_directories(\n ((path_globs_input_digest,) if path_globs_input_digest else ())\n + ((input_digest,) if input_digest else ()))\n\n epr = ExecuteProcessRequest(\n argv=tuple(cmd),\n input_files=epr_input_files,\n output_files=tuple(),\n output_directories=(output_dir,),\n timeout_seconds=15*60,\n description='run {} for {}'.format(tool_name, tgt),\n # TODO: These should always be unicodes\n # Since this is always hermetic, we need to use `underlying.home` because\n # ExecuteProcessRequest requires an existing, local jdk location.\n jdk_home=text_type(distribution.underlying_home),\n )\n res = self.context.execute_process_synchronously_without_raising(\n epr,\n self.name(),\n [WorkUnitLabel.TOOL])\n\n if res.exit_code != 0:\n raise TaskError(res.stderr, exit_code=res.exit_code)\n\n if output_dir:\n res.output_directory_digest.dump(output_dir)\n self.context._scheduler.materialize_directories((\n DirectoryToMaterialize(\n # NB the first element here is the root to materialize into, not the dir to snapshot\n text_type(get_buildroot()),\n res.output_directory_digest),\n ))\n # TODO drop a file containing the digest, named maybe output_dir.digest\n return res\n\n # The classpath is parameterized so that we can have a single nailgun instance serving all of our\n # execution requests.\n def _runtool_nonhermetic(self, parent_workunit, classpath, main, tool_name, args, distribution):\n result = self.runjava(\n classpath=classpath,\n main=main,\n jvm_options=self.get_options().jvm_options,\n args=args,\n workunit_name=tool_name,\n workunit_labels=[WorkUnitLabel.TOOL],\n dist=distribution\n )\n if result != 0:\n raise TaskError('Running {} failed'.format(tool_name))\n runjava_workunit = None\n for c in parent_workunit.children:\n if c.name is tool_name:\n runjava_workunit = c\n break\n # TODO: figure out and document when would this happen.\n if runjava_workunit is None:\n raise Exception('couldnt find work unit for underlying execution')\n return runjava_workunit\n\n def _runtool(self, main, tool_name, args, distribution,\n tgt=None, input_files=tuple(), input_digest=None, output_dir=None):\n with self.context.new_workunit(tool_name) as wu:\n return self.execution_strategy_enum.resolve_for_enum_variant({\n self.HERMETIC: lambda: self._runtool_hermetic(\n main, tool_name, args, distribution,\n tgt=tgt, input_files=input_files, input_digest=input_digest, output_dir=output_dir),\n self.SUBPROCESS: lambda: self._runtool_nonhermetic(\n wu, self.tool_classpath(tool_name), main, tool_name, args, distribution),\n self.NAILGUN: lambda: self._runtool_nonhermetic(\n wu, self._nailgunnable_combined_classpath, main, tool_name, args, distribution),\n })()\n\n _JDK_LIB_NAMES = ['rt.jar', 'dt.jar', 'jce.jar', 'tools.jar']\n\n @memoized_method\n def _jdk_libs_paths_and_digest(self, hermetic_dist):\n jdk_libs_rel, jdk_libs_globs = hermetic_dist.find_libs_path_globs(self._JDK_LIB_NAMES)\n jdk_libs_digest = self.context._scheduler.capture_snapshots(\n (jdk_libs_globs,))[0].directory_digest\n return (jdk_libs_rel, jdk_libs_digest)\n\n @memoized_method\n def _jdk_libs_abs(self, nonhermetic_dist):\n return nonhermetic_dist.find_libs(self._JDK_LIB_NAMES)\n\n def _on_invalid_compile_dependency(self, dep, compile_target, contexts):\n \"\"\"Decide whether to continue searching for invalid targets to use in the execution graph.\n\n If a necessary dep is a rsc-then-zinc dep and the root is a zinc-only one, continue to recurse\n because otherwise we'll drop the path between Zinc compile of the zinc-only target and a Zinc\n compile of a transitive rsc-then-zinc dependency.\n\n This is only an issue for graphs like J -> S1 -> S2, where J is a zinc-only target,\n S1/2 are rsc-then-zinc targets and S2 must be on the classpath to compile J successfully.\n \"\"\"\n return contexts[compile_target][0].workflow.resolve_for_enum_variant({\n 'zinc-only': lambda : contexts[dep][0].workflow == _JvmCompileWorkflowType.rsc_then_zinc,\n 'rsc-then-zinc': lambda : False\n })()\n","sub_path":"src/python/pants/backend/jvm/tasks/jvm_compile/rsc/rsc_compile.py","file_name":"rsc_compile.py","file_ext":"py","file_size_in_byte":27034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"563638148","text":"#!/usr/bin/python3\nfrom itertools import chain\nfrom collections import namedtuple\nfrom enum import Enum\nfrom utils.rule import Rule\n\n\nEMPTY_SEQUNCE = 'ε'\n\n\nclass GrammarType(Enum):\n '''Contains all possible grammar types.'''\n ZERO = 'Zero type grammar'\n CONTEXT_DEPENDENT = 'Context-dependent grammar'\n CONTEXT_FREE = 'Context-free grammar'\n REGULAR = 'Regular grammar'\n\n\nclass Grammar:\n def __init__(self, terminals, nonterminals, rules, start_symbol):\n self._terminals = terminals\n self._nonterminals = nonterminals\n self._rules = set(chain.from_iterable(Rule.parse(rule) for rule in rules))\n self._start_symbol = start_symbol\n\n validation_summary = self._validate_grammar(terminals, nonterminals, self._rules, start_symbol)\n if len(validation_summary):\n raise ValueError(\"\\n\".join(validation_summary))\n\n @property\n def terminals(self):\n return self._terminals\n\n @property\n def nonterminals(self):\n return self._nonterminals\n\n @property\n def rules(self):\n return self._rules\n\n @property\n def start_symbol(self):\n return self._start_symbol\n\n @property\n def grammar_type(self):\n \"\"\"Identify type of the given grammar. All args are iterables of strings.\"\"\"\n rule_context = (self._terminals, self._nonterminals)\n\n if all(rule.is_regular(rule_context) for rule in self._rules):\n return GrammarType.REGULAR\n elif all(rule.is_context_free(rule_context) for rule in self._rules):\n return GrammarType.CONTEXT_FREE\n elif all(rule.is_context_dependent(rule_context) for rule in self._rules):\n return GrammarType.CONTEXT_DEPENDENT\n return GrammarType.ZERO\n\n @staticmethod\n def get_grammar(data):\n terminals = set(data[\"terminals\"])\n nonterminals = set(data[\"nonterminals\"])\n rules = set(data[\"rules\"])\n start_symbol = data[\"start_symbol\"]\n return Grammar(terminals, nonterminals, rules, start_symbol)\n\n def _validate_grammar(self, terminals, nonterminals, rules, start_symbol):\n \"\"\"Validate grammar rule\"\"\"\n validation_summary = []\n\n if not terminals - {EMPTY_SEQUNCE}:\n validation_summary.append(\"No terminals specified.\")\n\n if not nonterminals - {EMPTY_SEQUNCE}:\n validation_summary.append(\"No non-terminals specified.\")\n\n common = terminals & nonterminals\n if common:\n validation_summary.append(f\"Terminals and nonterminals have common members: {common}.\")\n\n if start_symbol not in nonterminals:\n validation_summary.append(f\"Start symbol {start_symbol} is not in nonterminals {nonterminals}.\")\n\n if not rules:\n validation_summary.append(\"No rules specified.\")\n\n symbols_in_rules = set(chain.from_iterable(rule.input_symbols + rule.output_symbols for rule in rules))\n extra_symbols = (symbols_in_rules - (terminals | nonterminals | {EMPTY_SEQUNCE}))\n if extra_symbols:\n validation_summary.append(f\"Your rules contain symbols that were not specified: {extra_symbols}.\")\n\n return validation_summary\n","sub_path":"PracticalApplicationOfFiniteStateMachines/lab_5/utils/grammar.py","file_name":"grammar.py","file_ext":"py","file_size_in_byte":3188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"389938395","text":"import random as r\ni = int(input(\"Enter quantity \"))\ndef foo(a):\n if a > 0 and a < 11:\n print(a, end = ' ')\n elif a > 11:\n print(\"This value out of the range\")\nwhile i < 1000:\n i+=15\n print('i - ', i)\n a = r.randint(1,11)\n foo(a)\n","sub_path":"1/Python_13.py","file_name":"Python_13.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"523713214","text":"\"\"\"\n--------------------------------------\n date: 2018/3/20\n--------------------------------------\n Change Date: 2018/3/20\n \n\"\"\"\nfrom lib.business.mysqldb.db_business import DBBusiness\nfrom lib.entity.db_entity.db_table import DBTable\nfrom lib.entity.db_entity.mbk_db import MBKGlobalUser\n\n__author__ = \"dingbaixia@mobike.com\"\n\n\nclass MBKGlobalUserBusiness(DBBusiness):\n def __init__(self):\n super(MBKGlobalUserBusiness, self).__init__(DBTable.MBKGlobalUser)\n\n def get_global_userinfo_from_mbkglobaluser(self, user_id):\n \"\"\"\n 根据userid获取globaluserinfo\n :param user_id:\n :return:\n \"\"\"\n where = MBKGlobalUser()\n where.userId = user_id\n items = self.query_with_column(where, MBKGlobalUser.select_column)\n\n if len(items) > 1:\n raise Exception(\"获取用户membership信息出错\")\n if len(items) == 0:\n return None\n item = items[0]\n obj = MBKGlobalUser()\n obj.userId = item[0]\n obj.agreeMarketing = item[1]\n obj.meetLegalAge = item[2]\n obj.stripeCountry = item[3]\n obj.agree_to_sms = item[4]\n obj.agree_to_push = item[5]\n obj.agree_to_email = item[6]\n obj.create_time = item[7]\n obj.update_time = item[8]\n obj.agree_to_required_consent = item[9]\n\n return obj\n\n def add_globaluserinfo_record(self, user_id):\n \"\"\"\n 添加一条记录\n :param user_id:\n :return:\n \"\"\"\n obj = MBKGlobalUser()\n obj.userId = user_id\n self.add_record(obj)\n\n\n","sub_path":"mobike-api-test/lib/business/mysqldb/mbk_db/mbk_global_user_business.py","file_name":"mbk_global_user_business.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"433061720","text":"def get_pixel_color(stack):\n i = 0\n while stack[i] == 2: \n i += 1\n return stack[i]\n\n\ndef print_image(image, width, height):\n for y in range(height):\n for x in range(width):\n if image[y][x] == 1:\n print('x', end='')\n else:\n print(' ', end='')\n print('')\n\n\ndef part_one(encoded_image, width, height):\n layers = [encoded_image[i:i+width*height] \\\n for i in range(0, len(encoded_image), width*height)]\n zeros = [layer.count(0) for layer in layers]\n index = zeros.index(min(zeros))\n result = layers[index].count(1) * layers[index].count(2)\n print(result)\n\n\ndef part_two(encoded_image, width, height):\n layers = [encoded_image[i:i+width*height] \\\n for i in range(0, len(encoded_image), width*height)]\n stacks = [[layer[i] for layer in layers] for i in range(width * height)]\n colors = [get_pixel_color(stack) for stack in stacks]\n image = [colors[i:i+width] for i in range(0, len(colors), width)]\n print_image(image, 25, 6)\n\n\nif __name__ == \"__main__\":\n inputs = open('inputs/08.txt', 'r')\n encoded_image = list(map(int, inputs.read()))\n\n print(\"Part 1:\")\n part_one(encoded_image, 25, 6)\n\n print(\"Part 2:\")\n part_two(encoded_image, 25, 6)","sub_path":"08.py","file_name":"08.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"228764433","text":"import csv\nfrom .db import DB\nfrom .abstract_entity import AbstractEntity\n\nclass LegalBase(AbstractEntity):\n\n def __init__(self, institution_code):\n self._db = DB()\n self._table_name = 'api.legal_base'\n self._institution_code = institution_code\n \n def prepare(self): return #self._db.empty_table(self._table_name)\n \n def cleanup(self): self._db.complete_operations()\n\n def extract_str(self, collection, key):\n val = collection[key].strip()\n return None if (val == '' or val == '0') else val\n\n def execute(self):\n self.prepare()\n\n legis_type = { 'Ley': 'law', 'Reglamento de Ley': 'regulation', 'No Existe': 'non_existent',\n 'Acuerdo Ministerial': 'ministerial_agreement', 'Otro': 'other',\n 'Constitución': 'constitution', 'Tratado Internacional': 'international_treaty',\n 'Reglamento Técnico': 'technical_regulation', 'Decreto Ejecutivo': 'executive_order',\n 'Reglamento': 'regulation', 'Tratado': 'international_treaty', 'No existe': 'non_existent',\n 'Reglamento de ley': 'regulation', 'Reglamento Tecnico': 'technical_regulation',\n 'otro': 'other' }\n\n with open('data/'+self._institution_code+'/legal_base.csv', encoding='utf-8') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n #If not applicable there should not be a record\n if row['legislation_type'].upper()=='NO APLICA': continue\n\n mode_code = row['mode_code'].replace(' ', '')\n base_type = legis_type[row['legislation_type'].strip()]\n name = self.extract_str(row, 'legislation_name')\n reference = self.extract_str(row, 'legislation_name')\n topic = self.extract_str(row, 'legal_topic')\n\n qs = 'INSERT INTO ' + self._table_name\n qs += '(mode_id, type, legislation_name, legislation_reference, '\n qs += 'legal_topic_id)'\n qs += 'VALUES ((SELECT id FROM api.modes WHERE code=%s), %s, %s, %s, '\n qs += '(SELECT id FROM api.legal_topics WHERE UPPER(name)=UPPER(%s)))'\n values = (mode_code, base_type, name, reference,\n topic)\n self._db.create_record(qs, values)\n\n self.cleanup()\n","sub_path":"entities/legal_base.py","file_name":"legal_base.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"414958567","text":"# -*- coding: utf-8 -*-\nfrom setuptools import setup,Extension\nimport sys\nsys.path.append('./src')\nsys.path.append('./test')\nversion = file('VERSION').read().strip()\n\nsetup(name='pyccv',\n version=version,\n description=\"Calculate color coherence vector for similar image search\",\n long_description=file('README').read(),\n classifiers=[],\n keywords=('image-processing computer-vision'),\n author='Shunsuke Aihara',\n author_email='s.aihara@gmail.com',\n url='http://www.bitbucket.org/aihara/pyccv',\n license='MIT License',\n package_dir={'': 'src'},\n packages=['pyccv'],\n ext_modules=[\n Extension(\n 'pyccv._ccv', [\n 'ccv/ccv.cpp',\n ],\n include_dirs=['ccv'],\n extra_compile_args=[],\n ),\n ],\n install_requires=[\"numpy\",\"scipy\",\"PIL\"],\n test_suite = 'test_ccv.suite'\n )\n","sub_path":"pypi_install_script/pyccv-0.08.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"156408145","text":"import pyrebase\nimport time\nimport random\n\nfirebaseconfig = {\n \"apiKey\": \"AIzaSyAFuyR4uVduD9EX20IzFPbeXa8U0VxaeYQ\",\n \"authDomain\": \"relayproject-76dc2.firebaseapp.com\",\n \"databaseURL\": \"https://relayproject-76dc2.firebaseio.com\",\n \"storageBucket\": \"relayproject-76dc2.appspot.com\"\n}\n\n\ndef notifyproc(relayid, uid):\n db = pyrebase.initialize_app(firebaseconfig).database()\n relaytitle = db.child(\"relays\").child(relayid).child(\"title\").get().val()\n username = db.child(\"users\").child(uid).child(\"member\").child(\"dispname\").get().val()\n pushmsg = \"%s님이 %s 캠페인의 릴레이에 회원님을 태그했습니다.\" % (username, relaytitle)\n deviceid = db.child('users').child(uid).child('member').child('deviceid').get().val()\n cur_usertagged = db.child(\"users\").child(uid).child(\"relayinfo\").child(\"tagged\").get().val()\n if cur_usertagged is not None:\n db.child(\"users\").child(uid).child(\"relayinfo\").child(\"tagged\").set(cur_usertagged + \",\" + relayid)\n else:\n db.child(\"users\").child(uid).child(\"relayinfo\").child(\"tagged\").set(relayid)\n\n # TODO: Request pushmsg&deviceid in push service\n\n\ndef addrelay(uid, title, content, multitype, multiuri, tag):\n db = pyrebase.initialize_app(firebaseconfig).database()\n relayid = str(int(time.time())) + str(random.randint(0, 99)).zfill(2)\n response_data = {}\n relayset = {\n \"title\": title,\n \"start\": str(int(time.time())),\n \"content\": content,\n \"multitype\": multitype,\n \"multiuri\": multiuri,\n \"uid\": uid,\n \"tag\": tag,\n \"likes\": 0\n }\n db.child(\"relays\").child(relayid).set(relayset)\n cur_userup = db.child(\"users\").child(uid).child(\"relayinfo\").child(\"uploaded\").get().val()\n if cur_userup is not None:\n db.child(\"users\").child(uid).child(\"relayinfo\").child(\"uploaded\").set(cur_userup + \",\" + relayid)\n else:\n db.child(\"users\").child(uid).child(\"relayinfo\").child(\"uploaded\").set(relayid)\n tagged_target = tag.split(\",\")\n if len(tagged_target) < 1:\n response_data = {\n \"result\": False\n }\n else:\n for t in tagged_target:\n notifyproc(relayid, t)\n response_data = {\n \"result\": True,\n \"relayid\": relayid\n }\n return response_data\n\n\ndef detailrelay(relayid):\n db = pyrebase.initialize_app(firebaseconfig).database()\n relaydata = db.child(\"relays\").child(relayid).get().val()\n userprofile = getprofile(relaydata[\"uid\"])\n relaycnt = len(relaydata[\"relaycontent\"]) if \"relaycontent\" in relaydata.keys() else 0\n response_data = {\n \"result\": True,\n \"title\": relaydata[\"title\"],\n \"start\": relaydata[\"start\"],\n \"content\": relaydata[\"content\"],\n \"multitype\": relaydata[\"multitype\"],\n \"multiuri\": relaydata[\"multiuri\"],\n \"uid\": relaydata[\"uid\"],\n \"dispname\": userprofile[\"dispname\"],\n \"imgexist\": userprofile[\"imgexist\"],\n \"profileimg\": userprofile[\"profileimg\"],\n \"tag\": relaydata[\"tag\"],\n \"likes\": relaydata[\"likes\"],\n \"relayed\": relaycnt\n }\n return response_data\n\n\ndef joinrelay(uid, relayid, content, multitype, multiuri, tag):\n db = pyrebase.initialize_app(firebaseconfig).database()\n response_data = {}\n relayset = {\n \"uid\": uid,\n \"content\": content,\n \"multitype\": multitype,\n \"multiuri\": multiuri,\n \"tag\": tag\n }\n db.child(\"relays\").child(relayid).child(\"relaycontent\").child(str(int(time.time()))).set(relayset)\n cur_userjoin = db.child(\"users\").child(uid).child(\"relayinfo\").child(\"joined\").get().val()\n if cur_userjoin is not None:\n db.child(\"users\").child(uid).child(\"relayinfo\").child(\"joined\").set(cur_userjoin + \",\" + relayid)\n else:\n db.child(\"users\").child(uid).child(\"relayinfo\").child(\"joined\").set(relayid)\n\n tagged_target = tag.split(\",\")\n if len(tagged_target) < 1:\n response_data = {\n \"result\": False\n }\n else:\n for t in tagged_target:\n notifyproc(relayid, t)\n response_data = {\n \"result\": True\n }\n return response_data\n\n\ndef listrelay():\n db = pyrebase.initialize_app(firebaseconfig).database()\n all_relays = db.child(\"relays\").get()\n response_data = {\"result\": True, \"relays\": []}\n for relayitem in all_relays.each():\n itemset = {}\n itemdata = relayitem.val()\n userdata = getprofile(itemdata['uid'])\n itemset[\"rid\"] = relayitem.key()\n itemset[\"title\"] = itemdata[\"title\"]\n itemset[\"uid\"] = itemdata[\"uid\"]\n itemset[\"dispname\"] = userdata[\"dispname\"]\n itemset[\"imgexist\"] = userdata[\"imgexist\"]\n itemset[\"profileimg\"] = userdata[\"profileimg\"]\n itemset[\"multitype\"] = itemdata[\"multitype\"]\n itemset[\"multiuri\"] = itemdata[\"multiuri\"]\n itemset[\"likes\"] = itemdata[\"likes\"]\n if \"relaycontent\" in itemdata.keys():\n itemset[\"relayed\"] = len(itemdata[\"relaycontent\"])\n else:\n itemset[\"relayed\"] = 0\n response_data[\"relays\"].append(itemset)\n return response_data\n\n\ndef hotrelay():\n db = pyrebase.initialize_app(firebaseconfig).database()\n all_relays = db.child(\"relays\").get()\n response_data = {\"result\": True, \"relays\": []}\n for relayitem in all_relays.each():\n itemset = {}\n itemdata = relayitem.val()\n userdata = getprofile(itemdata['uid'])\n itemset[\"rid\"] = relayitem.key()\n itemset[\"title\"] = itemdata[\"title\"]\n itemset[\"uid\"] = itemdata[\"uid\"]\n itemset[\"dispname\"] = userdata[\"dispname\"]\n itemset[\"imgexist\"] = userdata[\"imgexist\"]\n itemset[\"profileimg\"] = userdata[\"profileimg\"]\n itemset[\"multitype\"] = itemdata[\"multitype\"]\n itemset[\"multiuri\"] = itemdata[\"multiuri\"]\n itemset[\"likes\"] = itemdata[\"likes\"]\n if \"relaycontent\" in itemdata.keys():\n itemset[\"relayed\"] = len(itemdata[\"relaycontent\"])\n else:\n itemset[\"relayed\"] = 0\n response_data[\"relays\"].append(itemset)\n templist = sorted(response_data[\"relays\"], key=lambda k: k['likes'])\n response_data[\"relays\"] = templist[len(response_data['relays'])-3:len(response_data['relays'])]\n response_data[\"relays\"].reverse()\n return response_data\n\n\ndef setdevice(uid, dispname, deviceid):\n db = pyrebase.initialize_app(firebaseconfig).database()\n db.child(\"users\").child(uid).child(\"member\").child(\"deviceid\").set(deviceid)\n db.child(\"users\").child(uid).child(\"member\").child(\"dispname\").set(dispname)\n response_data = {\n \"result\": True\n }\n return response_data\n\n\ndef getprofile(uid):\n db = pyrebase.initialize_app(firebaseconfig).database()\n memberdata = db.child(\"users\").child(uid).child(\"member\").get().val()\n profileexist = False\n if \"profileuri\" in memberdata.keys():\n profileexist = True\n response_data = {\n \"result\": True,\n \"imgexist\": profileexist,\n \"profileimg\": memberdata[\"profileuri\"] if profileexist else None,\n \"dispname\": memberdata[\"dispname\"]\n }\n return response_data\n\n\ndef setprofile(uid, profileimg):\n db = pyrebase.initialize_app(firebaseconfig).database()\n db.child(\"users\").child(uid).child(\"member\").child(\"profileuri\").set(profileimg)\n response_data = {\n \"result\": True\n }\n return response_data\n\n\ndef friendlist(uid):\n print(uid)\n db = pyrebase.initialize_app(firebaseconfig).database()\n all_friend = db.child(\"users\").child(uid).child(\"member\").child(\"friends\").get().val()\n friendlist = all_friend.split(\",\")\n response_data = {\"friends\": []}\n for frienditem in friendlist():\n itemset = {}\n userdata = getprofile(frienditem)\n itemset['uid'] = frienditem\n itemset['imgexist'] = userdata['imgexist']\n itemset['profileimg'] = userdata['profileimg']\n itemset['dispname'] = userdata['dispname']\n response_data[\"friends\"].append(itemset)\n return response_data\n","sub_path":"relayapi.py","file_name":"relayapi.py","file_ext":"py","file_size_in_byte":8055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"471321660","text":"\"\"\"\nAcquire DOIs of citation papers\n\"\"\"\nimport re\nimport os\nimport pymongo\n\n\ndef file_list(path):\n \"\"\"\n Get the list of file names in one folder\n \"\"\"\n files = []\n for file in os.listdir(path):\n files.append(path+\"\\\\\"+file)\n return files\n\n\ndef doi_find(collection,file,num):\n \"\"\"\n Extract the DOI of citations with the information file downloaded in WoS\n \"\"\"\n f = open(file,'r', encoding='UTF-8')\n for line in f:\n g = re.search(\"(?<=DI )10\\.([0-9]{4}).*\", line)\n if g:\n doi_dic = {\"cited_no\": int(re.findall('\\((.*?)\\)', file)[0]) + num, \"doi_link\": str(g.group())}\n if not collection.find_one(doi_dic):\n collection.insert_one(doi_dic)\n f.close()\n\n\ndef doi_find_highpaper(collection,file,num):\n \"\"\"\n Extract the titles of highly-cited papers with the information file downloaded in WoS\n \"\"\"\n with open(file, 'r', encoding='UTF-8') as f:\n f = f.readlines()\n i = 0\n for line in f:\n y = re.search(\"(?<=^PY ).*$\", line)\n t = re.search(\"(?<=^TI ).*$\", line)\n if t:\n if(f[i+1].startswith('SO')):\n title = t.group()\n else:\n title = t.group() + f[i+1].replace('\\n', '') .replace(' ', '')\n num = num + 1\n collection.update_many({'cited_no': num}, {'$set': {'cited_title': title}})\n if y:\n year = y.group() \n collection.update_many({'cited_no': num}, {'$set': {'cited_year': int(year)}})\n i = i + 1 \n\n\ndef main_function(i):\n \"\"\"\n Main function\n \"\"\"\n client = pymongo.MongoClient('localhost:27017', connect=True)\n db = client['msc_project']\n collection = db['citations'] \n files = file_list(\"WOS_list\\\\\"+str(i))\n num = (i-1)*10\n for file in files:\n if \"(\" in file and \")\" in file:\n doi_find(collection, file, num)\n else:\n doi_find_highpaper(collection, file, num)\n client.close()\n\n\n'''\nSeveral Iterations for Main function\n'''\nfor i in range(1,12):\n main_function(i)\n\n\n\n","sub_path":"1_doi_acquire.py","file_name":"1_doi_acquire.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"495953070","text":"import apache_beam as beam\nfrom apache_beam.options import pipeline_options\nfrom apache_beam.options.pipeline_options import GoogleCloudOptions\nfrom apache_beam.runners import DataflowRunner\n\nimport google.auth\nfrom datetime import datetime, timedelta\nimport json\nimport numpy\nimport csv\nimport logging\nlogging.getLogger().setLevel(logging.INFO)\n\n# Setting up the Apache Beam pipeline options.\noptions = pipeline_options.PipelineOptions(flags=['--streaming'])\n\noptions.view_as(pipeline_options.StandardOptions).streaming = True\n_, options.view_as(GoogleCloudOptions).project = google.auth.default()\n\noptions.view_as(GoogleCloudOptions).region = 'us-west1'\noptions.view_as(\n GoogleCloudOptions).staging_location = 'gs://samhitha-dataflow/staging'\noptions.view_as(\n GoogleCloudOptions).temp_location = 'gs://samhitha-dataflow/temp'\noptions.view_as(GoogleCloudOptions).job_name = 'Vaccination_Progress'\n \n \nclass CollectLocationKey(beam.DoFn):\n def process(self, element):\n if element is None:\n return element\n return [(element['Country'], float(element['Daily_vaccinations']) if element['Daily_vaccinations'] else 0.0 )]\n \n \n\n \n\n \ndef addKey(row):\n return (1, row)\n\ndef sortGroupedData(row):\n (keyNumber, sortData) = row\n sortData.sort(key=lambda x: x['total_vaccines'], reverse=True)\n sortData_t10 = sortData[0:10]\n sortData_t10 = [dict(d, **{\"rank\":i+1}) for i,d in enumerate(sortData_t10)]\n return sortData_t10\n\n#FUNCTION FOR TOP VACCINES IN THE WORLD \n \nclass CollectLocationKey_Vaccines(beam.DoFn):\n def process(self, element):\n if element is None:\n return element\n return [(element['Country'],element['Vaccines'], float(element['Total_vaccinations']) if element['Total_vaccinations'] else 0.0 )]\n\n\n\ndef addKey_vaccines(row):\n return (1, row)\n\ndef sortGroupedData_vaccines(row):\n (keyNumber, sortData) = row\n sortData.sort(key=lambda x: x['country_count'], reverse=True)\n sortData_t10 = sortData[0:10]\n sortData_t10 = [dict(d, **{\"rank\":i+1}) for i,d in enumerate(sortData_t10)]\n return sortData_t10\n\n \n \n \n# DATA CLEANING FUNCTIONS \n \ndef replace_cols(data):\n \"\"\"replace with 0\"\"\"\n from datetime import date\n data_dict = {}\n if data is None or 'country' in data :\n return None\n \n data_dict['Country'] = data[0] if data[0] else None\n data_dict['iso_code'] = data[1] if data[1] else 'unknown'\n \n #print (data)\n ( year, month,day) = data[2].split('-')\n data_dict['Date'] = date(month=int(month), day=int(\n day), year=int(year)) \n data_dict['Total_vaccinations'] = float(data[3]) if data[3] != '' else 0\n data_dict['People_vaccinated'] = int(float(data[4])) if len(data[4]) > 0 else 0\n data_dict['People_fully_vaccinated'] = int(float(data[5])) if data[5] else 0\n\n data_dict['Daily_vaccinations_raw'] = int(float(data[6])) if data[6] else 0\n data_dict['Daily_vaccinations'] = int(float(data[7])) if data[7] else 0\n data_dict['Total_vaccinations_per_hundred'] = float(data[8]) if data[8] else 0\n\n data_dict['People_vaccinated_per_hundred'] = float(\n data[9]) if data[9] else 0\n data_dict['People_fully_vaccinated_per_hundred'] = float(\n data[10]) if data[10] else 0\n data_dict['Daily_vaccinations_per_million'] = float(\n data[11]) if data[11] else 0\n\n data_dict['Vaccines'] = data[12] if data[12] else 'unknown'\n data_dict['Source_name'] = data[13] if data[13] else 'unknown'\n data_dict['Source_website'] = data[14] if data[14] else 'unknown'\n #print (data_dict)\n return data_dict\n\ndef del_unwanted_cols(data):\n \"\"\"Deleting unwanted columns\"\"\"\n if data is None :\n return None\n del data['Source_name']\n del data['Source_website']\n return data\n\n\ndef format_data_old(data):\n if data is None:\n return None\n\n data['Date'] = \"{:%Y-%m-%d}\".format(data['Date'])\n return data\n\n\ndef format_stat_data(data):\n if data is None:\n return None\n d_dict = {}\n d_dict['Country'] = data[0]\n d_dict['Max_Total_Vaccination'] = data[1][0][0][0]\n d_dict['Total_Vaccination_LastDate'] = \"{:%Y-%m-%d}\".format(data[1][0][0][1])\n d_dict['Max_People_Vaccinated'] = data[1][1][0][0]\n d_dict['People_Vaccinated_LastDate'] = \"{:%Y-%m-%d}\".format(data[1][1][0][1])\n d_dict['Max_People_fully_vaccinated'] = data[1][2][0][0]\n d_dict['People_fully_vaccinated_LastDate'] = \"{:%Y-%m-%d}\".format(\n data[1][2][0][1])\n return d_dict\n\n\n\ndef filter_out_nones(row):\n if row is not None:\n yield row\n else:\n \n pass \n\ndef print_output(line):\n logging.info(\"Output \"+str(line))\n return line\n\ndef print_output2(line):\n logging.info(\"Output2 \"+str(line))\n return line\n\ndef print_ple_vac(line):\n logging.info(\"print_ple_vac \"+str(line))\n return line\n\ndef print_mapa(line):\n logging.error(\"Map after \"+str(line))\n return line\n\n\ndef print_mapb(line):\n logging.error(\"Map before \"+str(line))\n return line\n\n\n\n\ndef read_from_file(line):\n import csv\n x = None\n try:\n\n x = next(csv.reader([line]))\n except Exception as e:\n logging.error(line)\n logging.error(str(e))\n return x\n \n \n \n\n \n#Batch Data Topic\nbatch_topic = \"projects/samhitha-data228-project/topics/vaccines_batch_in\"\n\n\n#Streaming Data Topic\nstreaming_topic = \"projects/samhitha-data228-project/topics/my-dataflow-topic1\"\n#processing streaming pipeline\n\n\nwith beam.Pipeline(options=options) as pipeline:\n\n batch_data = (pipeline\n |\"Read_Batch_Data\" >> beam.io.ReadFromPubSub(topic=batch_topic)\n | \"Window_Batch\" >> beam.WindowInto(beam.window.FixedWindows(600))\n |\"Convert_To_Dict\" >> beam.Map(lambda x: json.loads(x))\n |\"Extract_File\" >> beam.Map(lambda x : 'gs://{}/{}'.format(x['bucket'], x['filename']))\n |\"Read_File\" >> beam.io.ReadAllFromText()\n \n )\n\n data = pipeline | \"Read_Stream_Data\" >> beam.io.ReadFromPubSub(topic=streaming_topic)\n windowed_data = (data | \"Window_Stream\" >> beam.WindowInto(beam.window.FixedWindows(600)))\n streaming_data = (windowed_data|\"Decode_Data\" >> beam.Map(lambda x: x.decode(\"utf-8\"))\n\n ) \n \n \n merge_data = (batch_data, streaming_data) | \"Merge_Data\" >> beam.Flatten()\n \n csv_formatted_data = (\n merge_data\n | \"Read_Line\" >> beam.Map(read_from_file)\n | \"Replace_Columns\">>beam.Map(replace_cols)\n | \"DelUnwantedData\" >> beam.Map(del_unwanted_cols)\n | \"Filter_Nones\" >> beam.ParDo(filter_out_nones)\n #|beam.Map(print)\n\n )\n \n \n \n \n grouped_by_country = (csv_formatted_data\n | \"CollectingCountryKey\" >> beam.ParDo(CollectLocationKey())\n | \"GroupingByCountry\" >> beam.GroupByKey()\n #|beam.Map(print)\n )\n \n \n\n\n # Which country Vaccinating more people?\n\n Total_vaccinations = (grouped_by_country\n | \"ExtractTotalVaccinations\" >> beam.Map(lambda x : {'country':x[0], 'total_vaccines':sum(x[1])})\n )\n\n\n\n Top_10_country_vaccinations = (Total_vaccinations\n | 'AddKey' >> beam.Map(addKey)\n | 'GroupByKey' >> beam.GroupByKey()\n | 'SortGroupedData' >> beam.Map(sortGroupedData)\n # |beam.Map(print)\n )\n\n \n \n output = ( Top_10_country_vaccinations\n | \"Output1 \" >> beam.Map(print_output)\n\n )\n \n\n# Most Popular Vaccine in the world?\n\n Top_Vaccines_data = (csv_formatted_data \n | \"CombineColumns\" >> beam.ParDo(CollectLocationKey_Vaccines())\n )\n \n\n Top_Vaccines_country = (Top_Vaccines_data\n | \"CollectColumns\" >> beam.Map(lambda x: (x[1] , x[0]))\n | \"GroupingByCountry_vaccine\" >> beam.GroupByKey()\n |beam.Map(lambda x: {'Vaccine':x[0] , 'country_count':len(set(x[1]))})\n \n |\"SortedValues\" >>beam.Map(addKey_vaccines)\n | \"GroupByKeyTotalVaccinations\" >> beam.GroupByKey()\n | \"SortGroupedDataVaccines\" >> beam.Map(sortGroupedData_vaccines)\n \n )\n\n # output = ( Top_Vaccines_country\n # | \"Output2 \" >> beam.Map(print_output)\n\n # )\n\n Total_vaccinations_max = (\n csv_formatted_data\n\n | \"FormingVacninationsDate\" >> beam.Map(lambda elem: (elem['Country'], (elem['Total_vaccinations_per_hundred'], elem['Date'])))\n #| \"PrintMapb\" >> beam.Map(print_mapb)\n | \"MaxTotalVaccination\" >> beam.GroupByKey()\n #| \"Print mapa\" >> beam.Map(print_mapa)\n | \"MapGroupedData1\" >> beam.Map(lambda elem: (elem[0], max(elem[1])))\n #|beam.Map(print)\n )\n \n People_vaccinated_max = (\n csv_formatted_data\n | \"FormingPeopleVacninationsDate\" >>beam.Map(lambda elem: (elem['Country'], (elem['People_vaccinated_per_hundred'], elem['Date'])))\n #|beam.Map(print)\n | \"MaxPeopleVaccinated\" >> beam.GroupByKey()\n\n | \"MapGroupedData2\" >> beam.Map(lambda elem: (elem[0], max(elem[1])))\n #|beam.Map(print)\n )\n \n People_fully_vaccinated_max = (\n csv_formatted_data\n | \"FormingPeopleFullyVacninationsDate\" >> beam.Map(lambda elem: (elem['Country'], (elem['People_fully_vaccinated_per_hundred'], elem['Date'])))\n #|beam.Map(print)\n | \"Max PeopleFullyVaccinated\" >> beam.GroupByKey()\n | \"MapGroupedData3\" >> beam.Map(lambda elem: (elem[0], max(elem[1])))\n #|beam.Map(print)\n )\n\n #output2 = (\n # Total_vaccinations_max | \"Output3 \" >> beam.Map(print_output2)\n\n #)\n \n \n agg = ((Total_vaccinations_max, People_vaccinated_max, People_fully_vaccinated_max)\n | \"CombineData\" >> beam.CoGroupByKey()\n | \"FormatData\" >> beam.Map(format_stat_data)\n #|beam.Map(print)\n )\n\n \n events = (csv_formatted_data \n | \"FormatToBigquery\" >> beam.Map(lambda x: {\"country\": x['Country'],\"iso_code\": x['iso_code'],\"date\": x['Date'].isoformat(),\"total_vaccinations\": x['Total_vaccinations'], \"people_vaccinated\": x['People_vaccinated']\n , \"people_fully_vaccinated\":x['People_fully_vaccinated'] , \"daily_vaccinations_raw\" :x['Daily_vaccinations_raw'],\n \"daily_vaccinations\": x[\"Daily_vaccinations\"],\"total_vaccinations_per_hundred\" : x['Total_vaccinations_per_hundred'],\n \"people_vaccinated_per_hundred\":x['People_vaccinated_per_hundred'],\"people_fully_vaccinated_per_hundred\":x['People_fully_vaccinated_per_hundred'],\n \"daily_vaccinations_per_million\":x['Daily_vaccinations_per_million'],\"vaccines\":x['Vaccines']})\n \n | \"WriteAllDataToBigQuery\" >> beam.io.WriteToBigQuery(\"samhitha-data228-project:Vaccine_Dataset.vaccine_format\", write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND)\n )\n\n \n \n Top_country_vaccinations = ( Top_10_country_vaccinations \n | 'FlatCountlists' >> beam.FlatMap(lambda elements: elements) \n | \"WriteTopCountryBigQuery\" >> beam.io.WriteToBigQuery(\"samhitha-data228-project:Vaccine_Dataset.topcountry\", write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND)\n )\n \n \n Top_vaccine = ( Top_Vaccines_country \n | 'Flatten lists' >> beam.FlatMap(lambda elements: elements) \n | \"WriteTopVaccine BigQuery\" >> beam.io.WriteToBigQuery(\"samhitha-data228-project:Vaccine_Dataset.topvaccine\", write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND)\n )\n\n\n \n (agg\n | \"Write all data to BigQuery\" >> beam.io.WriteToBigQuery(\"samhitha-data228-project:Vaccine_Dataset.vaccinationtrend\", write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND))\n\n \n \n \n \n DataflowRunner().run_pipeline(pipeline, options=options)\n\n\n \n \n\n\n \n\n\n \n","sub_path":"vpipeline_test.py","file_name":"vpipeline_test.py","file_ext":"py","file_size_in_byte":13186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"541573670","text":"import serial\nimport time\nfrom KeyPressHandler import KeyPressHandler\nfrom KeyCodesParser import KeyCodesParser\n\nport = '/dev/tty.wchusbserial1d1110'\narduinoSerial = serial.Serial(port, 9600, timeout=0)\n\nkeyCodesParser = KeyCodesParser()\nhandler = KeyPressHandler()\n\nwhile 1:\n try:\n code = arduinoSerial.readline()\n keyName = keyCodesParser.getKeyName(code)\n handler.handle(keyName)\n except Exception as e:\n print(str(e))\n\n time.sleep(1)\n\narduinoSerial.close()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"524166177","text":"from polynomial_regression import PolynomialRegression\nimport random\nimport numpy as np # numpy is used only for test data generation\nimport assignment_dataset as Dataset\n\ndef getPredictions(coefficients, independent):\n predictionList = []\n \n for sampleIndex in range(len(independent)):\n prediction = 0\n for index in range(len(coefficients)):\n prediction = prediction + coefficients[index] * pow(independent[sampleIndex], index)\n predictionList.append(prediction)\n return predictionList\n\ndef generateDataSet(coefficient=[], addError=False):\n independentList = np.arange(0, 50, 1.5)\n dependentList = []\n for value in independentList:\n dependent = 0\n for index in range(len(coefficient)):\n dependent = dependent + coefficient[index] * pow(value, index)\n if addError:\n dependent = dependent + random.randint(-100, 100)\n dependentList.append(dependent)\n \n return independentList, dependentList\n\ndef fitLineAndPlot(independentList, dependentList, plt, order=1):\n regression = PolynomialRegression(order)\n coefficient = regression.fit(independentList, dependentList)\n print('Coefficients for order %d' % order, coefficient)\n predictionList = getPredictions(coefficient, independentList)\n plt.plot(independentList, predictionList, label='Order-%d' % order, linewidth=3)\n plt.legend()\n \ndef drawScatterPlot(independentList, dependentList, plt):\n plt.scatter(independentList, dependentList, s=100)\n \ndef getAssignmentDataset():\n return Dataset.assignmentIndependentList, Dataset.assignmentDependentList\n ","sub_path":"test_lib.py","file_name":"test_lib.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"91241250","text":"import re\nfrom collections import namedtuple\n\n\nclass Sentence:\n\n def __init__(self, sentence):\n self._original = sentence.lstrip()\n self._clean = None # A lowercase copy of \"original\" with commas removed\n self._word_count = None # Number of words in this sentence\n self._word_list = None # List of words in this sentence\n self._word_set = None # Set of words in this sentence\n\n @property\n def original(self):\n return self._original\n\n @property\n def clean(self):\n if self._clean is None:\n self._clean = self.original.replace(\",\", \"\").lower() # Remove commas, make lower case\n\n return self._clean\n\n # Returns the number of words in this sentence\n @property\n def word_count(self):\n if self._word_count is None:\n self._word_count = len(self.word_list)\n\n return self._word_count\n\n # Returns a list of the words in this sentence\n @property\n def word_list(self):\n if self._word_list is None:\n self._word_list = self.clean.split(\" \")\n\n return self._word_list\n\n # Returns a set of the words in this sentence\n @property\n def word_set(self):\n if self._word_set is None:\n self._word_set = set(self.word_list)\n\n return self._word_set\n\n # Returns True if the two compared sentence strings are identical, False otherwise\n def is_identical_to(self, other_sentence):\n return self.clean == other_sentence.clean\n\n # Returns list of String(s) if the two compared sentence strings are similar, None otherwise\n def get_similarity_to(self, other_sentence, similarity_count):\n\n if self.word_count <= other_sentence.word_count: # Use the shorter of the two sentences\n sentence_a = self\n sentence_b = other_sentence\n else:\n sentence_a = other_sentence\n sentence_b = self\n\n similarities = []\n\n words_in_common = [word for word in sentence_a.word_list if word in sentence_b.clean]\n if len(words_in_common) < similarity_count:\n return None\n\n start_index = 0\n end_index = start_index + similarity_count\n\n while start_index < len(words_in_common) - similarity_count:\n substring = \" \".join(words_in_common[start_index:end_index])\n\n if substring not in sentence_b.clean:\n start_index += 1\n end_index += 1\n continue\n else:\n while end_index <= len(words_in_common):\n if end_index < len(words_in_common):\n if substring + \" \" + words_in_common[end_index] in sentence_b.clean:\n substring += \" \" + words_in_common[end_index]\n end_index += 1\n else:\n similarities.append(substring)\n start_index = end_index\n end_index = start_index + similarity_count\n break\n else:\n similarities.append(substring)\n return similarities\n\n return similarities if len(similarities) > 0 else None\n\n\n# Returns a list of sentences from the given text\ndef sentence_list_from_text(text):\n # Would like to retain delimiter, i.e. \".\", \"!\", \"?\"\n # Don't append empty strings\n return [Sentence(sentence) for sentence in re.split('[.!?]', text) if len(sentence) >= 1]\n\n\n# Prints out the list of sentences\ndef print_sentences(sentence_list):\n print()\n for sentence_index, sentence in enumerate(sentence_list):\n print(\"Sentence[{}]: {}\".format(sentence_index, sentence_list[sentence_index].original))\n\n\n# Prints out statistics pertaining to the list of sentences\ndef print_statistics(sentence_list):\n longest_sentence = sentence_list[0].word_count\n shortest_sentence = longest_sentence\n\n word_count = 0\n for sentence in sentence_list:\n sentence_length = sentence.word_count\n word_count += sentence_length\n\n if sentence_length > longest_sentence:\n longest_sentence = sentence_length\n elif sentence_length < shortest_sentence:\n shortest_sentence = sentence_length\n\n print()\n print(\" STATISTICS\")\n print(\"______________________________\")\n print(\" sentence_count: {}\".format(len(sentence_list)))\n print(\"average words per sentence: {}\".format(round(word_count / len(sentence_list), 0)))\n print(\" longest_sentence: {} (words)\".format(longest_sentence))\n print(\" shortest_sentence: {} (words)\".format(shortest_sentence))\n print(\"______________________________\")\n\n\ndef print_similarity(similarity_label, sentence_a_index, sentence_b_index, sentence_a, sentence_b, similarity=None):\n print(\"________________________________________________\")\n if similarity is None:\n print(\"{}:\".format(similarity_label))\n else:\n print(\"{}:\".format(similarity_label), end=\" \")\n for index, substring in enumerate(similarity):\n print(\"\\\"{}\\\"\".format(substring), end=\"\")\n if index < len(similarity) - 1:\n print(\", \", end=\"\")\n print()\n\n print(\"Sentence[{}]: {}\".format(sentence_a_index, sentence_a))\n print(\"Sentence[{}]: {}\".format(sentence_b_index, sentence_b))\n\n\ndef print_comparison_info(sentence_list, comparison_list):\n orig_num_compares = len(sentence_list) ** 2\n percent_reduction = round(100 - (len(comparison_list) / orig_num_compares * 100))\n compare_info = \"Number of comparisons reduced from: {} to: {} ({}% reduction)\"\n print(compare_info.format(orig_num_compares, len(comparison_list), percent_reduction))\n\n\n# Compares the sentences in the sentence list and prints out if they are \"identical\" or \"similar\"\ndef compare_sentences(sentence_list, comparison_list, similarity_count):\n for (sentence_a_index, sentence_b_index) in comparison_list:\n sentence_a = sentence_list[sentence_a_index]\n sentence_b = sentence_list[sentence_b_index]\n\n if sentence_a.is_identical_to(sentence_b):\n print_similarity(\"Identical\", sentence_a_index, sentence_b_index, sentence_a.original,\n sentence_b.original)\n else:\n similarity = sentence_a.get_similarity_to(sentence_b, similarity_count)\n if similarity is not None:\n print_similarity(\"Similarity\", sentence_a_index, sentence_b_index, sentence_a.original,\n sentence_b.original, similarity)\n\n\nSentenceIndexPair = namedtuple(\"SentenceIndexPair\", \"sentence_a_index sentence_b_index\") # Declare named tuple\n\n\n# Creates a list of tuples of sentence indexes to compare, to reduce the number of comparisons\ndef generate_comparison_list(sentence_list):\n word_dict = {}\n\n # Create a dictionary of all words\n # The key is the word and the value is a set of sentence indexes in which the word occurs\n for sentence_index, sentence in enumerate(sentence_list):\n for word in sentence.word_list:\n word_dict.setdefault(word, set()).add(sentence_index)\n\n # Create a set of tuples containing pairs of sentence indexes to compare\n comparison_set = set() # Use a set to eliminate duplicates\n for sentence_indexes in word_dict.values():\n if len(sentence_indexes) > 1:\n sentence_indexes = sorted(sentence_indexes) # sentence_indexes set becomes a sorted list here\n\n for sentence_a_index in range(len(sentence_indexes) - 1):\n for sentence_b_index in range(sentence_a_index + 1, len(sentence_indexes)):\n comparison_set.add(SentenceIndexPair(sentence_a_index=sentence_indexes[sentence_a_index],\n sentence_b_index=sentence_indexes[sentence_b_index]))\n\n comparison_list = sorted(comparison_set)\n\n print_comparison_info(sentence_list, comparison_list)\n\n return comparison_list\n\n\nSIMILARITY_COUNT = 3 # The minimum number of consecutive words matching to be considered \"similar\"\n\n\ndef main():\n with open('TestFile_01.txt', 'r') as test_file:\n file_text = test_file.read().replace('\\n', '')\n\n sentence_list = sentence_list_from_text(file_text)\n print_sentences(sentence_list)\n print_statistics(sentence_list)\n comparison_list = generate_comparison_list(sentence_list)\n compare_sentences(sentence_list, comparison_list, SIMILARITY_COUNT)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"sentences.py","file_name":"sentences.py","file_ext":"py","file_size_in_byte":8579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"636835686","text":"import copy\nfrom Tictactoe_Env import tictactoe\nfrom Agent import AIagent_RL, AIagent_Base, Human_agent\n\nenv = tictactoe()\nagent1 = AIagent_RL(restore=True)\nagent2 = Human_agent()\n\n\ndef play():\n done = 0\n winner = 0\n env.reset()\n state = copy.copy(env.state)\n\n i = 0\n while not done:\n i += 1\n turn = copy.copy(env.turn)\n if i % 2 == 1:\n action = agent1.policy(state, turn, epsilon=0)\n else:\n action = agent2.policy(state, turn, epsilon=0)\n next_state, done, reward, winner = env.step(action)\n state = copy.copy(next_state)\n env.render()\n\n if winner == 0:\n print(\"Draw!\")\n else:\n print(\"Winner is agent %d!\" % winner)\n\n\nif __name__ == \"__main__\":\n play()\n","sub_path":"Play.py","file_name":"Play.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"634659284","text":"\n\nfrom os.path import expanduser, join\n\n\n\nimport sys\nprint(sys.path)\n#sys.path.remove('/usr/local/lib/python3.7/site-packages')\nsys.path.append('/usr/local/.pyenv/versions/3.6.0/lib/python3.6/site-packages')\nsys.path.append('/Users/kazuya_yufune/.pyenv/versions/3.6.0/lib/python3.6/site-packages')\n\nimport time\n\nfrom nnmnkwii.datasets import FileDataSource, FileSourceDataset\nfrom nnmnkwii.datasets import PaddedFileSourceDataset, MemoryCacheDataset#これはなに?\nfrom nnmnkwii.preprocessing import trim_zeros_frames, remove_zeros_frames\nfrom nnmnkwii.preprocessing import minmax, meanvar, minmax_scale, scale\nfrom nnmnkwii import paramgen\nfrom nnmnkwii.io import hts\nfrom nnmnkwii.frontend import merlin as fe\nfrom nnmnkwii.postfilters import merlin_post_filter\n\nfrom os.path import join, expanduser, basename, splitext, basename, exists\nimport os\nfrom glob import glob\nimport numpy as np\nfrom scipy.io import wavfile\nfrom sklearn.model_selection import train_test_split\nimport pyworld\nimport pysptk\nimport librosa\nimport librosa.display\n\n\n\n\nDATA_ROOT = \"./data/basic5000\"#NIT-ATR503/\"#\ntest_size = 0.01 # This means 480 utterances for training data\nrandom_state = 1234\n\n\n\nmgc_dim = 180#メルケプストラム次数 ??\nlf0_dim = 3#対数fo ?? なんで次元が3?\nvuv_dim = 1#無声or 有声フラグ ??\nbap_dim = 15#発話ごと非周期成分 ??\n\nduration_linguistic_dim = 438#question_jp.hed で、ラベルに対する言語特徴量をルールベースで記述してる\nacoustic_linguisic_dim = 442#上のやつ+frame_features とは??\nduration_dim = 1\nacoustic_dim = mgc_dim + lf0_dim + vuv_dim + bap_dim #aoustice modelで求めたいもの\n\nfs = 48000\nframe_period = 5\nfftlen = pyworld.get_cheaptrick_fft_size(fs)\nalpha = pysptk.util.mcepalpha(fs)\nhop_length = int(0.001 * frame_period * fs)\n\nmgc_start_idx = 0\nlf0_start_idx = 180\nvuv_start_idx = 183\nbap_start_idx = 184\n\nwindows = [\n (0, 0, np.array([1.0])),\n (1, 1, np.array([-0.5, 0.0, 0.5])),\n (1, 1, np.array([1.0, -2.0, 1.0])),\n]\n\nuse_phone_alignment = True\nacoustic_subphone_features = \"coarse_coding\" if use_phone_alignment else \"full\" #とは?\n\n\n\nclass BinaryFileSource(FileDataSource):\n def __init__(self, data_root, dim, train):\n self.data_root = data_root\n self.dim = dim\n self.train = train\n def collect_files(self):\n files = sorted(glob(join(self.data_root, \"*.bin\")))\n #files = files[:len(files)-5] # last 5 is real testset\n train_files = []\n test_files = []\n #train_files, test_files = train_test_split(files, test_size=test_size, random_state=random_state)\n\n for i, path in enumerate(files):\n if (i - 1) % 20 == 0:#test\n pass\n elif i % 20 == 0:#valid\n test_files.append(path)\n else:\n train_files.append(path)\n\n if self.train:\n return train_files\n else:\n return test_files\n def collect_features(self, path):\n return np.fromfile(path, dtype=np.float32).reshape(-1, self.dim)\n\n\nX = {\"acoustic\": {}}\nY = {\"acoustic\": {}}\nutt_lengths = { \"acoustic\": {}}\nfor ty in [\"acoustic\"]:\n for phase in [\"train\", \"test\"]:\n train = phase == \"train\"\n x_dim = duration_linguistic_dim if ty == \"duration\" else acoustic_linguisic_dim\n y_dim = duration_dim if ty == \"duration\" else acoustic_dim\n X[ty][phase] = FileSourceDataset(BinaryFileSource(join(DATA_ROOT, \"X_{}\".format(ty)),\n dim=x_dim,\n train=train))\n Y[ty][phase] = FileSourceDataset(BinaryFileSource(join(DATA_ROOT, \"Y_{}\".format(ty)),\n dim=y_dim,\n train=train))\n utt_lengths[ty][phase] = np.array([len(x) for x in X[ty][phase]], dtype=np.int)\n\n\n\n\n\nX_min = {}\nX_max = {}\nY_mean = {}\nY_var = {}\nY_scale = {}\n\nfor typ in [\"acoustic\"]:\n X_min[typ], X_max[typ] = minmax(X[typ][\"train\"], utt_lengths[typ][\"train\"])\n Y_mean[typ], Y_var[typ] = meanvar(Y[typ][\"train\"], utt_lengths[typ][\"train\"])\n Y_scale[typ] = np.sqrt(Y_var[typ])\n\n\n\n\nfrom torch.utils import data as data_utils\n\n\nimport torch\nfrom torch import nn\nfrom torch.autograd import Variable\nfrom tqdm import tnrange, tqdm\nfrom torch import optim\nimport torch.nn.functional as F\n\n\nz_dim = 1\ndropout=0.3\n\nclass VAE(nn.Module):\n def __init__(self, bidirectional=True, num_layers=1):\n super(VAE, self).__init__()\n self.num_layers = num_layers\n self.num_direction = 2 if bidirectional else 1\n\n self.lstm1 = nn.LSTM(acoustic_linguisic_dim+acoustic_dim, 400, num_layers, bidirectional=bidirectional, dropout=dropout)#入力サイズはここできまる\n self.fc21 = nn.Linear(self.num_direction*400, z_dim)\n self.fc22 = nn.Linear(self.num_direction*400, z_dim)\n ##ここまでエンコーダ\n \n self.lstm2 = nn.LSTM(acoustic_linguisic_dim+z_dim, 400, num_layers, bidirectional=bidirectional, dropout=dropout)\n self.fc3 = nn.Linear(self.num_direction*400, acoustic_dim)\n\n def encode(self, linguistic_f, acoustic_f, mora_index):\n x = torch.cat([linguistic_f, acoustic_f], dim=1)\n out, hc = self.lstm1(x.view( x.size()[0],1, -1))\n nonzero_indices = torch.nonzero(mora_index.view(-1).data).squeeze()\n out = out[nonzero_indices]\n del nonzero_indices\n \n h1 = F.relu(out)\n\n return self.fc21(h1), self.fc22(h1)\n\n def reparameterize(self, mu, logvar):\n std = torch.exp(0.5*logvar)\n eps = torch.randn_like(std)\n return mu + eps*std\n\n def decode(self, z, linguistic_features, mora_index):\n \n z_tmp = torch.tensor([0]*linguistic_features.size()[0], dtype=torch.float32, requires_grad=True).to('cuda')\n count = 0\n prev_index = 0\n for i, mora_i in enumerate(mora_index):\n if mora_i == 1:\n z_tmp[prev_index:i] = z[count]\n prev_index = i\n count += 1\n \n \n\n \n x = torch.cat([linguistic_features, z_tmp.view(-1, z_dim)], dim=1).view(linguistic_features.size()[0], 1, -1)\n \n h3, (h, c) = self.lstm2(x)\n h3 = F.relu(h3)\n \n return self.fc3(h3)#torch.sigmoid(self.fc3(h3))\n\n def forward(self, linguistic_features, acoustic_features, mora_index):\n mu, logvar = self.encode(linguistic_features, acoustic_features, mora_index)\n z = self.reparameterize(mu, logvar)\n \n return self.decode(z, linguistic_features, mora_index), mu, logvar\n\n\nmodel = VAE().to('cuda')\n\n\n#model.load_state_dict(torch.load('vae_mse_0.01kld_z_changed_losssum_batchfirst_10.pth'))\n# In[104]:\n\n\nimport pandas as pd\n\n\nmora_index_lists = sorted(glob(join('data/basic5000/mora_index', \"*.csv\")))\n#mora_index_lists = mora_index_lists[:len(mora_index_lists)-5] # last 5 is real testset\nmora_index_lists_for_model = [np.array(pd.read_csv(path)).reshape(-1) for path in mora_index_lists]\n\ntrain_mora_index_lists = []\ntest_mora_index_lists = []\n#train_files, test_files = train_test_split(files, test_size=test_size, random_state=random_state)\n\nfor i, mora_i in enumerate(mora_index_lists_for_model):\n if (i - 1) % 20 == 0:#test\n pass\n elif i % 20 == 0:#valid\n test_mora_index_lists.append(mora_i)\n else:\n train_mora_index_lists.append(mora_i)\n\n\ndevice='cuda'\nmodel = VAE().to(device)\noptimizer = optim.Adam(model.parameters(), lr=2e-3)#1e-3\n\nstart = time.time()\n\n# Reconstruction + KL divergence losses summed over all elements and batch\ndef loss_function(recon_x, x, mu, logvar):\n MSE = F.mse_loss(recon_x.view(-1), x.view(-1, ), reduction='sum')#F.binary_cross_entropy(recon_x.view(-1), x.view(-1, ), reduction='sum')\n #print('LOSS')\n #print(BCE)\n\n # see Appendix B from VAE paper:\n # Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014\n # https://arxiv.org/abs/1312.6114\n # 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)\n KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())\n #print(KLD)\n return MSE + KLD\n\n\nfunc_tensor = np.vectorize(torch.from_numpy)\n\nX_acoustic_train = [X['acoustic']['train'][i] for i in range(len(X['acoustic']['train']))] \nY_acoustic_train = [Y['acoustic']['train'][i] for i in range(len(Y['acoustic']['train']))]\ntrain_mora_index_lists = [train_mora_index_lists[i] for i in range(len(train_mora_index_lists))]\n\ntrain_num = len(X_acoustic_train)\n\nX_acoustic_test = [X['acoustic']['test'][i] for i in range(len(X['acoustic']['test']))]\nY_acoustic_test = [Y['acoustic']['test'][i] for i in range(len(Y['acoustic']['test']))]\ntest_mora_index_lists = [test_mora_index_lists[i] for i in range(len(test_mora_index_lists))]\n\ntrain_loader = [[X_acoustic_train[i], Y_acoustic_train[i], train_mora_index_lists[i]] for i in range(len(train_mora_index_lists))]\ntest_loader = [[X_acoustic_test[i], Y_acoustic_test[i], test_mora_index_lists[i]] for i in range(len(test_mora_index_lists))]\n\n\ndef train(epoch):\n model.train()\n train_loss = 0\n for batch_idx, data in enumerate(train_loader):\n tmp = []\n\n \n for j in range(3):\n tmp.append(torch.from_numpy(data[j]).to(device))\n\n\n optimizer.zero_grad()\n recon_batch, mu, logvar = model(tmp[0], tmp[1], tmp[2])\n loss = loss_function(recon_batch, tmp[1], mu, logvar)\n loss.backward()\n train_loss += loss.item()\n optimizer.step()\n del tmp\n if batch_idx % 4945 == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx, train_num,\n 100. * batch_idx / train_num,\n loss.item()))\n\n\n print('====> Epoch: {} Average loss: {:.4f}'.format(\n epoch, train_loss / len(train_loader)))\n \n return train_loss / len(train_loader)\n\n\ndef test(epoch):\n model.eval()\n test_loss = 0\n with torch.no_grad():\n for i, data, in enumerate(test_loader):\n tmp = []\n\n \n for j in range(3):\n tmp.append(torch.tensor(data[j]).to(device))\n\n\n recon_batch, mu, logvar = model(tmp[0], tmp[1], tmp[2])\n test_loss += loss_function(recon_batch, tmp[1], mu, logvar).item()\n\n del tmp\n\n test_loss /= len(test_loader)\n print('====> Test set loss: {:.4f}'.format(test_loss))\n \n return test_loss\n\n\n\n\n\n\nloss_list = []\ntest_loss_list = []\nnum_epochs = 40\n\n#model.load_state_dict(torch.load('vae.pth'))\n\nfor epoch in range(1, num_epochs + 1):\n loss = train(epoch)\n test_loss = test(epoch)\n print(loss)\n print(test_loss)\n\n print('epoch [{}/{}], loss: {:.4f} test_loss: {:.4f}'.format(\n epoch + 1,\n num_epochs,\n loss,\n test_loss))\n\n # logging\n loss_list.append(loss)\n test_loss_list.append(test_loss)\n\n print(time.time() - start)\n\n if epoch % 10 == 0:\n torch.save(model.state_dict(), 'vae_mse_z_10dim_'+str(epoch+10)+'.pth')\n np.save('loss_list.npy', np.array(loss_list))\n np.save('test_loss_list.npy', np.array(test_loss_list))\n\n# save the training model\nnp.save('loss_list_lstm1layer_z10dim.npy', np.array(loss_list))\nnp.save('test_loss_list_lstm1layer_z10dim.npy', np.array(test_loss_list))\ntorch.save(model.state_dict(), 'vae_mse_0.vae_mse_z_10dim.pth')\n","sub_path":"notebooks/tts/vaelstm_0528.py","file_name":"vaelstm_0528.py","file_ext":"py","file_size_in_byte":11490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"241741336","text":"# -*- coding: utf-8 -*-\n\"\"\"\nGenerator Bot\n\nParameters:\n\"\"\"\n\nfrom faker import Faker\nimport time\n\nimport intelmq.lib.exceptions as exceptions\nfrom intelmq.lib.bot import CollectorBot\n\n\nclass DomainGeneratorCollectorBot(CollectorBot):\n\n def init(self):\n self.logger.info(\"Init Generator.\")\n # self.base_domains = self.parameters.domains\n self.iteration_time = getattr(self.parameters, 'iteration_time', 1)\n self.stop_time = getattr(self.parameters, 'stop_time', 86400)\n self.count = getattr(self.parameters, 'count', 1000)\n self.faker = Faker()\n \n def process(self):\n self.logger.info(\"Starting Generator Process.\")\n \n for _ in range(self.count):\n data = self.faker.domain_name()\n self.logger.info(\"Sending data: {}\".format(data))\n\n report = self.new_report()\n report.add(\"extra.fqdn\", data)\n report.add(\"raw\", data)\n self.send_message(report)\n time.sleep(self.iteration_time)\n \n time.sleep(self.stop_time)\n\n\nBOT = DomainGeneratorCollectorBot","sub_path":"volumes/intelmq-bots/bots/collectors/generators/domains.py","file_name":"domains.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"141800834","text":"import json\r\nimport os\r\nfrom __selector import __,__D\r\nimport random\r\n\r\nshort_output = \"output/ndtv.json\"\r\nbrot_output = \"output/ndtv-finished.json\"\r\n# https://www.ndtv.com/india || https://www.ndtv.com/india/page-{{PAGE_NO}}\r\ndef home():\r\n\tdata = [] \r\n\tfor i in range(0,14): \r\n\t\tif i == 0:\r\n\t\t\turl= \"https://www.ndtv.com/india\"\r\n\t\telse:\r\n\t\t\turl= \"https://www.ndtv.com/india/page-%i\"%i\r\n\t\tlist_lis = __(url,\".list-li\")\r\n\t\t\r\n\t\tfor li in list_lis:\r\n\t\t\tfor a in __('',\"a\",li):\r\n\t\t\t\tlink = a[\"href\"]\r\n\t\t\t\ttitle = a.text\r\n\t\t\tfor images in __('',\"img\",li):\r\n\t\t\t\tdata_src = images[\"data-src\"] \r\n\t\t\tobj = {\r\n\t\t\t\t\"link\": link,\r\n\t\t\t\t\"title\": title, \r\n\t\t\t\t\"data_src\": data_src,\r\n\t\t\t}\r\n\t\t\tif obj not in data:\r\n\t\t\t\tdata.append(obj)\r\n\t\t\r\n\tfile = open(short_output,\"w+\")\r\n\tfile.write(json.dumps(data))\r\n\tfile.close()\r\n\tprint(\"finished\")\r\n# home()\r\ndef getAllImage():\r\n\tfile = open(short_output,\"r\").read()\r\n\tdata = json.loads(file)\r\n\t \r\n\tfor link in data: \r\n\t\tprint(\"start\",\":\",link[\"data_src\"])\r\n\t\t__D(link[\"data_src\"],\"%s.jpg\"%random.randint(0,8897445464))\r\n\t\tprint(\"end\",\":\",link[\"data_src\"],\"/n\")\r\n\r\ngetAllImage()\r\n\r\ndef getFullData():\r\n\tfile = open(short_output,\"r\").read()\r\n\tdata = json.loads(file)\r\n\tobj = []\r\n\r\n\tfor link in data: \r\n\t\tbody = __(link[\"link\"],\"body\")[0]\r\n\t\ttry:\r\n\t\t\timg = __(\"\",\"picture > img\",body)[0][\"data-src\"]\r\n\t\t\thtml_body=str(__(\"\",\"#storyBody\",body)[0])\r\n\t\texcept Exception as e:\r\n\t\t\timg=\"\"\r\n\t\t\thtml_body=\"\"\r\n\t\t\tprint(link)\r\n\t\tobj.append({\r\n\t\t\t\"link\":link[\"link\"],\r\n\t\t\t\"title\":link[\"title\"],\r\n\t\t\t\"src\":link[\"data_src\"],\r\n\t\t\t\"img\":img,\r\n\t\t\t\"html_body\":html_body\r\n\t\t}) \r\n\tfile = open(brot_output,\"w+\")\r\n\tfile.write(json.dumps(obj))\r\n\tfile.close()\r\n\tprint(\"finished\")\r\n \r\n\t\r\n# getFullData()\r\n","sub_path":"ndtv.py","file_name":"ndtv.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"106572977","text":"from collections import defaultdict\n\nfrom dagster import (\n Field,\n InputDefinition,\n Int,\n ModeDefinition,\n RepositoryDefinition,\n String,\n lambda_solid,\n pipeline,\n solid,\n)\n\nfrom dagster_aws.s3.resources import s3_resource\nfrom dagster_aws.s3.system_storage import s3_plus_default_storage_defs\n\n\n@solid(input_defs=[InputDefinition('word', String)], config={'factor': Field(Int)})\ndef multiply_the_word(context, word):\n return word * context.solid_config['factor']\n\n\n@lambda_solid(input_defs=[InputDefinition('word')])\ndef count_letters(word):\n counts = defaultdict(int)\n for letter in word:\n counts[letter] += 1\n return dict(counts)\n\n\n@lambda_solid()\ndef error_solid():\n raise Exception('Unusual error')\n\n\n@pipeline(\n mode_defs=[\n ModeDefinition(\n system_storage_defs=s3_plus_default_storage_defs, resource_defs={'s3': s3_resource}\n )\n ]\n)\ndef demo_pipeline():\n count_letters(multiply_the_word()) # pylint: disable=no-value-for-parameter\n\n\n@pipeline\ndef demo_error_pipeline():\n error_solid()\n\n\ndef define_demo_execution_repo():\n return RepositoryDefinition(\n name='demo_execution_repo', pipeline_defs=[demo_pipeline, demo_error_pipeline]\n )\n","sub_path":"python_modules/dagster-airflow/dagster_airflow_tests/test_project/dagster_airflow_demo.py","file_name":"dagster_airflow_demo.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"531831530","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom Load_Prediction.LSTM.Functions_LSTM import plot_the_loss_curve, train_model, create_model\nfrom sklearn.model_selection import train_test_split, TimeSeriesSplit\nfrom sklearn.preprocessing import StandardScaler\nimport pandas as pd\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error\nimport keras\nfrom scipy.ndimage.interpolation import shift\nimport datetime\nfrom pandas import DataFrame\n\n########################################################################################################################\n# Get data and data preprocessing.\n########################################################################################################################\n\nfrom numpy import genfromtxt\n\ndef create_dates(features_df, y_values):\n\n date_list = [datetime.datetime(year=int(round(features_df[i, -1])),\n month=int(round(features_df[i, -2])),\n day=int(round(features_df[i, -3])),\n hour=int((round(features_df[i, -4])-1) / 2),\n minute=int(((round(features_df[i, -4])-1) % 2 ) * 30)) for i in range(len(features_df))]\n\n df_dates = DataFrame(date_list, columns=['Date'])\n df_dates = df_dates.set_index(['Date'])\n df_dates['Load'] = y_values\n\n return df_dates\n\n\n# Get the X (containing the features) and y (containing the labels) values\nX = genfromtxt('Data_Entsoe/Data_Preprocessing/For_336_SP_Step_Prediction/X.csv', delimiter=',')\ny = genfromtxt('Data_Entsoe/Data_Preprocessing/For_336_SP_Step_Prediction/y.csv', delimiter=',')\ny = np.reshape(y, (len(y), 1))\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0, shuffle = False)\nX_train_1, X_train_2, y_train_1, y_train_2 = train_test_split(X_train, y_train, test_size = 0.2, random_state = 0, shuffle = False)\n# Save the unscaled data for later for data representation.\nX_test_unscaled = X_test\nX_train_unscaled_1 = X_train_1\n\n# Feature Scaling\nx_scaler = StandardScaler()\ny_scaler = StandardScaler()\nX_train_1 = x_scaler.fit_transform(X_train_1)\nX_train_2 = x_scaler.transform(X_train_2)\nX_test = x_scaler.transform(X_test)\ny_train_1 = y_scaler.fit_transform(y_train_1)\n\n########################################################################################################################\n# Create the model.\n########################################################################################################################\n\n# Define the hyperparameters.\nlearning_rate = 0.001\nnumber_of_epochs = 50\nbatch_size = 32\n\n# Create the model.\nmy_model = create_model(X_train_1, learning_rate)\n\n# Extract the loss per epoch to plot the learning progress.\nhist_list = pd.DataFrame()\n\ntscv = TimeSeriesSplit()\nfor train_index, test_index in tscv.split(X_train_1):\n X_train_split, X_test_split = X_train_1[train_index], X_train_1[test_index]\n y_train_split, y_test_split = y_train_1[train_index], y_train_1[test_index]\n X_train_split = np.reshape(X_train_split, (X_train_split.shape[0],X_train_split.shape[1],1))\n hist_split = train_model(my_model, X_train_split, y_train_split, number_of_epochs, batch_size)\n hist_list = hist_list.append(hist_split)\n\n# Plot the loss per epoch.\nmetric = \"mean_absolute_error\"\nplot_the_loss_curve(np.linspace(1,len(hist_list), len(hist_list) ), hist_list[metric], metric)\n\n#my_model.save(\"put_path_here\")\n##my_model = keras.models.load_model(\"put_path_here\")\n\n########################################################################################################################\n# Predicting the generation.\n########################################################################################################################\n\nresult_train_1 = y_scaler.inverse_transform(my_model.predict(np.reshape(X_train_1, (X_train_1.shape[0],X_train_1.shape[1],1))))\nresult_train_2 = y_scaler.inverse_transform(my_model.predict(np.reshape(X_train_2, (X_train_2.shape[0],X_train_2.shape[1],1))))\nresult_test = y_scaler.inverse_transform(my_model.predict(np.reshape(X_test, (X_test.shape[0],X_test.shape[1],1))))\n\nX_train_1 = x_scaler.inverse_transform(X_train_1)\nX_train_2 = x_scaler.inverse_transform(X_train_2)\nX_test = x_scaler.inverse_transform(X_test)\ny_train_1 = y_scaler.inverse_transform(y_train_1)\n\n########################################################################################################################\n# Data processing for plotting curves and printing the errors.\n########################################################################################################################\n\n# Compute the error between the Actual Generation and the prediction from the NN\nprint(\"-\"*200)\nerror_train_1 = abs(result_train_1 - y_train_1)\nprint(\"The mean absolute error of the training set is %0.2f\" % mean_absolute_error(y_train_1,result_train_1))\nprint(\"The mean squared error of the training set is %0.2f\" % mean_squared_error(y_train_1,result_train_1))\nprint(\"The root mean squared error of the training set is %0.2f\" % np.sqrt(mean_squared_error(y_train_1,result_train_1)))\n\nprint(\"-\"*200)\nerror_train_2 = abs(result_train_2 - y_train_2)\nprint(\"The mean absolute error of the train set 2 is %0.2f\" % mean_absolute_error(y_train_2,result_train_2))\nprint(\"The mean squared error of the train set 2 is %0.2f\" % mean_squared_error(y_train_2,result_train_2))\nprint(\"The root mean squared error of the train set 2 is %0.2f\" % np.sqrt(mean_squared_error(y_train_2,result_train_2)))\nprint(\"-\"*200)\n\nerror_test = abs(result_test - y_test)\nprint(\"The mean absolute error of the test set is %0.2f\" % mean_absolute_error(y_test,result_test))\nprint(\"The mean squared error of the test set is %0.2f\" % mean_squared_error(y_test,result_test))\nprint(\"The root mean squared error of the test set is %0.2f\" % np.sqrt(mean_squared_error(y_test,result_test)))\nprint(\"-\"*200)\n\n########################################################################################################################\n# Plotting curves.\n########################################################################################################################\n\n# Plot the actual recorded generation against the date.\nfrom Load_Prediction.ANN.Functions_ANN import plot_actual_generation, plot_predicted_generation, plot_error, plot_prediction_zoomed_in, plot_total_generation\n\n#plot_total_generation(X_train_1, y_train_1, \"Total generation (Train + Test Set\")\n\n# Plot the actual recorded generation against the date.\nfig1, axes1 = plt.subplots(3)\n\nfig1.suptitle('Train Set 1 (LSTM)', fontsize=16)\n# Plot the actual generation in a new subplot of 3x1.\nplot_actual_generation(axes1, X_train_1, y_train_1, \"Actual Generation\")\n\n# Plot the the predicted (NN) generation.\nplot_predicted_generation(axes1, X_train_1, result_train_1, \"NN prediction train set 1\")\n\n# Plot the error between the predicted and the actual temperature.\nplot_error(axes1, X_train_1, error_train_1, \"NN error train set 1\")\n\n# Print the prediction of the training set 1.\ny_values_dates = create_dates(X_train_1[-48*7:],result_train_1[-48*7:])\nfig2, axes2 = plt.subplots(2)\naxes2[0].plot(y_values_dates, label = \"Prediction\")\ny_values_dates = create_dates(X_train_1[-48*7:],y_train_1[-48*7:])\naxes2[0].plot(y_values_dates, label = \"Actual\")\naxes2[0].set_xlabel(\"Settlement Periods Training Set 1\")\naxes2[0].set_ylabel(\"Electricity Load [MW]\")\naxes2[0].legend()\n\ny_values_dates = create_dates(X_train_1[-48*7:],abs(result_train_1[-48*7:]-y_train_1[-48*7:]))\naxes2[1].plot(y_values_dates, label = \"Error\")\naxes2[1].set_xlabel(\"Settlement Periods Training Set 1\")\naxes2[1].set_ylabel(\"Electricity Load [MW]\")\naxes2[1].legend()\n\n# Print the prediction of the training set 2.\nfig3, axes3 = plt.subplots(2)\ny_values_dates = create_dates(X_train_2[-48*7-1:],result_train_2[-48*7-1:])\naxes3[0].plot(y_values_dates, label = \"Prediction\")\ny_values_dates = create_dates(X_train_2[-48*7-1:],y_train_2[-48*7-1:])\naxes3[0].plot(y_values_dates, label = \"Actual\")\naxes3[0].set_xlabel(\"Settlement Periods Training Set 2\")\naxes3[0].set_ylabel(\"Electricity Load [MW]\")\naxes3[0].legend()\n\ny_values_dates = create_dates(X_train_2[-48*7-1:],abs(result_train_2[-48*7-1:]-(y_train_2[-48*7-1:])))\naxes3[1].plot(y_values_dates, label = \"Error\")\naxes3[1].set_xlabel(\"Settlement Periods Training Set 2\")\naxes3[1].set_ylabel(\"Electricity Load [MW]\")\naxes3[1].legend()\n\n# Print the prediction of the test set.\nfig4, axes4 = plt.subplots(2)\ny_values_dates = create_dates(X_test[-48*7:],result_test[-48*7:])\naxes4[0].plot(y_values_dates, label = \"Prediction\")\ny_values_dates = create_dates(X_test[-48*7:],y_test[-48*7:])\naxes4[0].plot(y_values_dates, label = \"Actual\")\naxes4[0].set_xlabel(\"Settlement Periods Test Set\")\naxes4[0].set_ylabel(\"Electricity Load [MW]\")\naxes4[0].legend()\n\ny_values_dates = create_dates(X_test[-48*7:],abs(result_test[-48*7:]-(y_test[-48*7:])))\naxes4[1].plot(y_values_dates, label = \"Error\")\naxes4[1].set_xlabel(\"Settlement Periods Test Set\")\naxes4[1].set_ylabel(\"Error in [MW]\")\naxes4[1].legend()\n\n########################################################################################################################\n# Save the results in a csv file.\n########################################################################################################################\n\npd.DataFrame(result_train_2).to_csv(\"Load_Prediction/Hybrid_Model/Pred_train2_other_metrics/LSTM_prediction.csv\")\npd.DataFrame(result_test).to_csv(\"Load_Prediction/Hybrid_Model/Pred_test_other_metrics/LSTM_prediction.csv\")\n\nimport csv\nwith open('/Compare_Models/MST2_results/LSTM_result.csv', 'w', newline='',) as file:\n writer = csv.writer(file)\n writer.writerow([\"Method\",\"MSE\",\"MAE\",\"RMSE\"])\n writer.writerow([\"LSTM\",\n str(mean_squared_error(y_test,result_test)),\n str(mean_absolute_error(y_test,result_test)),\n str(np.sqrt(mean_squared_error(y_test,result_test)))\n ])\n","sub_path":"Load_Prediction/LSTM/Hybrid_Model/MST_LSTM_Hybrid.py","file_name":"MST_LSTM_Hybrid.py","file_ext":"py","file_size_in_byte":10044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"63017077","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/anders/work/python/django-pagetimer/pagetimer/templatetags/pagetimertags.py\n# Compiled at: 2016-05-09 12:52:27\nfrom django import template\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nregister = template.Library()\n\n@register.inclusion_tag('pagetimer/pagetimer.html', takes_context=True)\ndef pagetimer(context):\n interval = 60\n if hasattr(settings, 'PAGETIMER_INTERVAL'):\n interval = settings.PAGETIMER_INTERVAL\n return {'pagetimer_endpoint': reverse('pagetimer-endpoint'), 'pagetimer_interval': interval}","sub_path":"pycfiles/django_pagetimer-0.2.0-py2.py3-none-any/pagetimertags.py","file_name":"pagetimertags.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"255221168","text":"# Write your solutions for 1.5 here!\nclass Superheros:\n\tdef __init__(self, name,superpower, strengh):\n\t\tself.name = name\n\t\tself.superpower = superpower\n\t\tself.strengh = strengh\n\tdef name_strengh(self):\n\t\tprint(\"the name of the superhero is: \" + self.name +\",his strengh level is: \"+str(self.strengh))\n\tdef save_civilian(self, work):\n\t\tif work > self.strengh:\n\t\t\tprint(\"not enough power :(\")\t\n\t\telse:\n\t\t\tself.strengh -= work\n\t\t\tprint(\"the amount of strengh left in your hero is \"+str(self.strengh))\n\t\t\t\nhero = Superheros(\"noam\", \"flying\", 11)\nhero.name_strengh()\nhero.save_civilian(2)","sub_path":"exercises/superheros.py","file_name":"superheros.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"493077798","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nimport math\n\nimport collada\nfrom collada.lineset import BoundLineSet, Line, LineSet\nfrom collada.scene import Scene, Node, NodeNode\nfrom collada.geometry import BoundGeometry, Geometry\nfrom lxml.etree import _Element\nfrom ruler_tracer_tools import *\n\nfrom pypcd import pypcd\n\ndef index_nodes(nodes, name_dict, level=0, name=''):\n for n in nodes:\n own_name = n.xmlnode.get('name')\n print('.'*level, n, name, n.xmlnode.get('id'))\n\n if 'node' in dir(n):\n id = n.node.id\n elif 'geometry' in dir(n):\n id = n.geometry.id\n else:\n id = n.xmlnode.get('id')\n\n if id is not None:\n if own_name is not None:\n name_dict[id] = own_name\n else:\n name_dict[id] = name\n\n if isinstance(n, Node):\n if own_name is not None:\n index_nodes(n.children, name_dict, level + 1, name=own_name)\n else:\n index_nodes(n.children, name_dict, level + 1, name=name)\n\n\ndef create_scene(filename):\n scene = {}\n scene['triangles'] = []\n scene['rulers'] = {}\n\n dae = collada.Collada(filename, ignore=[collada.DaeUnsupportedError,\n collada.DaeBrokenRefError])\n\n assert (isinstance(dae.scene, Scene))\n name_dict = {}\n index_nodes(dae.scene.nodes, name_dict)\n print(name_dict)\n\n for geom in dae.scene.objects('geometry'):\n print('===================')\n assert (isinstance(geom, BoundGeometry))\n assert (isinstance(geom.original, Geometry))\n assert (isinstance(geom.original.xmlnode, _Element))\n\n geometry_name = name_dict[geom.original.id]\n # print('>', geom, 'NAME:', name_dict[geom.original.id])\n\n for prim in geom.primitives():\n print('>', prim)\n prim_type = type(prim).__name__\n triangles = None\n lines = None\n if prim_type == 'BoundTriangleSet':\n triangles = prim\n elif prim_type == 'BoundPolylist':\n triangles = prim.triangleset()\n elif prim_type == 'BoundLineSet':\n assert (isinstance(prim, BoundLineSet))\n\n lines = prim.lines()\n else:\n print('Unsupported mesh used:', prim_type)\n\n print(type(prim))\n\n if triangles is not None and 'Ruler' not in geometry_name:\n print('=== Triangles')\n vertices = triangles.vertex.flatten().tolist()\n batch_len = len(vertices) // 3\n indices = triangles.vertex_index.flatten().tolist()\n normals = triangles.normal.flatten().tolist()\n print(vertices)\n print(indices)\n print(normals)\n\n i = np.array(indices)\n v = np.array(vertices).reshape((-1, 3))\n points = v[i].reshape((-1, 3, 3)) / 20\n\n for tidx in range(points.shape[0]):\n print(\"Adding \", points[tidx])\n scene['triangles'].append(add_triangle(points[tidx], [1, .3, .1]))\n\n if lines is not None:\n print('=== Lines')\n if 'Ruler' in geometry_name:\n assert('_' in geometry_name)\n ruler_name, part = geometry_name.split('_', 2)\n\n first_line = list(lines)[0]\n assert (isinstance(first_line, Line))\n i = np.array(first_line.indices)\n v = np.array(first_line.vertices).reshape((-1, 3))\n points = v[i].reshape((-1, 2, 3)) / 20\n\n print(first_line)\n print(first_line.vertices)\n print(first_line.indices)\n\n if ruler_name not in scene['rulers']:\n scene['rulers'][ruler_name] = {}\n\n scene['rulers'][ruler_name][part] = points\n\n return scene\n\ndef project_laser_points(scene, LaserO, LaserD, LaserLeft):\n # TODO: Go over angles, project rays into scene, store points\n angles_range = (-35, 35)\n num_steps = 100\n laser_points = []\n for idx in range(num_steps):\n angle = (angles_range[1] - angles_range[0]) / (num_steps-1) * idx + angles_range[0]\n #print(angle)\n vec = LaserLeft * math.sin(math.radians(angle)) + LaserD * math.cos(math.radians(angle))\n\n # Trace this laser ray\n traced = trace_ray(scene['triangles'], LaserO, vec, LaserO, LaserO) # TODO: remove lighting stuff\n if not traced:\n continue\n obj, M, N, col_ray = traced\n laser_points.append(M)\n\n if len(laser_points) > 0:\n return np.vstack(laser_points)\n else:\n return None\n\n\n\n\ndef simulate_ruler_single(scene, ruler, x_offset):\n offset_vector = np.array([x_offset, 0, 0])\n\n line_laser = ruler['Laser'][0]\n\n LaserO = line_laser[0] + offset_vector\n LaserD = normalize(line_laser[1] - line_laser[0])\n\n line_cam = ruler['Cam'][0]\n CamO = line_cam[0] + offset_vector\n CamD = normalize(line_cam[1] - line_cam[0])\n LaserLeft = normalize(np.cross(LaserD, CamO - LaserO))\n\n laser_points = project_laser_points(scene, LaserO, LaserD, LaserLeft)\n # print(laser_points)\n\n if laser_points is not None:\n\n pcd_points = np.zeros((len(laser_points), 4), dtype=np.float32)\n pcd_points[:, 0:3] = laser_points\n\n colors = np.zeros((len(laser_points), 3), dtype=np.uint)\n\n for idx, laser_point in enumerate(laser_points):\n # Check visibility from camera (like shadow checking in ray tracer)\n toCam = CamO - laser_point\n l = []\n for obj_sh in scene['triangles']:\n dist = intersect(laser_point, toCam, obj_sh)\n if dist > 0.001:\n l.append(dist)\n\n if l and min(l) < np.inf:\n colors[idx, :] = [255, 0, 0]\n else:\n colors[idx, :] = [0, 0, 255]\n\n colors_uint = np.array((colors[:, 0] << 16) | (colors[:, 1] << 8) | (colors[:, 2] << 0), dtype=np.uint32)\n colors_uint.dtype = np.float32\n pcd_points[:, 3] = colors_uint\n\n print(\"Ret points with offset \", x_offset)\n return pcd_points\n else:\n return None\n\ndef simulate_ruler(scene, ruler):\n print(\"Simulating Ruler '%s'\" % str(ruler))\n\n all_points = []\n for x_offset in np.linspace(-0.3, 0.3, 100):\n scanline_points = simulate_ruler_single(scene, ruler, x_offset)\n if scanline_points is not None:\n all_points.append(scanline_points)\n\n all_pcd_points = np.vstack(all_points)\n\n result = pypcd.make_xyz_rgb_point_cloud(all_pcd_points)\n pypcd.save_point_cloud_bin(result, 'out.pcd')\n\n\nif __name__ == '__main__':\n\n w = 200\n h = 150\n\n # List of objects.\n settings['color_plane0'] = 1. * np.ones(3)\n settings['color_plane1'] = 0. * np.ones(3)\n\n # Light position and color.\n L = np.array([5., 5., -10.])\n settings['color_light'] = np.ones(3)\n\n # Default light and material parameters.\n settings['ambient'] = .05\n settings['diffuse_c'] = 1.\n settings['specular_c'] = 1.\n settings['specular_k'] = 50\n\n\n scene = create_scene('data/rulertest02.dae')\n print(scene)\n\n for ruler in scene['rulers']:\n simulate_ruler(scene, scene['rulers'][ruler])\n\n sys.exit(1)\n\n depth_max = 2 # Maximum number of light reflections.\n col = np.zeros(3) # Current color.\n O = np.array([0., -1, 0.45]) # Camera.\n Q = np.array([0., 0., 0.]) # Camera pointing to.\n img = np.zeros((h, w, 3))\n\n r = float(w) / h\n # Screen coordinates: x0, y0, x1, y1.\n S = (-1., -1. / r + .25, 1., 1. / r + .25)\n\n # Loop through all pixels.\n for i, x in enumerate(np.linspace(S[0], S[2], w)):\n if i % 10 == 0:\n print(i / float(w) * 100, \"%\")\n for j, y in enumerate(np.linspace(S[1], S[3], h)):\n col[:] = 0\n Q[0] = x\n Q[2] = y\n D = normalize(Q - O)\n depth = 0\n rayO, rayD = O, D\n reflection = 1.\n # Loop through initial and secondary rays.\n while depth < depth_max:\n traced = trace_ray(scene, rayO, rayD, O, L)\n if not traced:\n break\n obj, M, N, col_ray = traced\n # Reflection: create a new ray.\n rayO, rayD = M + N * .0001, normalize(rayD - 2 * np.dot(rayD, N) * N)\n depth += 1\n col += reflection * col_ray\n reflection *= obj.get('reflection', 1.)\n img[h - j - 1, i, :] = np.clip(col, 0, 1)\n\n plt.imsave('fig2.png', img)\n","sub_path":"old/ruler_tracer.py","file_name":"ruler_tracer.py","file_ext":"py","file_size_in_byte":8806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"437471843","text":"from absl import app, flags\nfrom absl.flags import FLAGS\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\nfrom u_lambda import u_lambda\n\nflags.DEFINE_string('function', 'math.sin(x[0]*0.05)+math.sin(x[1]*0.05)+0.4*math.sin(x[0]*0.15)*math.sin(x[1]*0.15)', '')\nflags.DEFINE_integer('individuals_count', 25, '')\nflags.DEFINE_float('mutation', 0.1, '')\nflags.DEFINE_integer('variation_min', 0, '')\nflags.DEFINE_integer('variation_max', 100, '')\nflags.DEFINE_integer('iterations', 40, '')\n\ndef eval_function(X, Y):\n result = np.empty(X.shape)\n for i in range(len(X)):\n for j in range(len(X[i])):\n x = (X[i,j], Y[i,j])\n result[i,j] = eval(FLAGS.function)\n return result\n\ndef main(_argv):\n maximum = u_lambda(FLAGS.function, (FLAGS.variation_min, FLAGS.variation_min), (FLAGS.variation_max, FLAGS.variation_max), FLAGS.individuals_count, mutation=FLAGS.mutation, iterations=FLAGS.iterations)\n print('Maximum is: ({:.1f},{:.1f})'.format(maximum[0], maximum[1]))\n\n x = np.linspace(FLAGS.variation_min, FLAGS.variation_max, 100)\n y = np.linspace(FLAGS.variation_min, FLAGS.variation_max, 100)\n X, Y = np.meshgrid(x, y)\n Z = eval_function(X, Y)\n\n ax = plt.axes(projection='3d')\n ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='viridis', edgecolor='none')\n\n x = maximum\n z = eval(FLAGS.function)\n ax.scatter(maximum[0], maximum[1], z, marker='*', s=300, color='blue', label='Best result')\n ax.plot((maximum[0], maximum[0]), (maximum[1], maximum[1]), (0, z*1.5), color='blue', linewidth=5, label='Best result coordinates')\n\n plt.legend(loc='upper right')\n plt.title('Maximum for ' + FLAGS.function)\n plt.show()\n\nif __name__ == '__main__':\n app.run(main)\n","sub_path":"lab04/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"438255080","text":"# (c) Copyright [2018] Micro Focus or one of its affiliates. \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# AUTHOR: BADR OUALI\n#\n############################################################################################################ \n# __ __ ___ ____ ______ ____ __ ____ ___ ___ _ ____ __ __ ______ __ __ ___ ____ #\n# | | | / _| \\| | | / ]/ | | | | | | \\| | | | | |/ \\| \\ #\n# | | |/ [_| D | || | / /| o | | _ _ | | | o | | | | | | | _ | #\n# | | | _| /|_| |_|| |/ / | | | \\_/ | |___ | _/| ~ |_| |_| _ | O | | | #\n# | : | [_| \\ | | | / \\_| _ | | | | | | | |___, | | | | | | | | | #\n# \\ /| | . \\ | | | \\ | | | | | | | | | | | | | | | | | | | #\n# \\_/ |_____|__|\\_| |__| |____\\____|__|__| |___|___|_____| |__| |____/ |__| |__|__|\\___/|__|__| #\n# #\n############################################################################################################\n# Vertica-ML-Python allows user to create Virtual Dataframe. vDataframes simplify #\n# data exploration, data cleaning and machine learning in Vertica. #\n# It is an object which keeps in it all the actions that the user wants to achieve # \n# and execute them when they are needed. \t\t\t\t\t\t\t\t\t\t#\n#\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#\n# The purpose is to bring the logic to the data and not the opposite #\n#####################################################################################\n#\n# Libraries\nfrom vertica_ml_python import drop_model\nfrom vertica_ml_python import tablesample\nfrom vertica_ml_python import to_tablesample\n\nfrom vertica_ml_python.learn.metrics import accuracy_score\nfrom vertica_ml_python.learn.metrics import auc\nfrom vertica_ml_python.learn.metrics import prc_auc\nfrom vertica_ml_python.learn.metrics import log_loss\nfrom vertica_ml_python.learn.metrics import classification_report\nfrom vertica_ml_python.learn.metrics import confusion_matrix\nfrom vertica_ml_python.learn.metrics import critical_success_index\nfrom vertica_ml_python.learn.metrics import f1_score\nfrom vertica_ml_python.learn.metrics import informedness\nfrom vertica_ml_python.learn.metrics import markedness\nfrom vertica_ml_python.learn.metrics import matthews_corrcoef\nfrom vertica_ml_python.learn.metrics import multilabel_confusion_matrix\nfrom vertica_ml_python.learn.metrics import negative_predictive_score\nfrom vertica_ml_python.learn.metrics import precision_score\nfrom vertica_ml_python.learn.metrics import recall_score\nfrom vertica_ml_python.learn.metrics import specificity_score\n\nfrom vertica_ml_python.learn.plot import lift_chart\nfrom vertica_ml_python.learn.plot import roc_curve\nfrom vertica_ml_python.learn.plot import prc_curve\n\n#\nclass MultinomialNB:\n\t#\n\tdef __init__(self,\n\t\t\t\t name: str,\n\t\t\t\t cursor,\n\t\t\t\t alpha: float = 1.0):\n\t\tself.type = \"classifier\"\n\t\tself.cursor = cursor\n\t\tself.name = name\n\t\tself.alpha = alpha\n\t# \n\tdef __repr__(self):\n\t\ttry:\n\t\t\treturn (self.cursor.execute(\"SELECT GET_MODEL_SUMMARY(USING PARAMETERS model_name = '\" + self.name + \"')\").fetchone()[0])\n\t\texcept:\n\t\t\treturn \"\"\n\t#\n\t#\n\t#\n\t# METHODS\n\t# \n\t#\n\tdef add_to_vdf(self,\n\t\t\t\t vdf,\n\t\t\t\t name: str = \"\",\n\t\t\t\t cutoff: float = 0.5):\n\t\tname = \"MultinomialNB_\" + self.name if not (name) else name\n\t\tpos_label = self.classes[1] if (len(self.classes) == 2) else None\n\t\treturn (vdf.eval(name, self.deploySQL(pos_label, cutoff)))\n\t#\n\tdef classification_report(self, cutoff: float = 0.5, labels = []):\n\t\tlabels = self.classes if not(labels) else labels\n\t\treturn (classification_report(cutoff = cutoff, estimator = self, labels = labels))\n\t#\n\tdef confusion_matrix(self, pos_label = None, cutoff: float = 0.5):\n\t\tpos_label = self.classes[1] if (pos_label == None and len(self.classes) == 2) else pos_label\n\t\tif (pos_label in self.classes and cutoff < 1 and cutoff > 0):\n\t\t\treturn (confusion_matrix(self.y, self.deploySQL(pos_label, cutoff), self.test_relation, self.cursor, pos_label = pos_label))\n\t\telse:\n\t\t\treturn (multilabel_confusion_matrix(self.y, self.deploySQL(), self.test_relation, self.cursor, self.classes))\n\t#\n\tdef deploySQL(self, pos_label = None, cutoff: float = -1, allSQL: bool = False):\n\t\tif (allSQL):\n\t\t\tsql = \"PREDICT_NAIVE_BAYES({} USING PARAMETERS model_name = '{}', class = '{}', type = 'probability', match_by_pos = 'true')\".format(\", \".join(self.X), self.name, \"{}\")\n\t\t\tsql = [sql, \"PREDICT_NAIVE_BAYES({} USING PARAMETERS model_name = '{}', match_by_pos = 'true')\".format(\", \".join(self.X), self.name)]\n\t\telse:\n\t\t\tif (pos_label in self.classes and cutoff <= 1 and cutoff >= 0):\n\t\t\t\tsql = \"PREDICT_NAIVE_BAYES({} USING PARAMETERS model_name = '{}', class = '{}', type = 'probability', match_by_pos = 'true')\".format(\", \".join(self.X), self.name, pos_label)\n\t\t\t\tif (len(self.classes) > 2):\n\t\t\t\t\tsql = \"(CASE WHEN {} >= {} THEN '{}' WHEN {} IS NULL THEN NULL ELSE 'Non-{}' END)\".format(sql, cutoff, pos_label, sql, pos_label)\n\t\t\t\telse:\n\t\t\t\t\tnon_pos_label = self.classes[0] if (self.classes[0] != pos_label) else self.classes[1]\n\t\t\t\t\tsql = \"(CASE WHEN {} >= {} THEN '{}' WHEN {} IS NULL THEN NULL ELSE '{}' END)\".format(sql, cutoff, pos_label, sql, non_pos_label)\n\t\t\telif (pos_label in self.classes):\n\t\t\t\tsql = \"PREDICT_NAIVE_BAYES({} USING PARAMETERS model_name = '{}', class = '{}', type = 'probability', match_by_pos = 'true')\".format(\", \".join(self.X), self.name, pos_label)\n\t\t\telse:\n\t\t\t\tsql = \"PREDICT_NAIVE_BAYES({} USING PARAMETERS model_name = '{}', match_by_pos = 'true')\".format(\", \".join(self.X), self.name)\n\t\treturn (sql)\n\t#\n\tdef deploy_to_DB(self, name: str, view: bool = True, cutoff = -1, all_classes: bool = False):\n\t\trelation = \"TABLE\" if not(view) else \"VIEW\"\n\t\tsql = \"CREATE {} {} AS SELECT {}, {} FROM {}\".format(relation, name, \", \".join(self.X), \"{}\", self.test_relation)\n\t\tif (all_classes):\n\t\t\tpredict = []\n\t\t\tfor elem in self.classes:\n\t\t\t\tif elem not in (self.classes):\n\t\t\t\t\traise ValueError(\"All the elements of 'pos_label' must be in the estimator classes\")\n\t\t\t\talias = '\"{}_{}\"'.format(self.y.replace('\"', ''), elem) \n\t\t\t\tpredict += [\"{} AS {}\".format(self.deploySQL(elem), alias)]\n\t\t\tpredict += [\"{} AS {}\".format(self.deploySQL(), self.y)]\n\t\telse:\n\t\t\tif (len(self.classes) == 2):\n\t\t\t\tpredict = [\"{} AS {}\".format(self.deploySQL(self.classes[1], cutoff), self.y)]\n\t\t\telse:\n\t\t\t\tpredict = [\"{} AS {}\".format(self.deploySQL(), self.y)]\n\t\tself.cursor.execute(sql.format(\", \".join(predict)))\n\t#\n\tdef drop(self):\n\t\tdrop_model(self.name, self.cursor, print_info = False)\n\t#\n\tdef fit(self,\n\t\t\tinput_relation: str, \n\t\t\tX: list, \n\t\t\ty: str,\n\t\t\ttest_relation: str = \"\"):\n\t\tself.input_relation = input_relation\n\t\tself.test_relation = test_relation if (test_relation) else input_relation\n\t\tself.X = ['\"' + column.replace('\"', '') + '\"' for column in X]\n\t\tself.y = '\"' + y.replace('\"', '') + '\"'\n\t\tquery = \"SELECT NAIVE_BAYES('{}', '{}', '{}', '{}' USING PARAMETERS alpha = {})\".format(self.name, input_relation, self.y, \", \".join(self.X), self.alpha)\n\t\tself.cursor.execute(query)\n\t\tclasses = self.cursor.execute(\"SELECT DISTINCT {} FROM {} WHERE {} IS NOT NULL ORDER BY 1\".format(self.y, input_relation, self.y)).fetchall()\n\t\tself.classes = [item[0] for item in classes]\n\t\treturn (self)\n\t#\n\tdef lift_chart(self, pos_label = None):\n\t\tpos_label = self.classes[1] if (pos_label == None and len(self.classes) == 2) else pos_label\n\t\tif (pos_label not in self.classes):\n\t\t\traise ValueError(\"'pos_label' must be one of the response column classes\")\n\t\treturn (lift_chart(self.y, self.deploySQL(allSQL = True)[0].format(pos_label), self.test_relation, self.cursor, pos_label))\n\t#\n\tdef prc_curve(self, pos_label = None):\n\t\tpos_label = self.classes[1] if (pos_label == None and len(self.classes) == 2) else pos_label\n\t\tif (pos_label not in self.classes):\n\t\t\traise ValueError(\"'pos_label' must be one of the response column classes\")\n\t\treturn (prc_curve(self.y, self.deploySQL(allSQL = True)[0].format(pos_label), self.test_relation, self.cursor, pos_label))\n\t#\n\tdef roc_curve(self, pos_label = None):\n\t\tpos_label = self.classes[1] if (pos_label == None and len(self.classes) == 2) else pos_label\n\t\tif (pos_label not in self.classes):\n\t\t\traise ValueError(\"'pos_label' must be one of the response column classes\")\n\t\treturn (roc_curve(self.y, self.deploySQL(allSQL = True)[0].format(pos_label), self.test_relation, self.cursor, pos_label))\n\t#\n\tdef score(self, pos_label = None, cutoff: float = 0.5, method: str = \"accuracy\"):\n\t\tpos_label = self.classes[1] if (pos_label == None and len(self.classes) == 2) else pos_label\n\t\tif (pos_label not in self.classes):\n\t\t\traise ValueError(\"'pos_label' must be one of the response column classes\")\n\t\telif (cutoff >= 1 or cutoff <= 0):\n\t\t\traise ValueError(\"'cutoff' must be in ]0;1[\")\n\t\tif (method in (\"accuracy\", \"acc\")):\n\t\t\treturn (accuracy_score(self.y, self.deploySQL(pos_label, cutoff), self.test_relation, self.cursor))\n\t\telif (method == \"auc\"):\n\t\t\treturn auc(\"DECODE({}, '{}', 1, 0)\".format(self.y, pos_label), self.deploySQL(allSQL = True)[0].format(pos_label), self.test_relation, self.cursor)\n\t\telif (method == \"prc_auc\"):\n\t\t\treturn prc_auc(\"DECODE({}, '{}', 1, 0)\".format(self.y, pos_label), self.deploySQL(allSQL = True)[0].format(pos_label), self.test_relation, self.cursor)\n\t\telif (method in (\"best_cutoff\", \"best_threshold\")):\n\t\t\treturn (roc_curve(\"DECODE({}, '{}', 1, 0)\".format(self.y, pos_label), self.deploySQL(allSQL = True)[0].format(pos_label), self.test_relation, self.cursor, best_threshold = True))\n\t\telif (method in (\"recall\", \"tpr\")):\n\t\t\treturn (recall_score(self.y, self.deploySQL(pos_label, cutoff), self.test_relation, self.cursor))\n\t\telif (method in (\"precision\", \"ppv\")):\n\t\t\treturn (precision_score(self.y, self.deploySQL(pos_label, cutoff), self.test_relation, self.cursor))\n\t\telif (method in (\"specificity\", \"tnr\")):\n\t\t\treturn (specificity_score(self.y, self.deploySQL(pos_label, cutoff), self.test_relation, self.cursor))\n\t\telif (method in (\"negative_predictive_value\", \"npv\")):\n\t\t\treturn (precision_score(self.y, self.deploySQL(pos_label, cutoff), self.test_relation, self.cursor))\n\t\telif (method in (\"log_loss\", \"logloss\")):\n\t\t\treturn (log_loss(\"DECODE({}, '{}', 1, 0)\".format(self.y, pos_label), self.deploySQL(allSQL = True)[0].format(pos_label), self.test_relation, self.cursor))\n\t\telif (method == \"f1\"):\n\t\t\treturn (f1_score(self.y, self.deploySQL(pos_label, cutoff), self.test_relation, self.cursor))\n\t\telif (method == \"mcc\"):\n\t\t\treturn (matthews_corrcoef(self.y, self.deploySQL(pos_label, cutoff), self.test_relation, self.cursor))\n\t\telif (method in (\"bm\", \"informedness\")):\n\t\t\treturn (informedness(self.y, self.deploySQL(pos_label, cutoff), self.test_relation, self.cursor))\n\t\telif (method in (\"mk\", \"markedness\")):\n\t\t\treturn (markedness(self.y, self.deploySQL(pos_label, cutoff), self.test_relation, self.cursor))\n\t\telif (method in (\"csi\", \"critical_success_index\")):\n\t\t\treturn (critical_success_index(self.y, self.deploySQL(pos_label, cutoff), self.test_relation, self.cursor))\n\t\telse:\n\t\t\traise ValueError(\"The parameter 'method' must be in accuracy|auc|prc_auc|best_cutoff|recall|precision|log_loss|negative_predictive_value|specificity|mcc|informedness|markedness|critical_success_index\")","sub_path":"vertica_ml_python/learn/naive_bayes.py","file_name":"naive_bayes.py","file_ext":"py","file_size_in_byte":11938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"21257912","text":"import asyncio\nimport fmi.fmi\nimport json\nimport time\n\nfrom concurrent.futures import ThreadPoolExecutor\nfrom functools import partial\n\n\nclass TemperatureSource:\n def __init__(self):\n self._observation_callbacks = list()\n self._forecast_callbacks = list()\n\n def current_temperature(self):\n raise NotImplementedError()\n\n def register_observation_callback(self, f):\n self._observation_callbacks.append(f)\n\n def register_forecast_callback(self, f):\n self._forecast_callbacks.append(f)\n\n\nclass FmiTemperatureSource(TemperatureSource):\n def __init__(self, location: str = None):\n super().__init__()\n with open(\"keys.json\") as f:\n keys = json.load(f)\n self._client = fmi.Client(keys[\"fmi-apikey\"])\n self.location = location\n\n self._latest_observation = None\n self._latest_forecast = None\n\n async def updater(self):\n print(\"Temperature updater started.\")\n loop = asyncio.get_event_loop()\n update_time = loop.time()\n delta = 60 * 60 # One hour\n await self.run_forecast()\n while True:\n # Update forecast every hour\n if loop.time() > update_time + delta:\n await self.run_forecast()\n update_time = loop.time()\n\n # Update current temperature\n await self.run_current_temperature()\n await asyncio.sleep(60)\n\n def start_update(self):\n print(\"Starting temperature updater.\")\n asyncio.ensure_future(self.updater())\n\n def current_temperature(self):\n if self._latest_observation:\n #timestamp = self._latest_observation['timestamp']\n #if timestamp < time.time() + 5 * 60:\n # self.update_observation()\n\n return self._latest_observation.temperature\n\n return \"---\"\n\n def current_forecast(self):\n if self._latest_forecast:\n data = list()\n for forecast in self._latest_forecast:\n data.append(str(forecast.temperature))\n return data\n\n return list()\n\n async def run_current_temperature(self):\n self._latest_observation = await self._client.weather_now(self.location)\n print(self._latest_observation)\n for f in self._observation_callbacks:\n f()\n\n async def run_forecast(self, timestep: int = 6 * 60, count: int = 5):\n self._latest_forecast = await self._client.forecast(self.location, timestep, count)\n for forecast in self._latest_forecast:\n print(forecast)\n for f in self._forecast_callbacks:\n f()\n\n\nif __name__ == \"__main__\":\n fmi = FmiTemperatureSource(\"Kyröskoski\")\n fmi.current_temperature()\n fmi.forecast()\n","sub_path":"temperature_source.py","file_name":"temperature_source.py","file_ext":"py","file_size_in_byte":2757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"353711161","text":"# Taken from mission The Defenders\n\n# Taken from mission Army Battles\n\n# Taken from mission The Warriors\nclass Warrior:\n\tdef __init__(self):\n\t\tself.health = 50\n\t\tself.attack = 5\n\n\t@property\n\tdef is_alive(self):\n\t\treturn self.health > 0\n\n\tdef damage_taken(self, unit):\n\t\tself.health -= unit.attack\n\n\tdef damage_dealt(self, unit):\n\t\tpass\n\n\nclass Knight(Warrior):\n\tdef __init__(self):\n\t\tsuper().__init__()\n\t\tself.attack = 7\n\n\nclass Defender(Warrior):\n\tdef __init__(self):\n\t\tself.health = 60\n\t\tself.attack = 3\n\t\tself.defense = 2\n\n\tdef damage_taken(self, unit):\n\t\tif unit.attack > self.defense:\n\t\t\tself.health -= unit.attack - self.defense\n\n\nclass Vampire(Warrior):\n\tdef __init__(self):\n\t\tsuper().__init__()\n\t\tself.health = 40\n\t\tself.attack = 4\n\t\tself.vampirism = 50\n\n\tdef damage_dealt(self, unit):\n\t\tdefense = 0\n\t\tif isinstance(unit, Defender):\n\t\t\tdefense = unit.defense\n\t\tself.health = min(40, self.health + (self.attack - defense) * self.vampirism / 100)\n\n\nclass Army:\n\tdef __init__(self):\n\t\tself.units = []\n\n\tdef add_units(self, unit, amount):\n\t\tfor i in range(amount):\n\t\t\tself.units.append(unit())\n\n\nclass Battle:\n\tdef fight(self, army_1, army_2):\n\t\ti = 0\n\t\tj = 0\n\t\tlength1 = len(army_1.units)\n\t\tlength2 = len(army_2.units)\n\t\twhile i < length1 and j < length2:\n\t\t\tif fight(army_1.units[i], army_2.units[j]):\n\t\t\t\tj += 1\n\t\t\telse:\n\t\t\t\ti += 1\n\t\treturn True if j == length2 else False\n\n\ndef fight(unit_1, unit_2):\n\twhile True:\n\t\tunit_1.damage_dealt(unit_2)\n\t\tunit_2.damage_taken(unit_1)\n\t\tif not unit_2.is_alive:\n\t\t\treturn True\n\t\tunit_2.damage_dealt(unit_1)\n\t\tunit_1.damage_taken(unit_2)\n\t\tif not unit_1.is_alive:\n\t\t\treturn False\n\n\nif __name__ == '__main__':\n\t# These \"asserts\" using only for self-checking and not necessary for auto-testing\n\n\tchuck = Warrior()\n\tbruce = Warrior()\n\tcarl = Knight()\n\tdave = Warrior()\n\tmark = Warrior()\n\n\tassert fight(chuck, bruce) == True\n\tassert fight(dave, carl) == False\n\tassert chuck.is_alive == True\n\tassert bruce.is_alive == False\n\tassert carl.is_alive == True\n\tassert dave.is_alive == False\n\tassert fight(carl, mark) == False\n\tassert carl.is_alive == False\n\n\tprint(\"Coding complete? Let's try tests!\")\n\nif __name__ == '__main__':\n\t# These \"asserts\" using only for self-checking and not necessary for auto-testing\n\n\t# fight tests\n\tchuck = Warrior()\n\tbruce = Warrior()\n\tcarl = Knight()\n\tdave = Warrior()\n\tmark = Warrior()\n\n\tassert fight(chuck, bruce) == True\n\tassert fight(dave, carl) == False\n\tassert chuck.is_alive == True\n\tassert bruce.is_alive == False\n\tassert carl.is_alive == True\n\tassert dave.is_alive == False\n\tassert fight(carl, mark) == False\n\tassert carl.is_alive == False\n\n\t# battle tests\n\tmy_army = Army()\n\tmy_army.add_units(Knight, 3)\n\n\tenemy_army = Army()\n\tenemy_army.add_units(Warrior, 3)\n\n\tarmy_3 = Army()\n\tarmy_3.add_units(Warrior, 20)\n\tarmy_3.add_units(Knight, 5)\n\n\tarmy_4 = Army()\n\tarmy_4.add_units(Warrior, 30)\n\n\tbattle = Battle()\n\n\tassert battle.fight(my_army, enemy_army) == True\n\tassert battle.fight(army_3, army_4) == False\n\tprint(\"Coding complete? Let's try tests!\")\n\nif __name__ == '__main__':\n\t# These \"asserts\" using only for self-checking and not necessary for auto-testing\n\n\t# fight tests\n\tchuck = Warrior()\n\tbruce = Warrior()\n\tcarl = Knight()\n\tdave = Warrior()\n\tmark = Warrior()\n\tbob = Defender()\n\tmike = Knight()\n\trog = Warrior()\n\tlancelot = Defender()\n\n\tassert fight(chuck, bruce) == True\n\tassert fight(dave, carl) == False\n\tassert chuck.is_alive == True\n\tassert bruce.is_alive == False\n\tassert carl.is_alive == True\n\tassert dave.is_alive == False\n\tassert fight(carl, mark) == False\n\tassert carl.is_alive == False\n\tassert fight(bob, mike) == False\n\tassert fight(lancelot, rog) == True\n\n\t# battle tests\n\tmy_army = Army()\n\tmy_army.add_units(Defender, 1)\n\n\tenemy_army = Army()\n\tenemy_army.add_units(Warrior, 2)\n\n\tarmy_3 = Army()\n\tarmy_3.add_units(Warrior, 1)\n\tarmy_3.add_units(Defender, 1)\n\n\tarmy_4 = Army()\n\tarmy_4.add_units(Warrior, 2)\n\n\tbattle = Battle()\n\n\tassert battle.fight(my_army, enemy_army) == False\n\tassert battle.fight(army_3, army_4) == True\n\tprint(\"Coding complete? Let's try tests!\")\n\nif __name__ == '__main__':\n\t# These \"asserts\" using only for self-checking and not necessary for auto-testing\n\n\t# fight tests\n\tchuck = Warrior()\n\tbruce = Warrior()\n\tcarl = Knight()\n\tdave = Warrior()\n\tmark = Warrior()\n\tbob = Defender()\n\tmike = Knight()\n\trog = Warrior()\n\tlancelot = Defender()\n\teric = Vampire()\n\tadam = Vampire()\n\trichard = Defender()\n\togre = Warrior()\n\n\tassert fight(chuck, bruce) == True\n\tassert fight(dave, carl) == False\n\tassert chuck.is_alive == True\n\tassert bruce.is_alive == False\n\tassert carl.is_alive == True\n\tassert dave.is_alive == False\n\tassert fight(carl, mark) == False\n\tassert carl.is_alive == False\n\tassert fight(bob, mike) == False\n\tassert fight(lancelot, rog) == True\n\tassert fight(eric, richard) == False\n\tassert fight(ogre, adam) == True\n\n\t# battle tests\n\tmy_army = Army()\n\tmy_army.add_units(Defender, 2)\n\tmy_army.add_units(Vampire, 2)\n\tmy_army.add_units(Warrior, 1)\n\n\tenemy_army = Army()\n\tenemy_army.add_units(Warrior, 2)\n\tenemy_army.add_units(Defender, 2)\n\tenemy_army.add_units(Vampire, 3)\n\n\tarmy_3 = Army()\n\tarmy_3.add_units(Warrior, 1)\n\tarmy_3.add_units(Defender, 4)\n\n\tarmy_4 = Army()\n\tarmy_4.add_units(Vampire, 3)\n\tarmy_4.add_units(Warrior, 2)\n\n\tbattle = Battle()\n\n\tassert battle.fight(my_army, enemy_army) == False\n\tassert battle.fight(army_3, army_4) == True\n\tprint(\"Coding complete? Let's try tests!\")\n","sub_path":"Incincerator/OOP Game/the-vampires.py","file_name":"the-vampires.py","file_ext":"py","file_size_in_byte":5408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"415157629","text":"from __future__ import absolute_import, division, print_function\r\nimport copy\r\nimport random\r\nimport numpy as np\r\n\r\n# 0: 'up', 1: 'left', 2: 'down', 3: 'right'\r\nMOVES = [0, 1, 2, 3]\r\nACTIONS = [(0, -1), (-1, 0), (0, 1), (1, 0)]\r\nMAXIMIZER = 1\r\nCHANCEPLAYER = 0\r\nBOARD_SIZE = 4\r\nNO_DIRECTION = -1\r\n\r\n\r\nclass Gametree:\r\n\t\"\"\"main class for the AI\"\"\"\r\n\t# Hint: Two operations are important. Grow a game tree, and then compute minimax score.\r\n\t# Hint: To grow a tree, you need to simulate the game one step.\r\n\t# Hint: Think about the difference between your move and the computer's move.\r\n\r\n\r\n\tdef __init__(self, root_state, depth_of_tree, current_score):\r\n\t\tself.initial_state = root_state\r\n\t\tself.depth = depth_of_tree\r\n\t\tself.starting_score = current_score\r\n\r\n\r\n\t# a high leven interface to return best decision to game\r\n\tdef compute_decision(self):\r\n\t\t# build a simulator tree from the root node\r\n\t\troot = Simulator(copy.deepcopy(self.initial_state), self.starting_score, MAXIMIZER, NO_DIRECTION)\r\n\t\t# run expectimax from the root node\r\n\t\troot.buildTree(0, self.depth)\r\n\t\t# evaluate all the situations\r\n\t\troot.expectimax()\r\n\t\t# find the direction with max evaluation\r\n\t\tdirection = -1\r\n\t\tmaximum = -1\r\n\t\tfor child in root.children:\r\n\t\t\tif maximum\\\r\n\t\t\t\t\t< child.evaluation:\r\n\t\t\t\tdirection = child.direction\r\n\t\t\t\tmaximum = child.evaluation\r\n\t\treturn direction\r\n\r\n\r\n\t# for comparison: randomly return a direction\r\n\tdef trivial_decision(self):\r\n\t\treturn random.randint(0, 3)\r\n\r\n\r\nclass Simulator:\r\n\tdef __init__(self, state, utility, role, direction):\r\n\t\tself.tileMatrix = state\r\n\t\tself.total_points = utility\r\n\t\tself.children = []\r\n\t\tself.role = role # 1 for max 0 for chance\r\n\t\tself.direction = direction\r\n\t\tself.evaluation = -1\r\n\r\n\t# recursively build the simulator tree on a root node\r\n\tdef buildTree(self, level, height):\r\n\t\t# leaf node case, no child\r\n\t\tif level == height:\r\n\t\t\treturn\r\n\t\t# if the node is a maximizer\r\n\t\tif self.role == MAXIMIZER:\r\n\t\t\tfor direction in MOVES:\r\n\t\t\t\tchild = Simulator(copy.deepcopy(self.tileMatrix), self.total_points, CHANCEPLAYER, direction)\r\n\t\t\t\t# if the move makes no difference, disregard it\r\n\t\t\t\tif not child.canMove(direction):\r\n\t\t\t\t\tcontinue\r\n\t\t\t\t# if the action makes a difference, perform the action and update the child's matrix and score\r\n\t\t\t\telse:\r\n\t\t\t\t\t# perform the action on the child\r\n\t\t\t\t\tchild.move(direction)\r\n\t\t\t\t\t# recursively build the tree\r\n\t\t\t\t\tchild.buildTree(level+1, height)\r\n\t\t\t\t\t# append the child to the parent's children list\r\n\t\t\t\t\tself.children.append(child)\r\n\t\t# if the node is a chance player\r\n\t\telif self.role == CHANCEPLAYER:\r\n\t\t\tfor i in range(0, BOARD_SIZE):\r\n\t\t\t\tfor j in range(0, BOARD_SIZE):\r\n\t\t\t\t\t# find a blank tile\r\n\t\t\t\t\tif not self.tileMatrix[i][j]:\r\n\t\t\t\t\t\tchild = Simulator(copy.deepcopy(self.tileMatrix), self.total_points, MAXIMIZER, NO_DIRECTION)\r\n\t\t\t\t\t\t# insert a 2 into the blank tile\r\n\t\t\t\t\t\tchild.tileMatrix[i][j] = 2\r\n\t\t\t\t\t\t# recursively build the tree\r\n\t\t\t\t\t\tchild.buildTree(level + 1, height)\r\n\t\t\t\t\t\tself.children.append(child)\r\n\r\n\r\n\t# evaluate each choice with a numerical value\r\n\tdef expectimax(self):\r\n\t\t#for leaf nodes, simply return the score of its matrix\r\n\t\tif not len(self.children):\r\n\t\t\tself.evaluation = self.total_points\r\n\t\t\treturn self.evaluation\r\n\t\t# if the current player is a maximizer:\r\n\t\telif self.role == MAXIMIZER:\r\n\t\t\t# evaluate it by the highest score of its children's\r\n\t\t\tself.evaluation = max([c.expectimax() for c in self.children])\r\n\r\n\t\t\treturn self.evaluation\r\n\r\n\t\t# if the current player is a chance player\r\n\t\telif self.role == CHANCEPLAYER:\r\n\t\t\t# evaluate it by the mean score of its children's\r\n\t\t\tself.evaluation = float(sum([c.expectimax() for c in self.children])) / len(self.children)\r\n\t\t\treturn self.evaluation\r\n\r\n\r\n\t# check if the max tile is on the corner\r\n\tdef cornered (self):\r\n\t\t# if the largest number is on the corner, boost the score by 1.5\r\n\t\tmax_tile = 0\r\n\t\tmax_row = -1\r\n\t\tmax_column = -1\r\n\t\tfor i in range(0, BOARD_SIZE):\r\n\t\t\tfor j in range(0, BOARD_SIZE):\r\n\t\t\t\tif self.tileMatrix[i][j] > max_tile:\r\n\t\t\t\t\tmax_tile = self.tileMatrix[i][j]\r\n\t\t\t\t\tmax_row = i\r\n\t\t\t\t\tmax_column = j\r\n\t\t\t\telif self.tileMatrix[i][j] == max_tile:\r\n\t\t\t\t\t# max tile can only be on the first or last row\r\n\t\t\t\t\tif i == 0 or i == 3:\r\n\t\t\t\t\t\t# if the largest tile is on the corners\r\n\t\t\t\t\t\tif j == 0 or j == 3:\r\n\t\t\t\t\t\t\t# update the cordinates\r\n\t\t\t\t\t\t\tmax_row = i\r\n\t\t\t\t\t\t\tmax_column = j\r\n\t\tif max_row == 0 or max_row == 3:\r\n\t\t\tif max_column == 0 or max_column == 3:\r\n\t\t\t\treturn True\r\n\t\treturn False\r\n\r\n\r\n\t# apply the direction to the board\r\n\tdef move(self, direction):\r\n\t\t# perform the move\r\n\t\tself.moveTiles()\r\n\t\tself.mergeTiles()\r\n\t\t#self.placeRandomTile()\r\n\t\tfor j in range(0, (4 - direction) % 4):\r\n\t\t\tself.rotateMatrixClockwise()\r\n\r\n\r\n\t# not sure what it does\r\n\tdef rotateMatrixClockwise(self):\r\n\t\ttm = self.tileMatrix\r\n\t\tfor i in range(0, int(BOARD_SIZE/2)):\r\n\t\t\tfor k in range(i, BOARD_SIZE - i - 1):\r\n\t\t\t\ttemp1 = tm[i][k]\r\n\t\t\t\ttemp2 = tm[BOARD_SIZE - 1 - k][i]\r\n\t\t\t\ttemp3 = tm[BOARD_SIZE - 1 - i][BOARD_SIZE - 1 - k]\r\n\t\t\t\ttemp4 = tm[k][BOARD_SIZE - 1 - i]\r\n\t\t\t\ttm[BOARD_SIZE - 1 - k][i] = temp1\r\n\t\t\t\ttm[BOARD_SIZE - 1 - i][BOARD_SIZE - 1 - k] = temp2\r\n\t\t\t\ttm[k][BOARD_SIZE - 1 - i] = temp3\r\n\t\t\t\ttm[i][k] = temp4\r\n\r\n\r\n\tdef moveTiles(self):\r\n\t\ttm = self.tileMatrix\r\n\t\tfor i in range(0, BOARD_SIZE):\r\n\t\t\tfor j in range(0, BOARD_SIZE - 1):\r\n\t\t\t\twhile tm[i][j] == 0 and sum(tm[i][j:]) > 0:\r\n\t\t\t\t\tfor k in range(j, BOARD_SIZE - 1):\r\n\t\t\t\t\t\ttm[i][k] = tm[i][k + 1]\r\n\t\t\t\t\ttm[i][BOARD_SIZE - 1] = 0\r\n\r\n\r\n\tdef mergeTiles(self):\r\n\t\ttm = self.tileMatrix\r\n\t\tfor i in range(0, BOARD_SIZE):\r\n\t\t\tfor k in range(0, BOARD_SIZE - 1):\r\n\t\t\t\tif tm[i][k] == tm[i][k + 1] and tm[i][k] != 0:\r\n\t\t\t\t\ttm[i][k] = tm[i][k] * 2\r\n\t\t\t\t\ttm[i][k + 1] = 0\r\n\t\t\t\t\tself.total_points += tm[i][k]\r\n\t\t\t\t\tself.moveTiles()\r\n\r\n\r\n\t# check if the game can contitnue\r\n\tdef checkIfCanGo(self):\r\n\t\ttm = self.tileMatrix\r\n\t\tfor i in range(0, BOARD_SIZE ** 2):\r\n\t\t\tif tm[int(i / BOARD_SIZE)][i % BOARD_SIZE] == 0:\r\n\t\t\t\treturn True\r\n\t\tfor i in range(0, BOARD_SIZE):\r\n\t\t\tfor j in range(0, BOARD_SIZE - 1):\r\n\t\t\t\tif tm[i][j] == tm[i][j + 1]:\r\n\t\t\t\t\treturn True\r\n\t\t\t\telif tm[j][i] == tm[j + 1][i]:\r\n\t\t\t\t\treturn True\r\n\t\treturn False\r\n\r\n\r\n\t# check if the direction makes a difference\r\n\tdef canMove(self, direction):\r\n\t\t# always rotate the matrix to a fix direction\r\n\t\tfor i in range(0, direction):\r\n\t\t\tself.rotateMatrixClockwise()\r\n\t\t# check if the rotated matrix can move in the direction\r\n\t\ttm = self.tileMatrix\r\n\t\tfor i in range(0, BOARD_SIZE):\r\n\t\t\tfor j in range(1, BOARD_SIZE):\r\n\t\t\t\tif tm[i][j-1] == 0 and tm[i][j] > 0:\r\n\t\t\t\t\treturn True\r\n\t\t\t\telif (tm[i][j-1] == tm[i][j]) and tm[i][j-1] != 0:\r\n\t\t\t\t\treturn True\r\n\t\treturn False\r\n","sub_path":"ai.py","file_name":"ai.py","file_ext":"py","file_size_in_byte":6682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"644772166","text":"import numpy as np\r\nimport subprocess\r\nimport os\r\n\r\n\r\ndef ioa_with_anchors(anchors_min, anchors_max, box_min, box_max):\r\n # calculate the overlap proportion between the anchor and all bbox for supervise signal,\r\n # the length of the anchor is 0.01\r\n len_anchors = anchors_max - anchors_min\r\n int_xmin = np.maximum(anchors_min, box_min)\r\n int_xmax = np.minimum(anchors_max, box_max)\r\n inter_len = np.maximum(int_xmax - int_xmin, 0.)\r\n scores = np.divide(inter_len, len_anchors)\r\n return scores\r\n\r\n\r\ndef iou_with_anchors(anchors_min, anchors_max, box_min, box_max):\r\n \"\"\"Compute jaccard score between a box and the anchors.\r\n \"\"\"\r\n len_anchors = anchors_max - anchors_min\r\n int_xmin = np.maximum(anchors_min, box_min)\r\n int_xmax = np.minimum(anchors_max, box_max)\r\n inter_len = np.maximum(int_xmax - int_xmin, 0.)\r\n union_len = len_anchors - inter_len + box_max - box_min\r\n # print inter_len,union_len\r\n jaccard = np.divide(inter_len, union_len)\r\n return jaccard\r\n\r\n\r\ndef evaluate_proposals(cfg):\r\n python = '/home/nii/anaconda3/envs/py27/bin/python'\r\n subprocess.call(' '.join([\r\n 'cd densevid_eval',\r\n '&&',\r\n python, 'evaluate.py',\r\n '-s', os.path.abspath(cfg.DATA.RESULT_PATH),\r\n '-o', os.path.abspath(cfg.SCORE_PATH),\r\n '-d'\r\n ]), shell=True)\r\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"32858811","text":"# -*- coding: utf-8 -*-\nfrom PySide import QtGui, QtCore\nfrom TestCompile import Ui_Form\n\nclass MainWindow(QtGui.QWidget,Ui_Form):\n def __init__(self):\n super(MainWindow,self).__init__()\n self.setupUi(self)\n\n #Init Window\n self.show()\n\napp = QtGui.QApplication([])\nMyWindow = MainWindow()\nMyWindow.show()\napp.exec_()\n","sub_path":"src/Ui/s10s36_Import_UI.py","file_name":"s10s36_Import_UI.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"78224374","text":"# =================================================================\n#\n# Authors: Tom Kralidis \n#\n# Copyright (c) 2019 Tom Kralidis\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#\n# =================================================================\n\nimport csv\nimport io\nimport pytest\n\nfrom pygeoapi.formatter.csv_ import CSVFormatter\n\n\n@pytest.fixture()\ndef fixture():\n data = {\n 'features': [{\n 'geometry': {\n 'type': 'Point',\n 'coordinates': [\n -130.44472222222223,\n 54.28611111111111\n ]\n },\n 'type': 'Feature',\n 'properties': {\n 'id': 1972,\n 'foo': 'bar',\n 'title': None,\n },\n 'id': 48693\n }]\n }\n\n return data\n\n\ndef test_csv__formatter(fixture):\n f = CSVFormatter({'geom': True})\n f_csv = f.write(data=fixture)\n\n buffer = io.StringIO(f_csv.decode('utf-8'))\n reader = csv.DictReader(buffer)\n\n header = list(reader.fieldnames)\n\n assert f.mimetype == 'text/csv; charset=utf-8'\n\n assert len(header) == 5\n\n assert 'x' in header\n assert 'y' in header\n\n data = next(reader)\n assert data['x'] == '-130.44472222222223'\n assert data['y'] == '54.28611111111111'\n assert data['id'] == '1972'\n assert data['foo'] == 'bar'\n assert data['title'] == ''\n","sub_path":"tests/test_csv__formatter.py","file_name":"test_csv__formatter.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"468297201","text":"import os \nimport sys\nimport re\nimport pandas as pd\nimport collections\nimport math\nimport numpy as np\nimport matplotlib \nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom multiprocessing import Pool\nfrom itertools import chain, combinations, product,compress\n\nimport cgatcore.experiment as E\n\ndef main(argv=sys.argv):\n\n##################\n# Option parsing \n##################\n\n parser = E.OptionParser(version=\"%prog version: $Id$\",\n usage=globals()[\"__doc__\"])\n\n parser.add_option(\"-d\", \"--dir\", dest=\"bus_dir\", type =\"string\" ,\n help=\"directory bus output is located within\")\n\n parser.add_option(\"-t\", \"--t2gmap\", dest=\"t2gmap\", type =\"string\" ,\n help=\"Transcript to gene map file\")\n\n parser.add_option(\"-b\", \"--barcodethresh\", dest=\"thresh\", type =\"int\" ,\n help=\"Minimum threshold for cellular barcodes\") \n\n parser.add_option(\"-o\", \"--out\", dest=\"outfile\", type =\"string\" ,\n help=\"Gene count matrix outfile\")\n\n parser.add_option(\"-e\", \"--expectedcells\", dest=\"exp_cells\", type =\"int\" ,\n help=\"Expected number of cells\")\n\n parser.add_option( \"--threads\", dest=\"threads\", type =\"int\" ,\n help=\"Number of threads\")\n \n\n parser.set_defaults(bus_dir=None, t2gmap = 'transcript2geneMap.tsv', thresh = 100, outfile = 'kallisto.dir/output.bus.mtx', exp_cells = 1000, threads = 1)\n\n (options, args) = E.start(parser)\n\n bus_dir = options.bus_dir\n t2gmap = options.t2gmap\n barcode_thresh = options.thresh\n outfile = options.outfile\n exp_cells = options.exp_cells\n threads = options.threads\n\n # Bus files\n\n matrix_ec = bus_dir + \"/matrix.ec\"\n transcripts = bus_dir + \"/transcripts.txt\"\n sorted_text = bus_dir + \"/output.bus.sorted.txt\"\n\n\n def t2g_dict(infile):\n d={}\n with open(infile) as f:\n next(f)\n for line in f:\n (key, value)=line.split()\n d[key]=value\n return(d)\n \n # load transcripts \n trlist = []\n with open(bus_dir+'/transcripts.txt') as f:\n for line in f:\n trlist.append(line.rstrip('\\n'))\n\n # Dictionaries for transcript to gene and for gene to gene symbol\n tr2g = t2g_dict(t2gmap)\n \n # load equivalence classes\n ecs = {}\n with open(matrix_ec) as f:\n for line in f:\n l = line.split()\n ec = int(l[0])\n trs = [int(x) for x in l[1].split(',')]\n ecs[ec] = trs\n\n def ec2g(ec):\n if ec in ecs:\n return list(set(tr2g[trlist[t]] for t in ecs[ec])) \n else:\n return []\n\n # load kallisto bus output dataset\n\n cell_gene = collections.defaultdict(lambda: collections.defaultdict(float))\n pbar=None\n pumi=None\n with open(bus_dir+'/output.bus.sorted.txt') as f:\n gs = set()\n for line in f:\n l = line.split()\n barcode,umi,ec,count = line.split()\n ec = int(ec)\n \n if barcode == pbar:\n # same barcode\n if umi == pumi:\n # same UMI, let's update with intersection of genelist\n gl = ec2g(ec)\n gs.intersection_update(gl)\n else:\n # new UMI, process the previous gene set\n for g in gs:\n cell_gene[barcode][g] += 1.0/len(gs)\n # record new umi, reset gene set\n pumi = umi\n gs = set(ec2g(ec))\n else:\n # work with previous gene list\n for g in gs:\n cell_gene[pbar][g] += 1.0/len(gs)\n \n if sum(cell_gene[pbar][g] for g in cell_gene[pbar]) < 10:\n del cell_gene[pbar]\n \n pbar = barcode\n pumi = umi\n \n gs = set(ec2g(ec))\n #remember the last gene\n for g in gs:\n cell_gene[pbar][g] += 1.0/len(gs)\n \n if sum(cell_gene[pbar][g] for g in cell_gene[pbar]) < 10:\n del cell_gene[pbar]\n\n barcode_hist = collections.defaultdict(int)\n for barcode in cell_gene:\n cg = cell_gene[barcode]\n s = len([cg[g] for g in cg])\n barcode_hist[barcode] += s\n\n threshold = 0 # this filters the data by gene count\n bcv = [x for b,x in barcode_hist.items() if x > threshold] \n fig, ax = plt.subplots()\n ax.hist(bcv,bins=40, log=True)\n \n ax.set_ylabel('Number barcodes', color='k')\n ax.set_xlabel('Number of gene counts', color='k')\n\n fig.savefig(bus_dir+'/Number_barcodes_vs_gene_counts.png')\n\n\n barcodes_to_use = [b for b,x in barcode_hist.items() if x > 0 ]\n\n num_entries = 0\n for barcode in barcodes_to_use:\n num_entries += len([x for x in cell_gene[barcode].values() if round(x)>0])\n\n genes = list(set(tr2g[t] for t in tr2g))\n gene_to_id = dict((g,i+1) for i,g in enumerate(genes))\n\n with open(outfile, 'w') as of:\n of.write('%%MatrixMarket matrix coordinate real general\\n%\\n')\n #number of genes\n of.write(\"%d %d %d\\n\"%(len(genes), len(barcodes_to_use), num_entries))\n bcid = 0\n for barcode in barcodes_to_use:\n bcid += 1\n cg = cell_gene[barcode]\n gl = [(gene_to_id[g],round(cg[g])) for g in cg if round(cg[g]) > 0]\n gl.sort()\n for x in gl:\n of.write(\"%d %d %d\\n\"%(x[0],bcid,x[1]))\n\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n\n","sub_path":"scpipelines/bus2count2.py","file_name":"bus2count2.py","file_ext":"py","file_size_in_byte":5625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"631436619","text":"'''\nPara ler 4 números. Calcule e informe a soma dos números lidos!\n'''\nsoma = 0\nqtde_pos = 0\n\nqtde = int(input('Quantidade de iterações: '))\n\nfor i in range(qtde):\n num = int(input('Informe o {} valor: '.format(i + 1)))\n soma = soma + num\n if (num > 0):\n qtde_pos += 1\n # soma += num\n\n \n\n\nprint(soma)\n","sub_path":"semana_06/exemplo2.py","file_name":"exemplo2.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"307556765","text":"\nimport warnings\nimport datetime\nfrom matplotlib import pyplot\nfrom matplotlib.dates import (YearLocator, MonthLocator, DayLocator,\n HourLocator, MinuteLocator, SecondLocator,\n DateFormatter, epoch2num)\nfrom matplotlib.ticker import FixedLocator, FixedFormatter\nimport Chandra.Time\nimport numpy as np\n\n# Default tick locator and format specification for making nice time axes\n# majorLoc, major_kwargs, major_fmt, minorLoc, minor_kwargs\n\nTICKLOCS = (\n (YearLocator, {'base': 2}, '%Y', YearLocator, {'base': 1}),\n (YearLocator, {'base': 1}, '%Y', MonthLocator, {'bymonth': (1, 4, 7, 10)}),\n\n (MonthLocator, {'bymonth': list(range(1, 13, 6))}, '%Y-%b', MonthLocator, {}),\n (MonthLocator, {'bymonth': list(range(1, 13, 4))}, '%Y-%b', MonthLocator, {}),\n (MonthLocator, {'bymonth': list(range(1, 13, 3))}, '%Y-%b', MonthLocator, {}),\n (MonthLocator, {'bymonth': list(range(1, 13, 2))}, '%Y-%b', MonthLocator, {}),\n (MonthLocator, {}, '%Y-%b', DayLocator, {'bymonthday': (1, 15)}),\n\n (DayLocator, {'interval': 10}, '%Y:%j', DayLocator, {}),\n (DayLocator, {'interval': 5}, '%Y:%j', DayLocator, {}),\n (DayLocator, {'interval': 4}, '%Y:%j', DayLocator, {}),\n (DayLocator, {'interval': 2}, '%Y:%j', DayLocator, {}),\n (DayLocator, {'interval': 1}, '%Y:%j', HourLocator, {'byhour': (0, 6, 12, 18)}),\n\n (HourLocator, {'byhour': list(range(0, 24, 12))}, '%j:%H:00', HourLocator, {}),\n (HourLocator, {'byhour': list(range(0, 24, 6))}, '%j:%H:00', HourLocator, {}),\n (HourLocator, {'byhour': list(range(0, 24, 4))}, '%j:%H:00', HourLocator, {}),\n (HourLocator, {'byhour': list(range(0, 24, 2))}, '%j:%H:00', HourLocator, {}),\n (HourLocator, {}, '%j:%H:00', MinuteLocator, {'byminute': (0, 15, 30, 45)}),\n\n (MinuteLocator, {'byminute': (0, 30)}, '%j:%H:%M', MinuteLocator, {'byminute': list(range(0,60,5))}),\n (MinuteLocator, {'byminute': (0, 15, 30, 45)}, '%j:%H:%M', MinuteLocator, {'byminute': list(range(0,60,5))}),\n (MinuteLocator, {'byminute': list(range(0, 60, 10))}, '%j:%H:%M', MinuteLocator, {}),\n (MinuteLocator, {'byminute': list(range(0, 60, 5))}, '%j:%H:%M', MinuteLocator, {}),\n (MinuteLocator, {'byminute': list(range(0, 60, 4))}, '%j:%H:%M', MinuteLocator, {}),\n (MinuteLocator, {'byminute': list(range(0, 60, 2))}, '%j:%H:%M', MinuteLocator, {}),\n (MinuteLocator, {}, '%j:%H:%M', SecondLocator, {'bysecond': (0, 15, 30, 45)}),\n\n (SecondLocator, {'bysecond': (0, 30)}, '%H:%M:%S', SecondLocator, {'bysecond': list(range(0,60,5))}),\n (SecondLocator, {'bysecond': (0, 15, 30, 45)}, '%H:%M:%S', SecondLocator, {'bysecond': list(range(0,60,5))}),\n (SecondLocator, {'bysecond': list(range(0, 60, 10))}, '%H:%M:%S', SecondLocator, {}),\n (SecondLocator, {'bysecond': list(range(0, 60, 5))}, '%H:%M:%S', SecondLocator, {}),\n (SecondLocator, {'bysecond': list(range(0, 60, 4))}, '%H:%M:%S', SecondLocator, {}),\n (SecondLocator, {'bysecond': list(range(0, 60, 2))}, '%H:%M:%S', SecondLocator, {}),\n (SecondLocator, {}, '%H:%M:%S', SecondLocator, {}),\n )\n\ndef set_time_ticks(plt, ticklocs=None):\n \"\"\"\n Pick nice values to show time ticks in a date plot.\n Example::\n \n x = cxctime2plotdate(np.linspace(0, 3e7, 20))\n y = np.random.normal(size=len(x))\n fig = pylab.figure()\n plt = fig.add_subplot(1, 1, 1)\n plt.plot_date(x, y, fmt='b-')\n ticklocs = set_time_ticks(plt)\n fig.autofmt_xdate()\n fig.show()\n The returned value of ``ticklocs`` can be used in subsequent date plots to\n force the same major and minor tick locations and formatting. Note also\n the use of the high-level fig.autofmt_xdate() convenience method to configure\n vertically stacked date plot(s) to be well-formatted.\n :param plt: ``matplotlib.axes.AxesSubplot`` object (from ``pylab.figure.add_subplot``)\n :param ticklocs: list of major/minor tick locators ala the default ``TICKLOCS``\n :rtype: tuple with selected ticklocs as first element\n \"\"\"\n\n locs = ticklocs or TICKLOCS\n\n for majorLoc, major_kwargs, major_fmt, minorLoc, minor_kwargs in locs:\n plt.xaxis.set_major_locator(majorLoc(**major_kwargs))\n plt.xaxis.set_minor_locator(minorLoc(**minor_kwargs))\n plt.xaxis.set_major_formatter(DateFormatter(major_fmt))\n\n majorticklocs = plt.xaxis.get_ticklocs()\n if len(majorticklocs) >= 5:\n break\n\n return ((majorLoc, major_kwargs, major_fmt, minorLoc, minor_kwargs), )\n\ndef remake_ticks(ax):\n \"\"\"Remake the date ticks for the current plot if space is pressed. If '0'\n is pressed then set the date ticks to the maximum possible range.\n \"\"\"\n ticklocs = set_time_ticks(ax)\n ax.figure.canvas.draw()\n \ndef plot_cxctime(times, y, fmt='-b', fig=None, ax=None, yerr=None, xerr=None, tz=None,\n state_codes=None, interactive=True, **kwargs):\n \"\"\"Make a date plot where the X-axis values are in CXC time. If no ``fig``\n value is supplied then the current figure will be used (and created\n automatically if needed). If yerr or xerr is supplied, ``errorbar()`` will be\n called and any additional keyword arguments will be passed to it. Otherwise\n any additional keyword arguments (e.g. ``fmt='b-'``) are passed through to\n the ``plot()`` function. Also see ``errorbar()`` for an explanation of the possible\n forms of *yerr*/*xerr*.\n If the ``state_codes`` keyword argument is provided then the y-axis ticks and\n tick labels will be set accordingly. The ``state_codes`` value must be a list\n of (raw_count, state_code) tuples, and is normally set to ``msid.state_codes``\n for an MSID object from fetch().\n If the ``interactive`` keyword is True (default) then the plot will be redrawn\n at the end and a GUI callback will be created which allows for on-the-fly\n update of the date tick labels when panning and zooming interactively. Set\n this to False to improve the speed when making several plots. This will likely\n require issuing a plt.draw() or fig.canvas.draw() command at the end.\n :param times: CXC time values for x-axis (date)\n :param y: y values\n :param fmt: plot format (default = '-b')\n :param fig: pyplot figure object (optional)\n :param yerr: error on y values, may be [ scalar | N, Nx1, or 2xN array-like ] \n :param xerr: error on x values in units of DAYS (may be [ scalar | N, Nx1, or 2xN array-like ] )\n :param tz: timezone string\n :param state_codes: list of (raw_count, state_code) tuples\n :param interactive: use plot interactively (default=True, faster if False)\n :param **kwargs: keyword args passed through to ``plot_date()`` or ``errorbar()``\n :rtype: ticklocs, fig, ax = tick locations, figure, and axes object.\n \"\"\"\n\n if fig is None:\n fig = pyplot.gcf()\n\n if ax is None:\n ax = fig.gca()\n\n if yerr is not None or xerr is not None:\n ax.errorbar(cxctime2plotdate(times), y, yerr=yerr, xerr=xerr, fmt=fmt, **kwargs)\n ax.xaxis_date(tz)\n else:\n ax.plot_date(cxctime2plotdate(np.repeat(times, 2)[1:]), np.repeat(y, 2)[:-1], fmt=fmt, **kwargs)\n ticklocs = set_time_ticks(ax)\n fig.autofmt_xdate()\n\n if state_codes is not None:\n counts, codes = list(zip(*state_codes))\n ax.yaxis.set_major_locator(FixedLocator(counts))\n ax.yaxis.set_major_formatter(FixedFormatter(codes))\n\n # If plotting interactively then show the figure and enable interactive resizing\n if interactive and hasattr(fig, 'show'):\n fig.canvas.draw()\n ax.callbacks.connect('xlim_changed', remake_ticks)\n\n return ticklocs, fig, ax\n\n\ndef cxctime2plotdate(times):\n \"\"\"\n Convert input CXC time (sec) to the time base required for the matplotlib\n plot_date function (days since start of year 1).\n \n :param times: iterable list of times\n :rtype: plot_date times\n \"\"\"\n \n # Find the plotdate of first time and use a relative offset from there\n t0 = Chandra.Time.DateTime(times[0]).unix\n plotdate0 = epoch2num(t0)\n\n return (np.asarray(times) - times[0]) / 86400. + plotdate0\n ","sub_path":"fot_trend/plot_cxctime_custom.py","file_name":"plot_cxctime_custom.py","file_ext":"py","file_size_in_byte":8421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"394477004","text":"import logging\nimport requests\n\n\nclass SpaceHandler(logging.Handler):\n def __init__(self, URL, *args, **kwargs):\n self.URL = URL\n super().__init__(*args, **kwargs)\n\n def emit(self, record):\n client = requests.Session()\n client.get(self.URL + '/auth/')\n print(record)\n print(client.cookies)\n csrf_token = client.cookies['csrftoken']\n client.post(self.URL + '/auth/', data=dict(username='Archie',\n password='kuku',\n csrfmiddlewaretoken=csrf_token))\n client.get(self.URL + '/log/')\n csrf_token = client.cookies['csrftoken']\n client.post(self.URL + '/log/', data=dict(message=record.message,\n name=record.name,\n levelname=record.levelname,\n asctime=record.asctime,\n csrfmiddlewaretoken=csrf_token))\n\n\nlogger = logging.getLogger('spam_application')\nlogger.setLevel(\"DEBUG\")\n\n# create console handler with a higher log level\nch = logging.StreamHandler()\nspace_handler = SpaceHandler('http://127.0.0.1:8000')\nch.setLevel(\"DEBUG\")\nspace_handler.setLevel(\"DEBUG\")\n\n# create formatter and add it to the handlers\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\nch.setFormatter(formatter)\nspace_handler.setFormatter(formatter)\nlogger.addHandler(ch)\nlogger.addHandler(space_handler)\n\nlogger.info('creating an instance of auxiliary_module.Auxiliary')","sub_path":"logger_1.py","file_name":"logger_1.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"433677021","text":"# labelImgYOLO2VoTTCSV\n# U can convert labelImgYOLO CSV file to VoTTCSV file\n\nimport os\nimport numpy as np\nimport cv2\n\n\ndef labelImgYOLO2VoTTCSV(path=\"./\", folder = None, label = None):\n \"\"\"\n path is an image path without image folder name\n folder is folder name with out path\n label is what U wanna add to CSV\n \"\"\"\n if folder is None or label is None:\n print(\"Plz input name and label val\")\n return\n filenameList = os.listdir(path + folder + \"/\")\n\n with open(path + folder + \".csv\", 'w', errors='ignore') as out:\n out.write('\"image\",\"xmin\",\"ymin\",\"xmax\",\"ymax\",\"label\"\\n')\n\n for filename in filenameList:\n extension = filename[-3:]\n if extension == 'jpg' or extension == 'jpeg' or extension == 'png'or extension == 'gif':\n imgname = filename\n elif extension == 'txt':\n if imgname[:-4] == filename[:-4]:\n img = cv2.imread(path + folder + \"/\" + imgname)\n img_y, img_x = img.shape[:2]\n with open(path + folder + \"/\" + filename, 'r', errors='ignore') as textfile:\n lines = textfile.readlines()\n for line in lines:\n x, y, w, h = line.split()[1:]\n x = float(x)\n y = float(y)\n w = float(w)\n h = float(h)\n out.write('\"{}\",{},{},{},{},{}\\n'.format(imgname, x * img_x - (w * img_x / 2), y * img_y - (h * img_y / 2), x * img_x + (w * img_x / 2), y * img_y + (h * img_y / 2), label))\n else:\n print(\"Unexpected file : {}\".format(filename))\n ","sub_path":"README.py","file_name":"README.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"296195432","text":"import random\nprint(\"new\")\na0, a1, a2, a3 = 0, 0, 0, 0\nfor i in range(4):\n globals()['a' + str(i)] = random.randint(50, 80)\n\n\nclass Main:\n def __init__(self, m, n, a0, a1, a2, a3):\n self.a0, self.a1, self.a2, self.a3, self.row, self.column = a0, a1, a2, a3, m, n\n self.main_func()\n\n def main_func(self):\n self.make_mass(self.row, self.column)\n self.y_d0_x0()\n self.make_second_mass()\n self.show()\n\n def make_mass(self, size1, size2):\n self.main_mass = []\n for i in range(size1):\n temp_mass = []\n for j in range(size2):\n temp_mass.append(float(random.randint(0, 20)))\n self.main_mass.append(temp_mass)\n\n def make_second_mass(self):\n self.second_mass = []\n for i in range(self.row):\n temp_mass = []\n for j in range(self.column):\n temp_mass.append(round((self.main_mass[i][j] - self.x0_mass[j]) / self.dx_mass[j], 2))\n self.second_mass.append(temp_mass)\n\n def y_d0_x0(self):\n self.dx_mass, self.x0_mass, self.y_mass, self.mass, self.average_y, self.new_mass, self.y_x0 = [], [], [], [\n \"Num\", \"X1\",\n \"X2\", \"X3\",\n \"Y\", \"Xn1\",\n \"Xn2\",\n \"Xn3\"], 0, [], self.a0\n for i in range(self.row):\n self.y_mass.append(\n self.a0 + self.main_mass[i][0] * self.a1 + self.main_mass[i][1] * self.a2 + self.main_mass[i][\n 2] * self.a3)\n\n for i in range(self.column):\n temp_mass = []\n for j in range(self.row):\n temp_mass.append(self.main_mass[j][i])\n self.x0_mass.append(((max(temp_mass) + min(temp_mass)) / 2))\n\n for i in range(self.column):\n temp_mass = []\n for j in range(self.row):\n temp_mass.append(self.main_mass[j][i])\n self.dx_mass.append(self.x0_mass[i] - min(temp_mass))\n\n for i in range(len(self.y_mass)):\n self.average_y += self.y_mass[i]\n\n self.average_y = self.average_y / len(self.y_mass)\n\n for i in range(len(self.y_mass)):\n if self.y_mass[i] < self.average_y:\n self.new_mass.append(self.average_y - self.y_mass[i])\n\n self.var = self.average_y - min(self.new_mass)\n\n for i in range(3):\n self.y_x0 += globals()['a' + str(i + 1)] * self.x0_mass[i]\n self.dx_mass.append(self.average_y)\n self.x0_mass.append(round(self.y_x0, 2))\n\n for i in range(3):\n self.dx_mass.append(\"---\")\n self.x0_mass.append(\"---\")\n\n def show(self):\n print(\"{:<2}\".format(self.mass[0]), \"{:>3}\".format(self.mass[1]), \"{:>6}\".format(self.mass[2]),\n \"{:>6.5}\".format(self.mass[3]), \"{:>5.5}\".format(self.mass[4]), \"{:>7}\".format(self.mass[5]),\n \"{:>7}\".format(self.mass[6]), \"{:>5.5}\".format(self.mass[7]))\n for i in range(self.row):\n print(\"{:<3}\".format(i + 1), end=\" \")\n for j in range(self.column):\n print(\"{:<6}\".format(self.main_mass[i][j]), end=\" \")\n print(\"{:<6}\".format(self.y_mass[i]), end=\" \")\n for k in range(self.column):\n print(\"{:<6}\".format(self.second_mass[i][k]), end=\" \")\n print(\"|\")\n\n print(\"{:<3}\".format(\"x0\"), end=\" \")\n for i in self.x0_mass:\n print(\"{:<6}\".format(i), end=\" \")\n print(\"{:<5}\".format(\"|\\ndx\"), end=\" \")\n for i in self.dx_mass:\n print(\"{:<6}\".format(i), end=\" \")\n print(\"|\")\n for i in range(4):\n print(\"a\" + str(i) + \" = \", globals()['a' + str(i)], end=\", \")\n print(\"Середнє Y - \", self.average_y, end=\", \")\n print(\"> Y - \" + str(self.var) + \".\")\n\n\nif __name__ == \"__main__\":\n t = Main(8, 3, a0, a1, a2, a3)\n","sub_path":"Lab1/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":3868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"340957874","text":"#!/usr/bin/env python3\r\n\r\n# an example Python program\r\n# by Erin Coffey\r\n# 10 January 2018\r\n\r\nimport sys\r\nMODULES_DIR = \"/Users/erin/Documents/Development/Python/modules/\"\r\nsys.path.append(MODULES_DIR)\r\n\r\n# import local module for welcome message\r\nimport stringer\r\n# import random for dice rolls\r\nimport random\r\n# import module for tracking lost time\r\nimport timer\r\n\r\nNAME = \"Pig Dice\"\r\nAUTHOR = \"Erin Coffey\"\r\n\r\ndef display_rules():\r\n print(\"\\nHow to play the PIG game...\")\r\n print()\r\n print(\"* See how many turns it takes to score 20 points.\")\r\n print(\"* A turn ends when you HOLD or, roll a '1'\")\r\n print(\"* If you roll a '1', you lose ALL points for the turn.\")\r\n print(\"* If you HOLD, you save all points for the turn.\")\r\n print()\r\n# end display_rules\r\n\r\ndef take_turn(turn, score, game_over):\r\n print(\"TURN:\\t\", str(turn))\r\n score_this_turn = 0\r\n turn_over = False\r\n\r\n while not turn_over:\r\n choice = input(\"Roll or Hold? (r/h): \")\r\n if choice.lower() == \"r\":\r\n turn, score, score_this_turn, turn_over = \\\r\n roll_die(turn, score, score_this_turn)\r\n elif choice.lower() == \"h\":\r\n turn, score, turn_over, game_over = \\\r\n hold_turn(turn, score, score_this_turn)\r\n else:\r\n print(\"Invalid selection. Please try again.\")\r\n return turn, score, game_over\r\n# end take_turn\r\n\r\ndef roll_die(turn, score, score_this_turn):\r\n die = random.randint(1,6)\r\n print(\"DIE:\\t\" + str(die))\r\n if die == 1:\r\n score_this_turn = 0\r\n turn += 1\r\n print(\"Turn over. No score for you!\\n\")\r\n turn_over = True\r\n else:\r\n score_this_turn += die\r\n turn_over = False\r\n return turn, score, score_this_turn, turn_over\r\n# end roll_die\r\n\r\ndef hold_turn(turn, score, score_this_turn):\r\n print(\"Score for turn:\\t\" + str(score_this_turn))\r\n score += score_this_turn\r\n print(\"Total Score:\\t\" + str(score))\r\n turn_over = True\r\n game_over = False\r\n if score >= 20:\r\n print(\"You completed the game in \"+ str(turn) + \" turn\", end = \"\")\r\n if turn > 1:\r\n print(\"s.\")\r\n else:\r\n print(\"!!!\")\r\n game_over = True\r\n return turn, score, turn_over, game_over\r\n turn += 1\r\n return turn, score, turn_over, game_over\r\n# end hold_turn\r\n\r\ndef play_game():\r\n game_over = False\r\n turn = 1\r\n score = 0\r\n while not game_over:\r\n turn, score, game_over = take_turn(turn, score, game_over)\r\n print()\r\n print(\"Game over!\")\r\n# end play_game\r\n\r\ndef main():\r\n myTimer = timer.begin_timer()\r\n stringer.show_welcome(NAME)\r\n display_rules()\r\n should_Exit = False\r\n \r\n while not should_Exit:\r\n print()\r\n play_game()\r\n\r\n choice = input(\"Try again? (y/n): \")\r\n if choice.lower() != \"y\":\r\n should_Exit = True\r\n # end while loop\r\n timer.stop_timer(myTimer)\r\n print(\"Bye!\")\r\n# end main\r\n\r\n\r\n#if the current module is the main module\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n","sub_path":"examples/pig_dice.py","file_name":"pig_dice.py","file_ext":"py","file_size_in_byte":3052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"159572954","text":"\n'''\n\nNotes from Freedom EVOware Sotware manual V2.3\n15.24.2 - Worklist file format\n- Text file containing pipetting instructions\n- Individual lines: \"records\"\n- - Records start with a single character and are followed by 1 or more parameters, separated by semicolons\n- Record types available:\n - Aspirate\n - A;RackLabel;RackID;RackType;Position;TubeID;Volume;LiquidClass;TipType;TipMask;ForcedRackType\n - Dispense\n - D;RackLabel;RackID;RackType;Position;TubeID;Volume;LiquidClass;TipType;TipMask;ForcedRackType\n - [see 15.24.2.1 \"parameters for aspirate and dispense records\", and \"15-41 for details)\n - Wash tips / replace DITIs\n - W;\n - W1;\n - W2;\n - W3;\n - W4;\n - Washes the tip or replaced the DITI which was used by the preceding aspirate record\n - No parameters\n - Decontamination wash\n - WD;\n - Decomntamination wash followed by normal wash\n - No parameters\n - Flush\n - F;\n - Discards tip contents without washing them or dropping DITIs\n - Break\n - B;\n - Forces excution of previously specified aspirate/dispense/wash actions which have not yet been executed\n - Always resets the DITI type to the type selected in the worklist command\n - If a Break record is not specified, commands will be executed in groups to optimize efficiency\n - Set DITI type (disposable tip type)\n - S;DITI_index\n - Can only be used at the very beginning of the worklist or directly after a break record\n - \n - Comment\n - C;comment\n - Ignored by the EVO\n - **Reagent distribution**\n - R;AspirateParameters;DispenseParameters;Volume;LiquidClass;NoOfDitiReuses;NoOfMultiDisp;Direction[;ExcludeDestWell]\n where\n - AspirateParameters=SrcRackLabel;SrcRackID;SrcRackType;SrcPosStart;SrcPosEnd;\n - DispenseParameters = DestRackLabel;DestRackID;DestRackType;DestPostStart;DestPosEnd\n\n- **Parameters for aspirate and dispense records**\n - RackLabel: User-defined label assigned to the labware\n - RackID: labware barcode\n - RackType: labware type\n - **Position:** well position in the labware (1-indexed, increases from rear to front and left to right\n - TubeID: tube barcode\n - **Volume:** Pipetting volume in microL\n - **LiquidClass:** optional parameter overwrites the liquid class specified in worklist command\n - TipMask: optional, specifies the tip to use\n - ForcedRack-Type: optional, configuration name of labware\n - **MinDetectedVolume:** liquid volume in microL -- if specified, and if liquid level detection is enabled\n in the selected liquid class, is used to determine the minimum liquid height which must be available in the well\n\n'''\n\ndef add_reagent_to_worklist(source_rack_label,\n source_rack_id,\n source_rack_type,\n source_position,\n target_rack_label,\n target_rack_id,\n target_rack_type,\n positions,\n volumes,\n liquid_class='',\n tip_mask='',\n forced_rack_type='',\n min_detected_volume=''\n ):\n worklist = []\n for position,volume in zip(positions,volumes):\n # aspirate from source\n worklist.append('A;{0};{1};{2};{3};{4};{5};{6};{7};{8};'.format(\\\n source_rack_label,\n source_rack_id,\n source_rack_type,\n source_position,\n volume,\n liquid_class,\n tip_mask,\n forced_rack_type,\n min_detected_volume))\n \n # dispense into target\n worklist.append('D;{0};{1};{2};{3};{4};{5};{6};{7};{8};'.format(\\\n target_rack_label,\n target_rack_id,\n target_rack_type,\n position,\n volume,\n liquid_class,\n tip_mask,\n forced_rack_type,\n min_detected_volume))\n \n # wash\n worklist.append('W;')\n return worklist\n\nif __name__=='__main__':\n reagent_names = ['hepes',\n 'K2HPO4',\n 'MPG',\n 'amm_acetate',\n 'TCEP',\n 'glucose',\n 'amino_acids',\n 'folinic_acid',\n 'amp',\n 'GMP',\n 'UMP',\n 'CMP',\n 'cf_extract',\n 'dna',\n 'water']\n\n target_rack_label='96wellrxnplate'\n\n # define a random 96-well format experiment\n import numpy as np\n experiment = np.random.randint(3,10,size=(len(reagent_names),96))\n \n # construct a list of worklists, one for each reagent\n worklist = []\n for i,reagent in enumerate(reagent_names):\n worklist.append(add_reagent_to_worklist(reagent,\n '',\n '',\n '',\n target_rack_label,\n '',\n '',\n np.arange(96),\n experiment[i]))\n # flatten that list of lists\n worklist = [line for sublist in worklist for line in sublist]\n\n # write the list to CSV for later use\n worklist_name='example_worklist.csv'\n f = open(worklist_name,'w')\n for line in worklist:\n f.write(line+'\\n')\n f.close()\n\n\n","sub_path":"utils/generate_worklists.py","file_name":"generate_worklists.py","file_ext":"py","file_size_in_byte":5840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"550157348","text":"# If we plan to use custom modules for certain layers, those could be defined using the nn package prior to defining the model sequence.\n# This examples shows the same two-layer network as a custom function\n\nimport torch\n\nclass TwoLayerNet(torch.nn.Module):\n\tdef __init__(self, D_in, H, D_out):\n\t\t\"\"\"\n\t\tIn the constructor we instantiate two nn.Linear modules and assign them a member variables.\n\t\t\"\"\"\t\n\t\tsuper(TwoLayerNet, self).__init__()\n\t\tself.linear1 = torch.nn.Linear(D_in, H)\n\t\tself.linear2 = torch.nn.Linear(H, D_out)\n\t\n\tdef forward(self,x):\n\t\t\"\"\"\n\t\tIn the forward function we accept a Tensor of input data and we must return a Tensor of output data. We can use Modules defined in the constructor as well as arbitrary operators on Tensors\n\t\t\"\"\"\n\t\th_relu = self.linear1(x).clamp(min=0)\n\t\ty_pred = self.linear2(h_relu)\n\t\treturn y_pred\n\n\n# N is batch size; D_in is input dimension;\n# H is hidden dimension; D_out is output dimension.\nN, D_in, H, D_out = 64, 1000, 100, 10\n\n# Create random Tensors to hold inputs and outputs\nx = torch.randn(N, D_in)\ny = torch.randn(N, D_out)\n\n\n# Construct our model by instantiating the class defined above\nmodel = TwoLayerNet(D_in, H, D_out)\n\n# Construct our loss function and an Optimizer. The call to model.parameters()\n# in the SGD constructor will contain the learnable parameters of the two\n# nn.Linear modules which are members of the model.\n\nloss_fn = torch.nn.MSELoss(reduction='sum')\noptimizer = torch.optim.SGD(model.parameters(), lr=1e-4) # Note the use of just stochastic gradient descent (SGD) here\nfor t in range(500):\n\t# Forward pass: Compute predicted y by passing x to the model\n\ty_pred = model(x)\n\n\t# Compute and print loss\n\tloss = loss_fn(y_pred, y)\n\tprint(t, loss.item())\n\n\t# Zero gradients, perform a backward pass, and update the weights.\n\toptimizer.zero_grad()\n\tloss.backward()\n\toptimizer.step()\n","sub_path":"example8.py","file_name":"example8.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"6373206","text":"import os\nimport unittest\nimport mock\nimport multiprocessing\nimport ssl\n\nimport suds\n\nfrom requests.exceptions import SSLError\nfrom suds.transport import TransportError\n\nfrom oydiv_rpc.sudsssltransport import (\n _StrictSSLHTTPTransportAuthenticated as HTTPSTransport,\n SudsClientStrictSSL as Client\n)\n\nfrom six.moves import SimpleHTTPServer\nfrom six.moves import socketserver\n\nMOCK_WSDL = b\"\"\"\n\n\n \n \n ... \n ... \n \n \n\n\"\"\"\n\n\ndef make_request(url):\n \"\"\"test helper to convert a URL into a suds Request object\"\"\"\n return suds.transport.Request(url, \"fakedata\")\n\n\nclass HTTPSServerProcess(object):\n \"\"\"\n implements an HTTPS server and spawns a separate process\n to allow making HTTPS requests to a testable, controlled, ephemeral\n server.\n \"\"\"\n def __init__(self, *args, **kwargs):\n self.queue = multiprocessing.Queue()\n kwargs.update({'queue': self.queue})\n self.server_proc = multiprocessing.Process(\n target=HTTPSServerProcess.start_server,\n kwargs=kwargs\n )\n self.server_proc.start()\n self.server_address = self.queue.get()\n\n @classmethod\n def start_server(*args, **kwargs):\n \"\"\"\n entry-point for the new server process.\n starts a new HTTP server wrapped in an ssl socket. This could\n easily be a standalone function, but making it @classmethod\n makes this a bit more self-contained\n \"\"\"\n response = kwargs.pop('response', '')\n\n class HTTP200Server(SimpleHTTPServer.SimpleHTTPRequestHandler):\n \"\"\"\n This HTTP request handler simply\n responds 200 with any POST or GET request\n \"\"\"\n def do_GET(self, *args, **kwargs):\n self.send_response(200)\n self.end_headers()\n self.wfile.write(response)\n\n def do_POST(self, *args, **kwargs):\n return self.do_GET(*args, **kwargs)\n\n class TestingHTTPSSocketServer:\n def __init__(self, *args, **kwargs):\n self.server = socketserver.ThreadingTCPServer(\n ('127.0.0.1', 0), # let the OS choose a free port\n HTTP200Server,\n )\n self.server.socket = ssl.wrap_socket(\n self.server.socket,\n certfile=kwargs['cert'],\n server_side=True\n )\n queue = kwargs['queue']\n server = TestingHTTPSSocketServer(*args, **kwargs)\n queue.put(server.server.server_address)\n\n server.server.serve_forever()\n\n def __enter__(self, *args, **kwargs):\n return self\n\n def __exit__(self, *args, **kwargs):\n self.stop_server()\n\n def stop_server(self):\n self.server_proc.terminate()\n\n\nclass TestSSLCertificateHandling(unittest.TestCase):\n \"\"\"\n urllib<3 is deficient in SSL handling.\n It does not do verification of the server certificate, which amounts to\n *no security at all*. This test is here to make sure that failure does not\n make it into our suds transport that is meant to be checking certificates.\n See https://bitbucket.org/jurko/suds/issue/23/ssl-certificate-verification\n for the discussion.\n \"\"\"\n\n def setUp(self):\n self.transport = HTTPSTransport()\n\n def test_certname_handling(self):\n with HTTPSServerProcess(\n cert=os.path.join(os.path.dirname(__file__), 'certs/selfsigned.pem')\n ) as server:\n url = 'https://localhost:%s/' % (server.server_address[1],)\n data = 'thisdataissecret'\n request = suds.transport.Request(url, data)\n with self.assertRaises((ssl.SSLError, TransportError)):\n self.transport.open(request)\n\n\nclass HTTPSTransportTests(unittest.TestCase):\n def setUp(self):\n session_mock = mock.MagicMock()\n session_mock.get.return_value.text = 'response text'\n self.mocked_session = session_mock\n\n def test_plain_http_no_rewrite_fails(self):\n \"\"\"\n Some buggy SOAP servers reference plain HTTP urls in the WSDL\n even when served over HTTPS.\n The ``SudsClientStrictSSL`` Transport has an option to rewrite urls to HTTPS\n before making the request. If this is `False`, and `verify_ssl == True`\n We expect the request to fail.\n Assert that the default behaviour of the transport is strict.\n Does not allow plain HTTP unless overriden with verify_ssl=False\"\"\"\n transport = HTTPSTransport(rewrite_to_https=False)\n transport.session = self.mocked_session\n\n with self.assertRaises((SSLError, TransportError)):\n transport.open(make_request('http://example.com/'))\n\n def test_plain_http_rewrite_rewritten(self):\n transport = HTTPSTransport(rewrite_to_https=True)\n transport.session = self.mocked_session\n return_value = mock.MagicMock()\n return_value.content = b''\n transport.session.get.return_value = return_value\n\n transport.open(make_request('http://example.com'))\n # mock.MagicMock.assert_called_with does not allow specifying interest in a single argument\n self.assertEqual(\n transport.session.get.call_args[1].get('url'),\n 'https://example.com'\n )\n\n def test_plain_http_no_args_fails(self):\n \"\"\"The default behaviour should be to refuse to send credentials over HTTP\"\"\"\n transport = HTTPSTransport()\n transport.session = self.mocked_session\n\n with self.assertRaises((SSLError, TransportError)):\n transport.open(make_request('http://example.com/'))\n\n def test_https_transport_commonname_with_cacert_bundle(self):\n \"\"\"\n Test the handling of using custom CA-Certificate bundle\n \"\"\"\n with HTTPSServerProcess(\n response=MOCK_WSDL,\n cert=os.path.join(os.path.dirname(__file__), 'certs/localhost.pem')\n ) as server:\n # This should be just fine\n Client(\n 'https://localhost:%s/' % server.server_address[1],\n verify_ssl=os.path.join(os.path.dirname(__file__), 'certs/localhost_cacert.pem')\n )\n with self.assertRaises(TransportError):\n # using 127.0.0.1 should not match subjectAltName or commonName\n # and throw an error\n Client(\n 'https://127.0.0.1:%s/' % server.server_address[1],\n verify_ssl=os.path.join(os.path.dirname(__file__), 'certs/localhost_cacert.pem')\n )\n","sub_path":"tests/test_transport.py","file_name":"test_transport.py","file_ext":"py","file_size_in_byte":7087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"462257850","text":"import sublime\nimport sublime_plugin\nimport re\n\n\nclass SqlUpperCommand(sublime_plugin.TextCommand):\n\n def run(self, edit):\n region = sublime.Region(0, self.view.size())\n raw_text = self.view.substr(region)\n\n for word in RESERVED_WORDS:\n # pattern = r'(?!\\B\"[^\"]*)(?:\\b' + word + r'\\b)(?![^\"]*\"\\B)'\n pattern = r'\\b{}\\b'.format(word)\n pattern = re.compile(pattern, re.IGNORECASE)\n raw_text = pattern.sub(word.upper(), raw_text)\n\n self.view.replace(edit, region, raw_text)\n self.view.window().status_message('Ololo')\n\n\nRESERVED_WORDS = (\n 'add',\n 'aggregate',\n 'all',\n 'alter',\n 'analytic',\n 'and',\n 'anti',\n 'api_version',\n 'as',\n 'asc',\n 'avro',\n 'between',\n 'bigint',\n 'binary',\n 'boolean',\n 'buckets',\n 'by',\n 'cached',\n 'cascade',\n 'case',\n 'cast',\n 'change',\n 'char',\n 'class',\n 'close_fn',\n 'column',\n 'columns',\n 'comment',\n 'compute',\n 'count',\n 'create',\n 'cross',\n 'current',\n 'data',\n 'database',\n 'databases',\n 'date',\n 'datetime',\n 'decimal',\n 'delete',\n 'delimited',\n 'desc',\n 'describe',\n 'distinct',\n 'distribute',\n 'div',\n 'double',\n 'drop',\n 'else',\n 'end',\n 'escaped',\n 'exists',\n 'explain',\n 'extended',\n 'external',\n 'false',\n 'fields',\n 'fileformat',\n 'finalize_fn',\n 'first',\n 'float',\n 'following',\n 'for',\n 'format',\n 'formatted',\n 'from',\n 'full',\n 'function',\n 'functions',\n 'grant',\n 'group',\n 'hash',\n 'having',\n 'if',\n 'ignore',\n 'ilike',\n 'in',\n 'incremental',\n 'init_fn',\n 'inner',\n 'inpath',\n 'insert',\n 'int',\n 'integer',\n 'intermediate',\n 'interval',\n 'into',\n 'invalidate',\n 'iregexp',\n 'is',\n 'join',\n 'last',\n 'left',\n 'like',\n 'limit',\n 'lines',\n 'load',\n 'location',\n 'merge_fn',\n 'metadata',\n 'not',\n 'null',\n 'nulls',\n 'offset',\n 'on',\n 'or',\n 'order',\n 'outer',\n 'over',\n 'overwrite',\n 'parquet',\n 'parquetfile',\n 'partition',\n 'partitioned',\n 'partitions',\n 'preceding',\n 'prepare_fn',\n 'produced',\n 'purge',\n 'range',\n 'rcfile',\n 'real',\n 'refresh',\n 'regexp',\n 'rename',\n 'replace',\n 'restrict',\n 'returns',\n 'revoke',\n 'right',\n 'rlike',\n 'role',\n 'roles',\n 'row',\n 'rows',\n 'schema',\n 'schemas',\n 'select',\n 'semi',\n 'sequencefile',\n 'serdeproperties',\n 'serialize_fn',\n 'set',\n 'show',\n 'smallint',\n 'split',\n 'stats',\n 'stored',\n 'straight_join',\n 'string',\n 'sum',\n 'symbol',\n 'table',\n 'tables',\n 'tblproperties',\n 'terminated',\n 'textfile',\n 'then',\n 'timestamp',\n 'tinyint',\n 'to',\n 'true',\n 'truncate',\n 'unbounded',\n 'uncached',\n 'union',\n 'update',\n 'update_fn',\n 'use',\n 'using',\n 'values',\n 'varchar',\n 'view',\n 'when',\n 'where',\n 'with',\n)\n","sub_path":".config/sublime-tex-3/Packages/User/sql_upper.py","file_name":"sql_upper.py","file_ext":"py","file_size_in_byte":3108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"11854324","text":"#!/usr/bin/python\n#-*- coding:utf-8 -*-\n# vim:fenc=utf-8\n# @Author: wiseacreee\n# @Created Time: 2018-06-15\n\nimport pickle\nfrom app import redis_store, db\nfrom functools import wraps\nfrom flask import request, make_response\nfrom app.common.constant import HALF_HOUR\n\ndef format_record_to_dict(record, dict_keys):\n \"\"\"\n 格式化记录\n @params list|dict record: 数据\n @params str rtype: 返回类型 list表示列表 dict表示字典\n @params list dict_keys: 字典类型key列表\n @return dict\n \"\"\"\n if isinstance(record, list):\n # 生产多重key数据\n final = {}\n\n # keys长度\n dict_keys_len = len(dict_keys)\n\n for row in record:\n # 利用字典可变性质,一层层生产字典\n r = final\n for index in range(0, dict_keys_len):\n key = row[dict_keys[index]]\n\n # 字典不存在则生成一个\n if key not in r.keys():\n r[key] = {}\n\n # 到达最后一个key,直接指向当前行 if index == dict_keys_len - 1:\n r[key] = row\n r = r[key]\n return final\n\n return record\n\ndef single_orm_query(record):\n \"\"\" orm查询单行数据 \"\"\"\n\n # 格式化\n final = record._asdict() if record else {}\n\n return final\n\ndef multi_orm_query(record):\n \"\"\" orm查询多行数据 \"\"\"\n\n # 格式化\n final = [row._asdict() for row in record]\n\n return final\n\ndef single_raw_query(sql):\n \"\"\" 原生sql查询单行数据 \"\"\"\n\n # 查询数据库\n record = db.session.execute(sql)\n\n # 获取第一条记录\n row = record.first() if record.rowcount else {}\n\n final = {key: value for key, value in row.items()}\n\n return final\n\ndef multi_raw_query(sql):\n \"\"\" 原生sql查询多行数据 \"\"\"\n\n # 查询数据库\n record = db.session.execute(sql)\n\n final = [{key: value for key, value in row.items()} for row in record]\n\n return final\n\ndef format_record(record, qtype):\n \"\"\" 格式化查询参数 \"\"\"\n if qtype == 'orm_single':\n # orm查询单行数据\n record = single_orm_query(record)\n elif qtype == 'orm_multi':\n # orm查询多行数据\n record = multi_orm_query(record)\n elif qtype == 'raw_single':\n # 原生sql查询单行数据\n record = single_raw_query(record)\n elif qtype == 'raw_multi':\n # 原生sql查询多行数据\n record = multi_raw_query(record)\n return record\n\ndef get_cache_key(func, args, kwargs, args_name):\n \"\"\" 生产缓存key\n 根据原函数的参数生成缓存key\n key命名: func_name:arg1:arg2...\n \"\"\"\n cache_key = '{0}.{1}'.format(func.__module__, func.__name__)\n for arg_name in args_name:\n k = args.pop(0) if arg_name not in kwargs.keys() else kwargs[arg_name]\n cache_key = '{0}:{1}'.format(cache_key, k)\n return cache_key\n\ndef format_query_record(qtype='orm_single', rtype='list', dict_keys=[],\n cache=False, expire_time=HALF_HOUR, func_type='class'):\n \"\"\" 格式化查询数据\n params: qtype[str] 查找数据的类型\n params: rtyep[str] 返回数据的类型\n params: dict_keys[str] 字典类型的key\n params: cache[B] True设置缓存 False不需要 默认False\n params: expire_time[int] 缓存过期时间(秒)\n params: func_type[str] 查找方法的类型\n \"\"\"\n def wrapper_fun(func):\n @wraps(func)\n def _wrapper_fun(*args, **kwargs):\n\n # 是否设置缓存\n if cache == True:\n # 处理class中的self\n start_index = 1 if func_type == 'class' else 0\n\n # 获取方法参数的值\n func_args = list(args[start_index:])\n\n # 获取方法参数的名称\n varnames = func.__code__.co_varnames\n args_name = varnames[start_index:func.__code__.co_argcount]\n\n # 生产缓存key\n cache_key = get_cache_key(func, func_args, kwargs, args_name)\n\n # 查询redis缓存数据\n val = redis_store.get(cache_key) if expire_time else None\n if val is not None:\n record = pickle.loads(val)\n return record\n\n # 查询记录\n record = func(*args, **kwargs)\n\n # 格式化记录\n record = format_record(record, qtype)\n if rtype == 'dict':\n record = format_record_to_dict(record, dict_keys)\n\n if cache == True:\n # 序列化参数,写缓存,设置缓存有效时间\n val = pickle.dumps(record)\n redis_store.set(cache_key, val, expire_time)\n\n return record\n return _wrapper_fun\n return wrapper_fun\n\ndef view_cached(expire_time=HALF_HOUR):\n \"\"\" 视图缓存 \"\"\"\n def wrapper_fun(func):\n @wraps(func)\n def _wrapper_fun(*args, **kwargs):\n \"\"\" _wrapper_fun\"\"\"\n # 获取方法参数的字典\n input_kwargs = kwargs['params']['input']\n if 'access_token' in input_kwargs:\n del input_kwargs['access_token']\n\n # 获取方法参数的名称\n args_name = sorted(input_kwargs.keys())\n\n # 生产缓存key\n cache_key = get_cache_key(func, args, input_kwargs, args_name)\n\n # 查询redis缓存数据\n val = redis_store.get(cache_key) if expire_time else None\n if val is not None:\n result = pickle.loads(val)\n return result\n\n result = func(*args, **kwargs)\n val = pickle.dumps(result)\n redis_store.set(cache_key, val, expire_time)\n\n return result\n return _wrapper_fun\n return wrapper_fun\n\ndef format_query_data(func):\n \"\"\" 格式化数据库查询 \"\"\"\n @wraps(func)\n def wrapper(*args, **kwargs):\n record = func(*args, **kwargs)\n if isinstance(record, list):\n if not record:\n return []\n new_record = [item._asdict() for item in record]\n return new_record\n if not record:\n return {}\n return record._asdict()\n return wrapper\n\n","sub_path":"app/common/decorator.py","file_name":"decorator.py","file_ext":"py","file_size_in_byte":6274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"642418251","text":"from telethon import events\nfrom telethon.events import NewMessage\nfrom telethon.tl.custom import Dialog\nfrom telethon.tl.types import Channel, Chat, User\nfrom telethon.errors import ChatSendInlineForbiddenError as noin\nfrom telethon.errors.rpcerrorlist import BotMethodInvalidError as dedbot\n\nfrom . import *\n\n#-------------------------------------------------------------------------------\n\nspeedo_pic = Config.ALIVE_PIC or \"https://telegra.ph/file/f46b11140c307df13750d.jpg\"\nalive_c = f\"__**🔥🔥Speedo ɨs օռʟɨռɛ🔥🔥**__\\n\\n\"\nalive_c += f\"__↼ Øwñêr ⇀__ : 『 {speedo_mention} 』\\n\\n\"\nalive_c += f\"•♦• Telethon : `{tel_ver}` \\n\"\nalive_c += f\"•♦• SPEEDOBOT : __**{speedo_ver}**__\\n\"\nalive_c += f\"•♦• Sudo : `{is_sudo}`\\n\"\nalive_c += f\"•♦• Channel : {speedo_channel}\\n\"\n\n#-------------------------------------------------------------------------------\n\n@speedo.on(Speedo_cmd(outgoing=True, pattern=\"speedo$\"))\n@speedo.on(sudo_cmd(pattern=\"speedo$\", allow_sudo=True))\nasync def up(speedo):\n if speedo.fwd_from:\n return\n await speedo.get_chat()\n await speedo.delete()\n await bot.send_file(speedo.chat_id, speedo_pic, caption=alive_c)\n await speedo.delete()\n\nmsg = f\"\"\"\n**⚡ 𝒮𝒫𝐸𝐸𝒟𝒪 ιѕ σиℓιиє ⚡**\n{Config.ALIVE_MSG}\n**🏅 𝙱𝚘𝚝 𝚂𝚝𝚊𝚝𝚞𝚜 🏅**\n**Telethon :** `{tel_ver}`\n**SPEEDOBOT :** **{speedo_ver}**\n**Abuse :** **{abuse_m}**\n**Sudo :** **{is_sudo}**\n\"\"\"\nbotname = Config.BOT_USERNAME\n\n@speedo.on(Speedo_cmd(pattern=\"alive$\"))\n@speedo.on(sudo_cmd(pattern=\"alive$\", allow_sudo=True))\nasync def speedo_a(event):\n try:\n speedo = await bot.inline_query(botname, \"alive\")\n await speedo[0].click(event.chat_id)\n if event.sender_id == ForGo10God:\n await event.delete()\n except (noin, dedbot):\n await eor(event, msg)\n\n\nCmdHelp(\"alive\").add_command(\n \"speedo\", None, \"Shows the Default Alive Message\"\n).add_command(\n \"alive\", None, \"Shows Inline Alive Menu with more details.\"\n).add_warning(\n \"✅ Harmless Module\"\n).add()\n","sub_path":"Speedo/plugins/alive.py","file_name":"alive.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"230029717","text":"# Copyright (c) 2020 PaddlePaddle 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\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport time\nimport multiprocessing\nimport numpy as np\n\n# from paddle.fluid.contrib.model_stat import summary\n\n\ndef set_paddle_flags(**kwargs):\n for key, value in kwargs.items():\n if os.environ.get(key, None) is None:\n os.environ[key] = str(value)\n\n\n# NOTE(paddle-dev): All of these flags should be\n# set before `import paddle`. Otherwise, it would\n# not take any effect. \nset_paddle_flags(\n FLAGS_eager_delete_tensor_gb=0, # enable GC to save memory\n)\n\nfrom paddle import fluid\nfrom ppocr.utils.utility import create_module\nfrom ppocr.utils.utility import load_config, merge_config\nimport ppocr.data.rec.reader_main as reader\nfrom ppocr.utils.utility import ArgsParser\nfrom ppocr.utils.character import CharacterOps, cal_predicts_accuracy\nfrom ppocr.utils.check import check_gpu\nfrom ppocr.utils.stats import TrainingStats\nfrom ppocr.utils.checkpoint import load_pretrain, load_checkpoint, save, save_model\nfrom ppocr.utils.eval_utils import eval_run\n\nfrom ppocr.utils.utility import initial_logger\nlogger = initial_logger()\nfrom ppocr.utils.utility import create_multi_devices_program\n\n\ndef main():\n config = load_config(FLAGS.config)\n merge_config(FLAGS.opt)\n char_ops = CharacterOps(config['Global'])\n config['Global']['char_num'] = char_ops.get_char_num()\n print(config)\n\n # check if set use_gpu=True in paddlepaddle cpu version\n use_gpu = config['Global']['use_gpu']\n check_gpu(use_gpu)\n\n place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace()\n exe = fluid.Executor(place)\n\n rec_model = create_module(config['Architecture']['function'])(params=config)\n\n startup_prog = fluid.Program()\n train_prog = fluid.Program()\n with fluid.program_guard(train_prog, startup_prog):\n with fluid.unique_name.guard():\n train_loader, train_outputs = rec_model(mode=\"train\")\n save_var = train_outputs[1]\n\n if \"gradient_clip\" in config['Global']:\n gradient_clip = config['Global']['gradient_clip']\n clip = fluid.clip.GradientClipByGlobalNorm(gradient_clip)\n fluid.clip.set_gradient_clip(clip, program=train_prog)\n\n train_fetch_list = [v.name for v in train_outputs]\n train_loss = train_outputs[0]\n opt_params = config['Optimizer']\n optimizer = create_module(opt_params['function'])(opt_params)\n optimizer.minimize(train_loss)\n global_lr = optimizer._global_learning_rate()\n global_lr.persistable = True\n train_fetch_list.append(global_lr.name)\n\n train_reader = reader.train_eval_reader(\n config=config, char_ops=char_ops, mode=\"train\")\n train_loader.set_sample_list_generator(train_reader, places=place)\n\n eval_prog = fluid.Program()\n with fluid.program_guard(eval_prog, startup_prog):\n with fluid.unique_name.guard():\n eval_loader, eval_outputs = rec_model(mode=\"eval\")\n eval_fetch_list = [v.name for v in eval_outputs]\n\n eval_prog = eval_prog.clone(for_test=True)\n exe.run(startup_prog)\n\n eval_reader = reader.train_eval_reader(\n config=config, char_ops=char_ops, mode=\"eval\")\n eval_loader.set_sample_list_generator(eval_reader, places=place)\n\n # compile program for multi-devices\n train_compile_program = create_multi_devices_program(train_prog,\n train_loss.name)\n\n pretrain_weights = config['Global']['pretrain_weights']\n if pretrain_weights is not None:\n load_pretrain(exe, train_prog, pretrain_weights)\n\n train_batch_id = 0\n train_log_keys = ['loss', 'acc']\n log_smooth_window = config['Global']['log_smooth_window']\n epoch_num = config['Global']['epoch_num']\n loss_type = config['Global']['loss_type']\n print_step = config['Global']['print_step']\n eval_step = config['Global']['eval_step']\n save_epoch_step = config['Global']['save_epoch_step']\n save_dir = config['Global']['save_dir']\n train_stats = TrainingStats(log_smooth_window, train_log_keys)\n best_eval_acc = -1\n best_batch_id = 0\n best_epoch = 0\n for epoch in range(epoch_num):\n train_loader.start()\n try:\n while True:\n t1 = time.time()\n train_outs = exe.run(program=train_compile_program,\n fetch_list=train_fetch_list,\n return_numpy=False)\n loss = np.mean(np.array(train_outs[0]))\n lr = np.mean(np.array(train_outs[-1]))\n\n preds = np.array(train_outs[1])\n preds_lod = train_outs[1].lod()[0]\n labels = np.array(train_outs[2])\n labels_lod = train_outs[2].lod()[0]\n\n acc, acc_num, img_num = cal_predicts_accuracy(\n char_ops, preds, preds_lod, labels, labels_lod)\n\n t2 = time.time()\n train_batch_elapse = t2 - t1\n\n stats = {'loss': loss, 'acc': acc}\n train_stats.update(stats)\n if train_batch_id > 0 and train_batch_id % print_step == 0:\n logs = train_stats.log()\n strs = 'epoch: {}, iter: {}, lr: {:.6f}, {}, time: {:.3f}'.format(\n epoch, train_batch_id, lr, logs, train_batch_elapse)\n logger.info(strs)\n\n if train_batch_id > 0 and train_batch_id % eval_step == 0:\n outs = eval_run(exe, eval_prog, eval_loader,\n eval_fetch_list, char_ops, train_batch_id,\n \"eval\")\n eval_acc, acc_num, sample_num = outs\n if eval_acc > best_eval_acc:\n best_eval_acc = eval_acc\n best_batch_id = train_batch_id\n best_epoch = epoch\n save_path = save_dir + \"/best_accuracy\"\n save_model(train_prog, save_path)\n\n strs = 'Test iter: {}, acc:{:.6f}, best_acc:{:.6f}, best_epoch:{}, best_batch_id:{}, sample_num:{}'.format(\n train_batch_id, eval_acc, best_eval_acc, best_epoch,\n best_batch_id, sample_num)\n logger.info(strs)\n train_batch_id += 1\n\n except fluid.core.EOFException:\n train_loader.reset()\n\n if epoch > 0 and epoch % save_epoch_step == 0:\n save_path = save_dir + \"/iter_epoch_%d\" % (epoch)\n save_model(train_prog, save_path)\n\n\ndef test_reader():\n config = load_config(FLAGS.config)\n merge_config(FLAGS.opt)\n char_ops = CharacterOps(config['Global'])\n config['Global']['char_num'] = char_ops.get_char_num()\n print(config)\n # tmp_reader = reader.train_eval_reader(\n # config=cfg, char_ops=char_ops, mode=\"train\")\n tmp_reader = reader.train_eval_reader(\n config=config, char_ops=char_ops, mode=\"eval\")\n count = 0\n print_count = 0\n import time\n starttime = time.time()\n for data in tmp_reader():\n count += len(data)\n print_count += 1\n if print_count % 10 == 0:\n batch_time = (time.time() - starttime) / print_count\n print(\"reader:\", count, len(data), batch_time)\n print(\"finish reader:\", count)\n print(\"success\")\n\n\nif __name__ == '__main__':\n parser = ArgsParser()\n parser.add_argument(\n \"-r\",\n \"--resume_checkpoint\",\n default=None,\n type=str,\n help=\"Checkpoint path for resuming training.\")\n FLAGS = parser.parse_args()\n main()\n# test_reader()\n","sub_path":"tools/tmp/train_rec.py","file_name":"train_rec.py","file_ext":"py","file_size_in_byte":8412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"274282215","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\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\n# published by the Free Software Foundation, either version 3 of the\n# License, or (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 Affero 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 osv import fields, osv\nfrom tools.translate import _\n\nclass account_fiscalyear_close(osv.osv_memory):\n \"\"\"\n Closes Account Fiscalyear and Generate Opening entries for New Fiscalyear\n \"\"\"\n _name = \"account.fiscalyear.close\"\n _description = \"Fiscalyear Close\"\n _columns = {\n 'fy_id': fields.many2one('account.fiscalyear', \\\n 'Fiscal Year to close', required=True, help=\"Select a Fiscal year to close\"),\n 'fy2_id': fields.many2one('account.fiscalyear', \\\n 'New Fiscal Year', required=True),\n 'journal_id': fields.many2one('account.journal', 'Opening Entries Journal', domain=\"[('type','=','situation')]\", required=True, help='The best practice here is to use a journal dedicated to contain the opening entries of all fiscal years. Note that you should define it with default debit/credit accounts, of type \\'situation\\' and with a centralized counterpart.'),\n 'period_id': fields.many2one('account.period', 'Opening Entries Period', required=True),\n 'report_name': fields.char('Name of new entries',size=64, required=True, help=\"Give name of the new entries\"),\n }\n _defaults = {\n 'report_name': _('End of Fiscal Year Entry'),\n }\n\n def data_save(self, cr, uid, ids, context=None):\n \"\"\"\n This function close account fiscalyear and create entries in new fiscalyear\n @param cr: the current row, from the database cursor,\n @param uid: the current user’s ID for security checks,\n @param ids: List of Account fiscalyear close state’s IDs\n\n \"\"\"\n obj_acc_period = self.pool.get('account.period')\n obj_acc_fiscalyear = self.pool.get('account.fiscalyear')\n obj_acc_journal = self.pool.get('account.journal')\n obj_acc_move_line = self.pool.get('account.move.line')\n obj_acc_account = self.pool.get('account.account')\n obj_acc_journal_period = self.pool.get('account.journal.period')\n\n data = self.browse(cr, uid, ids, context=context)\n\n if context is None:\n context = {}\n fy_id = data[0].fy_id.id\n\n cr.execute(\"SELECT id FROM account_period WHERE date_stop < (SELECT date_start FROM account_fiscalyear WHERE id = %s)\", (str(data[0].fy2_id.id),))\n fy_period_set = ','.join(map(lambda id: str(id[0]), cr.fetchall()))\n cr.execute(\"SELECT id FROM account_period WHERE date_start > (SELECT date_stop FROM account_fiscalyear WHERE id = %s)\", (str(fy_id),))\n fy2_period_set = ','.join(map(lambda id: str(id[0]), cr.fetchall()))\n\n period = obj_acc_period.browse(cr, uid, data[0].period_id.id, context=context)\n new_fyear = obj_acc_fiscalyear.browse(cr, uid, data[0].fy2_id.id, context=context)\n old_fyear = obj_acc_fiscalyear.browse(cr, uid, fy_id, context=context)\n\n new_journal = data[0].journal_id.id\n new_journal = obj_acc_journal.browse(cr, uid, new_journal, context=context)\n\n if not new_journal.default_credit_account_id or not new_journal.default_debit_account_id:\n raise osv.except_osv(_('UserError'),\n _('The journal must have default credit and debit account'))\n if (not new_journal.centralisation) or new_journal.entry_posted:\n raise osv.except_osv(_('UserError'),\n _('The journal must have centralised counterpart without the Skipping draft state option checked!'))\n\n move_ids = obj_acc_move_line.search(cr, uid, [\n ('journal_id', '=', new_journal.id), ('period_id.fiscalyear_id', '=', new_fyear.id)])\n\n if move_ids:\n obj_acc_move_line._remove_move_reconcile(cr, uid, move_ids, context=context)\n obj_acc_move_line.unlink(cr, uid, move_ids, context=context)\n\n cr.execute(\"SELECT id FROM account_fiscalyear WHERE date_stop < %s\", (str(new_fyear.date_start),))\n result = cr.dictfetchall()\n fy_ids = ','.join([str(x['id']) for x in result])\n query_line = obj_acc_move_line._query_get(cr, uid,\n obj='account_move_line', context={'fiscalyear': fy_ids})\n cr.execute('select id from account_account WHERE active AND company_id = %s', (old_fyear.company_id.id,))\n ids = map(lambda x: x[0], cr.fetchall())\n for account in obj_acc_account.browse(cr, uid, ids,\n context={'fiscalyear': fy_id}):\n accnt_type_data = account.user_type\n if not accnt_type_data:\n continue\n if accnt_type_data.close_method=='none' or account.type == 'view':\n continue\n if accnt_type_data.close_method=='balance':\n if abs(account.balance)>0.0001:\n obj_acc_move_line.create(cr, uid, {\n 'debit': account.balance>0 and account.balance,\n 'credit': account.balance<0 and -account.balance,\n 'name': data[0].report_name,\n 'date': period.date_start,\n 'journal_id': new_journal.id,\n 'period_id': period.id,\n 'account_id': account.id\n }, {'journal_id': new_journal.id, 'period_id':period.id})\n if accnt_type_data.close_method == 'unreconciled':\n offset = 0\n limit = 100\n while True:\n cr.execute('SELECT id, name, quantity, debit, credit, account_id, ref, ' \\\n 'amount_currency, currency_id, blocked, partner_id, ' \\\n 'date_maturity, date_created ' \\\n 'FROM account_move_line ' \\\n 'WHERE account_id = %s ' \\\n 'AND ' + query_line + ' ' \\\n 'AND reconcile_id is NULL ' \\\n 'ORDER BY id ' \\\n 'LIMIT %s OFFSET %s', (account.id, limit, offset))\n result = cr.dictfetchall()\n if not result:\n break\n for move in result:\n move.pop('id')\n move.update({\n 'date': period.date_start,\n 'journal_id': new_journal.id,\n 'period_id': period.id,\n })\n obj_acc_move_line.create(cr, uid, move, {\n 'journal_id': new_journal.id,\n 'period_id': period.id,\n })\n offset += limit\n\n #We have also to consider all move_lines that were reconciled\n #on another fiscal year, and report them too\n offset = 0\n limit = 100\n while True:\n cr.execute('SELECT DISTINCT b.id, b.name, b.quantity, b.debit, b.credit, b.account_id, b.ref, ' \\\n 'b.amount_currency, b.currency_id, b.blocked, b.partner_id, ' \\\n 'b.date_maturity, b.date_created ' \\\n 'FROM account_move_line a, account_move_line b ' \\\n 'WHERE b.account_id = %s ' \\\n 'AND b.reconcile_id is NOT NULL ' \\\n 'AND a.reconcile_id = b.reconcile_id ' \\\n 'AND b.period_id IN ('+fy_period_set+') ' \\\n 'AND a.period_id IN ('+fy2_period_set+') ' \\\n 'ORDER BY id ' \\\n 'LIMIT %s OFFSET %s', (account.id, limit, offset))\n result = cr.dictfetchall()\n if not result:\n break\n for move in result:\n move.pop('id')\n move.update({\n 'date': period.date_start,\n 'journal_id': new_journal.id,\n 'period_id': period.id,\n })\n obj_acc_move_line.create(cr, uid, move, {\n 'journal_id': new_journal.id,\n 'period_id': period.id,\n })\n offset += limit\n if accnt_type_data.close_method=='detail':\n offset = 0\n limit = 100\n while True:\n cr.execute('SELECT id, name, quantity, debit, credit, account_id, ref, ' \\\n 'amount_currency, currency_id, blocked, partner_id, ' \\\n 'date_maturity, date_created ' \\\n 'FROM account_move_line ' \\\n 'WHERE account_id = %s ' \\\n 'AND ' + query_line + ' ' \\\n 'ORDER BY id ' \\\n 'LIMIT %s OFFSET %s', (account.id, limit, offset))\n\n result = cr.dictfetchall()\n if not result:\n break\n for move in result:\n move.pop('id')\n move.update({\n 'date': period.date_start,\n 'journal_id': new_journal.id,\n 'period_id': period.id,\n })\n obj_acc_move_line.create(cr, uid, move)\n offset += limit\n ids = obj_acc_move_line.search(cr, uid, [('journal_id','=',new_journal.id),\n ('period_id.fiscalyear_id','=',new_fyear.id)])\n context['fy_closing'] = True\n\n if ids:\n obj_acc_move_line.reconcile(cr, uid, ids, context=context)\n new_period = data[0].period_id.id\n ids = obj_acc_journal_period.search(cr, uid, [('journal_id','=',new_journal.id),('period_id','=',new_period)])\n if not ids:\n ids = [obj_acc_journal_period.create(cr, uid, {\n 'name': (new_journal.name or '')+':'+(period.code or ''),\n 'journal_id': new_journal.id,\n 'period_id': period.id\n })]\n cr.execute('UPDATE account_fiscalyear ' \\\n 'SET end_journal_period_id = %s ' \\\n 'WHERE id = %s', (ids[0], old_fyear.id))\n return {'type': 'ir.actions.act_window_close'}\n\naccount_fiscalyear_close()\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"account/wizard/account_fiscalyear_close.py","file_name":"account_fiscalyear_close.py","file_ext":"py","file_size_in_byte":11574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"24549049","text":"#!/usr/bin/env python\n#coding=utf-8\n\"\"\"\nfake robot total program\n\nCopyright (c) 2015 Xu Zhihao (Howe). All rights reserved.\nThis program is free software; you can redistribute it and/or modify\nThis programm is tested on kuboki base turtlebot. \n\"\"\"\nimport rospy\nfrom sensor_msgs.msg import LaserScan\n\nclass LaserTransfer():\n def __init__(self):\n rospy.init_node('scan_remapper')\n rospy.Subscriber('scan', LaserScan, self.scan_callback)\n rospy.spin()\n \n def scan_callback(self,data):\n scan_data=data\n if rospy.has_param('~scan_frame_id'):\n frame_id=rospy.get_param('~scan_frame_id')\n else:\n rospy.set_param('~scan_frame_id')\n frame_id=rospy.get_param('~scan_frame_id')\n scan_data.header.frame_id=frame_id\n \n if rospy.has_param('~scan_topic'):\n scan_topic=rospy.get_param('~scan_topic')\n else:\n rospy.set_param('~scan_topic')\n scan_topic=rospy.get_param('~scan_topic')\n \n pub = rospy.Publisher(scan_topic, LaserScan, queue_size=10)\n pub.publish(scan_data)\nif __name__=='__main__':\n try:\n rospy.loginfo (\"initialization system\")\n LaserTransfer()\n rospy.loginfo (\"process done and quit\")\n except rospy.ROSInterruptException:\n rospy.loginfo(\"robot twist node terminated.\")\n","sub_path":"src/machine/src/scan_remaper.py","file_name":"scan_remaper.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"543249772","text":"# Copyright 2016 The Johns Hopkins University Applied Physics Laboratory\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\"\"\"\nCreate the cloudwatch alarms for the load balancer on top of a loadbalancer stack.The cloudwatch stack consists of\n * alarms monitor traffic in and out of the load balancer\n\n\"\"\"\n\nfrom lib.cloudformation import CloudFormationConfiguration, Arg, Ref, Arn\nfrom lib.userdata import UserData\nfrom lib.names import AWSNames\nfrom lib.keycloak import KeyCloakClient\nfrom lib.external import ExternalCalls\nfrom lib import aws\nfrom lib import utils\nfrom lib import scalyr\nfrom lib import constants as const\n\nimport json\n\ndef create_config(session, domain):\n \"\"\"Create the CloudFormationConfiguration object.\n :arg session used to perform lookups\n :arg domain DNS name of vpc\n \"\"\"\n config = CloudFormationConfiguration('cloudwatch', domain)\n names = AWSNames(domain)\n\n vpc_id = config.find_vpc(session)\n lambda_subnets, _ = config.find_all_availability_zones(session, lambda_compatible_only=True)\n\n internal_sg = aws.sg_lookup(session, vpc_id, names.internal)\n\n loadbalancer_name = names.endpoint_elb\n if not aws.lb_lookup(session, loadbalancer_name):\n raise Exception(\"Invalid load balancer name: \" + loadbalancer_name)\n\n # TODO Test that MailingListTopic is working.\n production_mailing_list = const.PRODUCTION_MAILING_LIST\n mailing_list_arn = aws.sns_topic_lookup(session, production_mailing_list)\n if mailing_list_arn is None:\n #config.add_sns_topic(\"topicList\", production_mailing_list)\n msg = \"MailingList {} needs to be created before running config\"\n raise Exception(msg.format(const.PRODUCTION_MAILING_LIST))\n\n config.add_cloudwatch(loadbalancer_name, [mailing_list_arn])\n\n lambda_role = aws.role_arn_lookup(session, 'VaultConsulHealthChecker')\n config.add_arg(Arg.String(\n 'VaultConsulHealthChecker', lambda_role,\n 'IAM role for vault/consul health check.' + domain))\n\n config.add_lambda('VaultLambda',\n names.vault_monitor,\n description='Check health of vault instances.',\n timeout=30,\n role=Ref('VaultConsulHealthChecker'),\n security_groups=[internal_sg],\n subnets=lambda_subnets,\n handler='index.lambda_handler',\n file=const.VAULT_LAMBDA)\n\n config.add_lambda('ConsulLambda',\n names.consul_monitor,\n description='Check health of vault instances.',\n timeout=30,\n role=Ref('VaultConsulHealthChecker'),\n security_groups=[internal_sg],\n subnets=lambda_subnets,\n handler='index.lambda_handler',\n file=const.CONSUL_LAMBDA)\n\n # Lambda input data\n json_str = json.dumps({\n 'vpc_id': vpc_id,\n 'vpc_name': domain,\n 'topic_arn': mailing_list_arn,\n })\n\n config.add_cloudwatch_rule('VaultConsulCheck',\n name=names.vault_consul_check,\n description='Check health of vault and consul instances.',\n targets=[\n {\n 'Arn': Arn('VaultLambda'),\n 'Id': names.vault_monitor,\n 'Input': json_str\n },\n {\n 'Arn': Arn('ConsulLambda'),\n 'Id': names.consul_monitor,\n 'Input': json_str\n },\n ],\n schedule='rate(1 minute)',\n depends_on=['VaultLambda', 'ConsulLambda'])\n\n config.add_lambda_permission('VaultPerms',\n names.vault_monitor,\n principal='events.amazonaws.com',\n source=Arn('VaultConsulCheck'))\n\n config.add_lambda_permission('ConsulPerms',\n names.consul_monitor,\n principal='events.amazonaws.com',\n source=Arn('VaultConsulCheck'))\n\n return config\n\n\ndef generate(session, domain):\n \"\"\"Create the configuration and save it to disk\n :arg folder location to generate the cloudformation template stack\n :arg domain internal DNS name\"\"\"\n config = create_config(session, domain)\n config.generate()\n\ndef create(session, domain):\n \"\"\"Create the configuration, launch it, and initialize Vault\n :arg session information for performing lookups\n :arg domain internal DNS name \"\"\"\n config = create_config(session, domain)\n\n success = config.create(session)\n\n if success:\n print('success')\n else:\n print('failed')\n","sub_path":"cloud_formation/configs/cloudwatch.py","file_name":"cloudwatch.py","file_ext":"py","file_size_in_byte":5566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"384745314","text":"from django.contrib import auth\nfrom django.shortcuts import render, redirect\nfrom django.shortcuts import get_object_or_404\nfrom django.urls import reverse\n\nfrom .models import Post, Category, Comment, StaticPages\nfrom django.core.paginator import Paginator\nfrom .forms import CommentForm, PostForm\nfrom django.contrib.auth.models import User\nfrom django.http import HttpResponseNotFound\n\n# Create your views here.\ndef home(request):\n post_list = Post.objects.filter(is_active=True)\n paginator = Paginator(post_list, 4)\n page = request.GET.get('page')\n posts = paginator.get_page(page)\n return render(request, 'blog/home.html ', context={'posts': posts})\n\ndef post_detail(request, post_slug):\n #post = Post.objects.get(post_slug__iexact=post_slug)\n active_posts = Post.objects.filter(is_active=True)\n post = get_object_or_404(active_posts, post_slug=post_slug)\n #post = get_object_or_404(Post, post_slug__iexact=post_slug) - можно использовать модель, но и так же можно использовать Queryset. В случае выше, мы проверяем не черновик ли. То есть активная ли статья.\n form = CommentForm()\n return render(request, 'blog/post_detail.html', context={'post': post, 'form': form})\n\ndef category_detail(request, category_slug):\n category = get_object_or_404(Category, category_slug__iexact=category_slug)\n return render(request, 'blog/category_detail.html', context={'category': category})\n\ndef search_form(request):\n search_query = request.GET.get('searchkey', '')\n\n if search_query:\n posts = Post.objects.filter(post_title__icontains=search_query, is_active=True) # Указываем поле по которому фильтровать, по которому происходить будет поиск.\n return render(request, 'blog/search_detail.html', context={'posts': posts, 'search_query': search_query})\n else:\n return render(request, 'blog/search_detail.html', context={'search_query': '- Вы ничего не указали!'})\n\n\ndef add_comment(request, post_slug):\n post = get_object_or_404(Post, post_slug=post_slug)\n full_form = CommentForm(request.POST)\n if full_form.is_valid():\n new_comment = Comment()\n new_comment.author_id = auth.get_user(request)\n new_comment.post_id = post\n new_comment.comment_body = full_form.cleaned_data['comment_body'] #cleaned дата позволяет взять данные с конкретного поля, которое мы указали в forms. Без тегов и прочей ереси. Чистый текст.\n new_comment.save()\n else:\n form = CommentForm()\n return redirect('post_detail_url', post_slug=post.post_slug)\n\ndef edit_post(request, post_slug):\n if request.user.is_authenticated:\n post = Post.objects.get(post_slug__iexact=post_slug)\n if request.user.id == post.author_id_id: #проверить почему id_id\n if request.method == 'GET':\n form = PostForm(instance=post)\n\n if request.method == 'POST':\n form = PostForm(request.POST, instance=post)\n if form.is_valid():\n updated_post = form.save()\n return redirect(updated_post)\n return render(request, 'blog/post_edit.html', context={'form': form, 'post': post})\n else:\n return HttpResponseNotFound('

Извините, но вы не являетесь автором этой статьи!

')\n else:\n return HttpResponseNotFound('

Извините, но вы не авторизованы!

')\n\ndef post_create(request):\n if request.user.is_authenticated:\n if request.method == 'GET':\n my_form = PostForm()\n return render(request, 'blog/post_create.html', context={'form': my_form})\n\n if request.method == 'POST':\n full_form = PostForm(request.POST)\n if full_form.is_valid():\n new_post = full_form.save()\n return redirect(new_post)\n else:\n return HttpResponseNotFound('

Извините, но вы не авторизованы!

')\n\n\ndef get_panel(request):\n if request.user.is_authenticated:\n user = request.user\n user_comments = user.comments\n user_posts = user.posts\n return render(request, 'blog/admin_panel.html', context={'user_comments': user_comments, 'user_posts': user_posts, 'user': user})\n else:\n return HttpResponseNotFound('

Извините, но вы не авторизованы!

')\n\ndef post_delete(request, post_slug):\n if request.user.is_authenticated:\n post = Post.objects.get(post_slug__iexact=post_slug)\n if request.user.id == post.author_id_id:\n if request.method == 'GET':\n return render(request, 'blog/post_delete.html', context={'post': post})\n\n if request.method == 'POST':\n post.delete()\n return redirect('user_admin_panel_url')\n else:\n return HttpResponseNotFound('

Извините, но вы не являетесь автором данной статьи!

')\n else:\n return HttpResponseNotFound('

Извините, но вы не авторизованы!

')\n\ndef static_page(request, page_slug):\n pages = StaticPages.objects.filter(is_active=True)\n page = get_object_or_404(pages, page_slug=page_slug)\n\n return render(request, 'blog/page_detail.html', context={'page': page})\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"650363880","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pylab as plb\nimport cmath\nimport os\n\nPath = '/Users/cgoldsmith/repos/delayFitting/Data/pertOutput/'\nos.chdir(Path)\n\nPath2 = '/Users/cgoldsmith/Desktop/text_files_data'\nos.chdir(Path2)\ndata = np.loadtxt('TDSE_3fs.txt')\nx = data[:, 0]\ny = data[:, 4]\n\nsizeO = 0\nwith open(Path + 'omega.txt') as infile:\n for line in infile:\n sizeO = sizeO + 1\n\nomega = np.zeros(sizeO)\nalphaOne = np.zeros(sizeO)\nreAlphaTwo = np.zeros(sizeO)\nimAlphaTwo = np.zeros(sizeO)\nalphaThree = np.zeros(sizeO)\nrecf = np.zeros(sizeO)\nimcf = np.zeros(sizeO)\nrecfOne = np.zeros(sizeO)\nimcfOne = np.zeros(sizeO)\nrecfTwo = np.zeros(sizeO)\nimcfTwo = np.zeros(sizeO)\nrecfThree = np.zeros(sizeO)\nimcfThree = np.zeros(sizeO)\n\ni = 0\nwith open(Path + 'omega.txt') as infile:\n for line in infile:\n omega[i] = (line.split()[0])\n i = i + 1\n \ni = 0\nwith open(Path + 'alphaOne.txt') as infile:\n for line in infile:\n alphaOne[i] = (line.split()[0])\n i = i + 1\n \ni = 0\nwith open(Path + 'alphaThree.txt') as infile:\n for line in infile:\n alphaThree[i] = (line.split()[0])\n i = i + 1\n\ni = 0\nwith open(Path + 'alphaTwo.txt') as infile:\n for line in infile:\n reAlphaTwo[i] = (line.split()[0])\n imAlphaTwo[i] = (line.split()[0])\n i = i + 1\n\ni = 0\nwith open(Path + 'recf.txt') as infile:\n for line in infile:\n recf[i] = (line.split()[0])\n i = i + 1\n \ni = 0\nwith open(Path + 'imcf.txt') as infile:\n for line in infile:\n imcf[i] = (line.split()[0])\n i = i + 1 \ni = 0\nwith open(Path + 'recfOne.txt') as infile:\n for line in infile:\n recfOne[i] = (line.split()[0])\n i = i + 1\n \ni = 0\nwith open(Path + 'imcfOne.txt') as infile:\n for line in infile:\n imcfOne[i] = (line.split()[0])\n i = i + 1\n\ni = 0\nwith open(Path + 'recfTwo.txt') as infile:\n for line in infile:\n recfTwo[i] = (line.split()[0])\n i = i + 1\n \ni = 0\nwith open(Path + 'imcfTwo.txt') as infile:\n for line in infile:\n imcfTwo[i] = (line.split()[0])\n i = i + 1\n\ni = 0\nwith open(Path + 'recfThree.txt') as infile:\n for line in infile:\n recfThree[i] = (line.split()[0])\n i = i + 1\n \ni = 0\nwith open(Path + 'imcfThree.txt') as infile:\n for line in infile:\n imcfThree[i] = (line.split()[0])\n i = i + 1\n\ndomega = np.gradient(omega)\n\ndrecfOne = np.gradient(recfOne, domega)\ndimcfOne = np.gradient(imcfOne, domega)\ncfSquareOne = recfOne**2 + imcfOne**2\ndelayOne = (recfOne*dimcfOne - imcfOne*drecfOne)/cfSquareOne\n\ndrecfTwo = np.gradient(recfTwo, domega)\ndimcfTwo = np.gradient(imcfTwo, domega)\ncfSquareTwo = recfTwo**2 + imcfTwo**2\ndelayTwo = (recfTwo*dimcfTwo - imcfThree*drecfTwo)/cfSquareTwo\n\ndrecfThree = np.gradient(recfThree, domega)\ndimcfThree = np.gradient(imcfThree, domega)\ncfSquareThree = recfThree**2 + imcfThree**2\ndelayThree = (recfThree*dimcfThree - imcfThree*drecfThree)/cfSquareThree\n\n# plt.plot(omega, cfSquareThree)\n# plt.plot(omega, reAlphaTwo, omega, imAlphaTwo)\n# plt.plot(omega, recfTwo, omega, imcfTwo)\n# plt.plot(omega, alphaOne, 'r-', omega, alphaThree, 'b-')\n# plb.ylim([-10, 10])\n# plb.ylabel('alphas')\nplt.plot(omega, np.gradient(np.arctan((imcfThree + imcfTwo)/(recfTwo + recfThree)), domega))\n# plt.plot(omega, recf, omega, imcf )\n# plb.ylim([-10, 10])\nplb.ylabel('real and imag cf, just two')\nplb.xlabel('central frequency (a.u.)')\nplb.legend(['real', 'imag'])\nplt.show()\n","sub_path":"Source/pertSource/PerturbationTheory/PerturbationTheory/plotIndividual.py","file_name":"plotIndividual.py","file_ext":"py","file_size_in_byte":3523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"486547305","text":"import sys\nfrom PyQt5.QtWidgets import QApplication, QWidget\nfrom PyQt5.QtGui import QIcon\n\nclass Example(QWidget):\n\n\n\tdef __init__(self):\n\t\tsuper().__init__()\n\t\tself.initUI()\n\n\n\tdef initUI(self):\n\t\tself.setGeometry(300, 300, 300, 220)\n\t\tself.setWindowTitle(\"icone\")\n\t\tself.setWindowIcon(QIcon(\"icon1.jpg\"))\n\t\tself.show()\n\n\napp = QApplication(sys.argv)\nex = Example()\nsys.exit(app.exec_())","sub_path":"PyQt5/curso/simple.py","file_name":"simple.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"76635410","text":"# G(N) = sum of gcd(i,j), for 1 <= i <= j <= N.\n# You are given: G(10)=122.\n# \n# Find G(10^11). Give your answer modulo 998244353\n\n# THEORY:\n# \n# G(N) = sum of (k * number of 1 <= i <= j <= N with gcd(i,j)=k) over k\n# = sum of (k * number of 1 <= i <= j <= N/k with gcd(i,j)=1) over k\n# = sum of (k * P(N/k)) over k\n# where P is the totient summatory function.\n\nfrom time import time\nimport sys\nsys.path.append(\"../Library\")\nfrom peresult import peresult\nfrom math import log\n\ndef get_p(n, memos, mod):\n if n in memos:\n return memos[n]\n result = (n * (n + 1) // 2) % mod\n denom = 2\n while denom <= n:\n arg = n // denom\n new_denom = n // arg + 1\n result -= get_p(arg, memos, mod) * (new_denom - denom)\n result %= mod\n denom = new_denom\n memos[n] = result\n return result \n\ndef solve(cap = 10 ** 11, mod = 998244353):\n memos = {1: 1}\n result = 0\n k = 1\n while k <= cap:\n p = get_p(cap // k, memos, mod)\n new_k = (cap // (cap // k)) + 1\n result += (new_k * (new_k - 1) - k * (k - 1)) // 2 * p\n result %= mod\n k = new_k\n return result\n\nif __name__ == \"__main__\":\n start = time()\n peresult(625, solve(), time() - start)\n","sub_path":"Problems 601-700/p625_GcdSum.py","file_name":"p625_GcdSum.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"28019754","text":"import pandas as pd\nimport numpy as np\n\nframe = pd.DataFrame(np.arange(16).reshape((4,4)),\n index=['red','blue','yellow','white'],\n columns=['ball','pen','pencil','paper'])\n\nprint(frame)\nframe.loc['yellow', 'pen'] = 30\nprint(frame)\nprint(frame.sort_values(by='pen'))","sub_path":"Aula 03/Slide_36.py","file_name":"Slide_36.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"35387409","text":"import cPickle as pickle\nimport pprint, os\nimport numpy as np\nimport plots\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport sys\nfrom matplotlib import rcParams\n\nsys.path.append(r'D:\\measuring')\nmatplotlib.use('PDF')\n\nfrom analysis.lib.fitting import fit\nfrom analysis.lib.lde import tail_cts_per_shot_v4\n\n\n\nLT1_clr = plots.colors['LT1']\nLT2_clr = plots.colors['LT2']\n\n\nrcParams['figure.subplot.hspace'] = 0.1\nrcParams['figure.subplot.right'] = 0.95\nrcParams['figure.subplot.top'] = 0.95\nrcParams['figure.subplot.left'] = 0.1\n\n\ndef find_nearest(array,value):\n idx=(abs(array-value)).argmin()\n return idx\n\n\ndata_path = r'D:\\measuring\\data\\LDE\\analysis_output\\20121104-opt-rabi-vs-CR'\ndata_lines = r'D:\\measuring\\data\\LDE\\analysis_output\\20121113-linewidths'\n\n\nf = open(os.path.join(data_path, r'LT1_sample_curve.pkl'),\"rb\")\nLT1_data=pickle.load(f)\nf.close()\n\nf = np.load(os.path.join(data_path,r'LT1_fit_with_slope_range_32_76.npz'))\ndamping_LT1 = f['damping'][1]\ndamping_err_LT1 = f['damping_err'][1]\nCR_LT1 = f['CR']\nf.close()\n\nf = open(os.path.join(data_lines, r'LT1_linewidths.pkl'),\"rb\")\nLT1_lines=pickle.load(f)\nf.close()\n\n\nf = open(os.path.join(data_path,r'LT2_sample_curve.pkl'),\"rb\")\nLT2_data=pickle.load(f)\nf.close()\n\nf = np.load(os.path.join(data_path,r'LT2_fit_with_slope_range_6_49_lp_5_33_hp.npz'))\ndamping_LT2 = f['damping'][0]\ndamping_err_LT2 = f['damping_err'][0]\nCR_LT2 = f['CR'][0]\nf.close()\n\nf = open(os.path.join(data_lines, r'LT2_linewidths.pkl'),\"rb\")\nLT2_lines=pickle.load(f)\nf.close()\n\nrebins = 4\n\noffset_LT1 = 26\nx_range=(0,88)\n\n\n####Normalization:\n# we assume that at the pulse begin the population should be 1 \n# i think this means assuming infinetely sharp pulses\n\nLT1_pulse_start = 30.6\nLT2_pulse_start = 4.8\n\nLT1_params = LT1_data[0]['fit_result'][0]['params_dict']\nLT2_params = LT2_data[0]['fit_result'][0]['params_dict']\n\nnorm_amp_LT1 = LT1_params['a'] + LT1_params['b']*(LT1_pulse_start-LT1_params['x0'])+\\\n np.abs(LT1_params['A']) * np.exp(-(LT1_pulse_start-LT1_params['x0'])/LT1_params['tau'])\n\nnorm_amp_LT2 = LT2_params['a'] + LT2_params['b']*(LT2_pulse_start-LT2_params['x0'])+\\\n np.abs(LT2_params['A']) * np.exp(-(LT2_pulse_start-LT2_params['x0'])/LT2_params['tau'])\n\nLT1_counts = tail_cts_per_shot_v4.rebin(LT1_data[0]['counts'],rebins)/(norm_amp_LT1*rebins)\nLT1_time = np.arange(len(LT1_counts))*0.128*rebins-26\nLT1_fit = tail_cts_per_shot_v4.rebin(LT1_data[0]['fit_result'][0]['fitdata'],rebins)/(norm_amp_LT1*rebins)\nLT1_fit_time = np.arange(len(LT1_fit))*0.128*rebins+LT1_data[0]['time_fit'][0]-26\n\n\nidx_LT1_min = find_nearest(LT1_time,x_range[0])\nidx_LT1_max = find_nearest(LT1_time,x_range[1])\n\n\nLT2_counts = tail_cts_per_shot_v4.rebin(LT2_data[0]['counts'],rebins)/(norm_amp_LT2*rebins)\nLT2_time = np.arange(len(LT2_counts))*0.128*rebins\nLT2_fit = tail_cts_per_shot_v4.rebin(LT2_data[0]['fit_result'][0]['fitdata'],rebins)/(norm_amp_LT2*rebins)\nLT2_fit_time = np.arange(len(LT2_fit))*0.128*rebins+LT2_data[0]['time_fit'][0]\n\n\nidx_LT2_min = find_nearest(LT2_time,x_range[0])\nidx_LT2_max = find_nearest(LT2_time,x_range[1])\n\n\n\n\n\n\n#################### damping\n\nfig1 = plt.figure(figsize=(3,1.5))\na3x = plt.subplot(111)\n#a3x.errorbar(CR_LT1,damping_LT1,yerr = damping_err_LT1,fmt = 'ro')\na3x.plot(CR_LT1,damping_LT1, 'o', markersize = 4,\n mec = LT1_clr['bright'], mfc = LT1_clr['bright'])\na3x.set_ylim(14.4,16.8)\na3x.set_xlim(-5,65)\na3x.locator_params(nbins=5)\na3x.set_ylabel('damping $\\\\tau$')#, position = (-1.6,-.08))\na3x.yaxis.labelpad = 2\na3x.set_xlabel('preparation threshold')\na3x.xaxis.labelpad = 2\n\n#a3x.set_xticklabels([])\na3x.text(0, 16.6, 'NV A', color = LT1_clr['bright'], \n horizontalalignment = 'left', verticalalignment = 'top')\n\n\n\na1x = fig1.add_axes([0.5,0.36,0.3,0.35])\na1x.plot(LT1_time[idx_LT1_min:idx_LT1_max],LT1_counts[idx_LT1_min:idx_LT1_max],\n '-', color = LT1_clr['bright'], linewidth = 2, label = 'NV A')\n#mec=colors.LT1_1, mfc=colors.LT1_1)\na1x.plot(LT1_fit_time, LT1_fit, '-', color = LT1_clr['dark'], linewidth = 1, label = 'fit')\na1x.set_xlim(x_range)\na1x.set_ylim(0,1.0)\na1x.set_yticks([0.0,0.5,1.0])\na1x.set_yticklabels(['0','','1'])\nfor tick in a1x.yaxis.get_major_ticks():\n tick.label.set_fontsize(7)\na1x.set_xticks([0,40,80])\nfor tick in a1x.xaxis.get_major_ticks():\n tick.label.set_fontsize(7)\n#a1x.text(85, 0.9, 'NV A', horizontalalignment = 'right',\n# verticalalignment = 'top', color = LT1_clr['bright'])\n#a1x.legend()\na1x.set_xlabel('t (ns)', fontsize = 7)\na1x.xaxis.labelpad = 1\na1x.set_ylabel('$P(E_y)$', fontsize = 7)\na1x.yaxis.labelpad = -4\n\nfig1.savefig(r'D:\\experiments\\LDE\\ldeplots\\damping_LT1.pdf')\n\n\n\nfig2 = plt.figure(figsize=(3,1.5))\n\n\na4x = plt.subplot(111)\n#a4x.errorbar(CR_LT2,damping_LT2,yerr = damping_err_LT2,fmt = 'ro')\na4x.plot(CR_LT2,damping_LT2, 'o', mec = LT2_clr['bright'], mfc = LT2_clr['bright'])\n#a4x.set_yticklabels([])\na4x.set_ylim(10.5,17.8)\na4x.set_xlim(-3 ,35)\na4x.locator_params(nbins=5)\na4x.set_xlabel('preparation threshold')\na4x.xaxis.labelpad = 2\n#a4x.set_xscale('log')\n#a4x.set_xticklabels([0.1,1,10])\na4x.set_yticks([12,14,16])\na4x.text(12, 17.5, 'NV B', color = LT2_clr['bright'],\n horizontalalignment = 'left', verticalalignment = 'top')\n\n\n\na2x = fig2.add_axes([0.68,0.34,0.25,0.3])\na2x.plot(LT2_time[idx_LT2_min:idx_LT2_max],LT2_counts[idx_LT2_min:idx_LT2_max],\n '-', color = LT2_clr['bright'], linewidth = 2, label = 'NV B')\na2x.plot(LT2_fit_time, LT2_fit, '-', color = LT2_clr['dark'], linewidth = 1, label = 'fit' )\na2x.set_xlim(x_range)\na2x.set_ylim(0,1.0)\na2x.set_yticks([0,0.5,1.0])\na2x.set_yticklabels(['0','','1'])\nfor tick in a2x.yaxis.get_major_ticks():\n tick.label.set_fontsize(7)\na2x.set_xticks([0,40,80])\nfor tick in a2x.xaxis.get_major_ticks():\n tick.label.set_fontsize(7)\n#a2x.text(85, 0.9, 'NV B', horizontalalignment = 'right',\n# verticalalignment = 'top', color = LT2_clr['bright'])\n#a2x.legend()\n#a2x.set_yticklabels([])\n#a2x.locator_params(nbins=4)\na2x.set_ylabel('$P(E_y)$', fontsize = 7)\na2x.yaxis.labelpad = -4\na2x.set_xlabel('t (ns)', fontsize = 7)\na2x.xaxis.labelpad = 1\n\n\nfig2.savefig(r'D:\\experiments\\LDE\\ldeplots\\damping_LT2.pdf')\n\n\n############## line scans\nfig3 = plt.figure(figsize=(3,1))\na5x = fig3.add_axes([0.57,0.05,0.38,0.7])\na5x.plot(LT1_lines[0]['homo_axis']-\\\n LT1_lines[0]['fit_result_inhomo']['params_dict']['x01'],\n LT1_lines[0]['counts_homo']/LT1_lines[0]['norm_homo'],\n 'o', mec = LT1_clr['medium'], mfc = LT1_clr['medium'], label = 'single')\na5x.plot(LT1_lines[0]['inhomo_axis']-\\\n LT1_lines[0]['fit_result_inhomo']['params_dict']['x01'],\n LT1_lines[0]['counts_inhomo']/LT1_lines[0]['norm_inhomo'],\n 'o', mec = LT1_clr['bright'], mfc = LT1_clr['bright'], label = 'sum')\na5x.plot(LT1_lines[0]['fit_result_homo']['fitx']+\\\n LT1_lines[0]['homo_offset']-\\\n LT1_lines[0]['fit_result_inhomo']['params_dict']['x01'],\n LT1_lines[0]['fit_result_homo']['fity']/LT1_lines[0]['norm_homo'],\n '-',color = LT1_clr['dark'])\na5x.plot(LT1_lines[0]['fit_result_inhomo']['fitx']-\\\n LT1_lines[0]['fit_result_inhomo']['params_dict']['x01'],\n LT1_lines[0]['fit_result_inhomo']['fity']/LT1_lines[0]['norm_inhomo'],\n '-',color = LT1_clr['dark'], label = 'fit')\na5x.set_xlim(-0.15,0.15)\na5x.set_ylim(0.01,1.2)\n#a5x.set_xticklabels([])\na5x.set_xticks([-0.1,0.0,0.1])\na5x.set_yticks([0.0,0.5,1.0])\na5x.set_yticklabels([])\n#a5x.set_ylabel('intensity')#, position = (-1.6,-.08))\na5x.set_xlabel('detuning (MHz)')\na5x.xaxis.labelpad = 2\na5x.xaxis.set_label_position('top')\na5x.xaxis.tick_top()\na5x.text(0.13,1.05,'single', color = LT1_clr['medium'], \n horizontalalignment = 'right', verticalalignment = 'center')\na5x.text(-0.13,1.05,'sum', color = LT1_clr['bright'], \n horizontalalignment = 'left', verticalalignment = 'center')\n#a5x.legend()\n#a5x.locator_params(nbins=5)\n\na6x = fig3.add_axes([0.15,0.05,0.38,0.7])\na6x.plot(LT2_lines[0]['homo_axis']-\\\n LT2_lines[0]['fit_result_inhomo']['params_dict']['x0'],\n LT2_lines[0]['counts_homo']/LT2_lines[0]['norm_homo'],\n 'o', mec = LT2_clr['medium'], mfc = LT2_clr['medium'], label = 'single')\na6x.plot(LT2_lines[0]['inhomo_axis']-\\\n LT2_lines[0]['fit_result_inhomo']['params_dict']['x0'],\n LT2_lines[0]['counts_inhomo']/LT2_lines[0]['norm_inhomo'],\n 'o', mec = LT2_clr['bright'], mfc = LT2_clr['bright'], label = 'sum')\na6x.plot(LT2_lines[0]['fit_result_homo']['fitx']+\\\n LT2_lines[0]['homo_offset']-\\\n LT2_lines[0]['fit_result_inhomo']['params_dict']['x0'],\n LT2_lines[0]['fit_result_homo']['fity']/LT2_lines[0]['norm_homo'],\n '-',color = LT2_clr['dark'])\na6x.plot(LT2_lines[0]['fit_result_inhomo']['fitx']-\\\n LT2_lines[0]['fit_result_inhomo']['params_dict']['x0'],\n LT2_lines[0]['fit_result_inhomo']['fity']/LT2_lines[0]['norm_inhomo'],\n '-',color = LT2_clr['dark'], label = 'fit')\na6x.set_xlim(-0.15,0.15)\na6x.set_ylim(0.01,1.2)\na6x.set_yticks([0.0,0.5,1.0])\na6x.set_xticks([-0.1,0.0,0.1])\na6x.text(0.13,1.05,'single', color = LT2_clr['medium'], \n horizontalalignment = 'right', verticalalignment = 'center')\na6x.text(-0.13,1.05,'sum', color = LT2_clr['bright'], \n horizontalalignment = 'left', verticalalignment = 'center')\n#a6x.legend()\na6x.set_xlabel('detuning (MHz)')\na6x.set_ylabel('intensity')\na6x.yaxis.labelpad = 2\na6x.xaxis.labelpad = 2\na6x.xaxis.set_label_position('top')\na6x.xaxis.tick_top()\n#plt.tight_layout()\n\nfig3.savefig(r'D:\\experiments\\LDE\\ldeplots\\line_widths.pdf')\n","sub_path":"plot_opt_rabi_v4.py","file_name":"plot_opt_rabi_v4.py","file_ext":"py","file_size_in_byte":9584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"266106428","text":"\n# -*- coding: utf-8 -*-\n#author: kai.zhang\nimport pandas as pd\nimport numpy as np\nimport arrow\nimport time\nimport datetime\nfrom conf.setting import *\nfrom core.common.string_tools import *\nimport logging\n\nlogging.basicConfig(filename='../logs/FlatLineCal.log',level=logging.DEBUG)\n\n'''\n计算每个币种以2018-05-01往前每天的平仓线\n\n'''\nclass DayFlatLineCal(object):\n\n def __init__(self, coin = 'xrpbtc'):\n self.data_path = '../data/'\n self.data_name = coin + '-m1-huobi.csv'\n self.head = ':00'\n self.tail = ' 23:59:59'\n\n def get_timestamp(self, date):\n return (int)(time.mktime(time.strptime(date, \"%Y-%m-%d %H:%M:%S\")))\n\n def get_date_range(self, start):\n start += self.head\n end = start + self.tail # 截止基准的00:00\n return self.get_timestamp(start), self.get_timestamp(end)\n\n def init(self):\n df = pd.read_csv(self.data_path + self.data_name).reset_index(drop=False)\n self.df = pd.DataFrame(df, columns=['timestamp', 'high', 'low'])\n return self\n\n\n def conver_rate(self, start ,end):\n '''\n 计算窗口内的折价率\n :param start: 窗口开始\n :param end: 结束\n :return: 窗口指标\n '''\n start = self.get_timestamp(start)\n end = self.get_timestamp(end)\n datas = self.df[(self.df['timestamp'] / 1000 >= start) & (self.df['timestamp'] / 1000 <= end)]\n high, low = datas.loc[datas.high == datas.high.max()], datas.loc[datas.low == datas.low.min()]\n if high.empty:\n return 0.0\n high = high.loc[high.index[0]]\n low = low.loc[low.index[0]]\n rate = 0.0\n if high.timestamp > low.timestamp: # 涨幅\n rate = (high.high - low.low) / low.low\n elif high.timestamp < low.timestamp: # 跌幅\n rate = (low.low - high.high) / high.high\n return round(rate, 4)\n\n\nif __name__ == '__main__':\n ## test\n benchmark = '2018-03-01'\n end_date = '2018-04-30'\n all = {}\n t0 = time.time()\n print('币种\\t类型\\t最大涨幅\\t最大跌幅')\n for coin in coins_pair: # 币\n res = {}\n start = datetime.datetime.strptime((datetime.datetime.strptime(benchmark, '%Y-%m-%d') + datetime.timedelta(days=-1)).strftime('%Y-%m-%d'),\n '%Y-%m-%d')\n for minute in conve_rate_minutes: # 窗口\n crc = DayFlatLineCal(coin).init()\n coin_min_rates = []\n i = 0\n while start < datetime.datetime.strptime(end_date, '%Y-%m-%d'):# %H:%M:%S'):\n i = i + 1\n td = (start + datetime.timedelta(days=1)).strftime('%Y-%m-%d')\n start = datetime.datetime.strptime(td, '%Y-%m-%d')\n rate = crc.conver_rate(start.strftime(\"%Y-%m-%d %H:%M:%S\"), td + crc.tail)\n coin_min_rates.append({\n 'start': start.strftime(\"%Y-%m-%d %H:%M:%S\"),\n 'end': td + crc.tail,\n 'rate': rate\n })\n logging.info({'i': i, 's': start, 'r': rate})\n cs = sorted(coin_min_rates, key=lambda e: e['rate'], reverse=True)\n big = 0\n\n small = 0\n try:\n big = cs[0]\n small = cs[-1]\n except:\n pass\n\n print(coin, '天级别平仓线', big['rate'], small['rate'])\n logging.debug({'c': coin, 'm': minute, 'b': big, 's': small})\n logging.info({'coin': coin, 'minute': minute, 'status': 'End....'})\n print('all times taken:', time.time() - t0)\n\n","sub_path":"huobi/analysis/DayFlatLineCal.py","file_name":"DayFlatLineCal.py","file_ext":"py","file_size_in_byte":3638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"158422137","text":"#!/usr/bin/python \n\nimport glob \nimport re\n\nm = open('makefile', 'w')\n\nm.write(\n\"\"\"CC=clang++\t\nCFLAGS=-std=c++11 -stdlib=libc++ -Wall -Werror -O2 -c\n\nifeq ($(shell uname -s), Linux) \n\tCFLAGS := -std=c++11 -Wall -Werror -O2 -c\n\tCC := g++\nendif\n\"\"\")\n\ntests = glob.glob('test*cpp')\n\nnames = map(lambda x: re.sub(r'\\.cpp', '', x), tests)\n\nm.write('all: ')\nm.write(' '.join(names))\nm.write('\\n\\n')\n\nfor i in names:\n m.write(i + ': ' + i + '.cpp\\n')\n m.write('\\t' + '$(CC) $(CFLAGS) ' + i + '.cpp -o ' + i + '\\n\\n')\n\nm.close()\n","sub_path":"gentests.py","file_name":"gentests.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"554922656","text":"# Anthony Krivonos\n# Nov 9th, 2018\n# src/models/quote.py\n\n# Imports\nimport sys\n\n# Abstract: Simple model that maps symbols to quantities.\n\nclass Quote:\n\n def __init__(self, symbol, count = 0, weight = 0.0, average_buy_price = 0, equity = 0, percent_change = 0, equity_change = 0, type = '', name = '', id = '', pe_ratio = 0):\n\n # Set properties\n self.symbol = symbol\n self.count = count\n self.weight = weight\n self.average_buy_price = average_buy_price\n self.equity = equity\n self.percent_change = percent_change\n self.equity_change = equity_change\n self.type = type\n self.name = name\n self.id = id\n self.pe_ratio = pe_ratio","sub_path":"src/models/quote.py","file_name":"quote.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"36621860","text":"import sys\nimport pickle\nimport csv\nimport numpy as np\nimport Algorithmia\n\nfrom sklearn.datasets import load_boston\nfrom sklearn.ensemble import RandomForestRegressor\n\nclient = Algorithmia.client()\n\ndef load_model():\n # Get file by name\n # Open file and load model\n file_path = 'data://YOUR_USERNAME/scikit_learn_demo/scikit-demo-boston-regression.pkl'\n model_path = client.file(file_path).getFile().name\n # Open file and load model\n with open(model_path, 'rb') as f:\n model = pickle.load(f)\n return model\n\n# Load model outside of the apply function so it only gets loaded once\nmodel = load_model()\n\n\ndef process_input(input):\n # Create numpy array from csv file passed as input in apply()\n if input.startswith('data:'):\n file_url = client.file(input).getFile().name\n try:\n np_array = np.genfromtxt(file_url, delimiter=',')\n print(np_array)\n return np_array\n except Exception as e:\n print(\"Could not create numpy array from data\", e)\n sys.exit(0)\n\n\ndef apply(input):\n # Input should be a csv file - model is trained on Sklearn \n # Boston housing dataset using RandomForestRegressor\n np_data = process_input(input)\n prediction = model.predict(np_data)\n return list(prediction)\n","sub_path":"algo-dev-demo/scikit-learn-demo/demo/boston-housing-prices.py","file_name":"boston-housing-prices.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"373793541","text":"import numpy as np\narray1 = np.ones(64)\narray2 = array1.reshape(8,8)\n\nfor i in range(0, 8):\n for j in range(0,8):\n if (i+j) % 2 == 0:\n array2[i][j] = 0\n\nprint(array2)\nprint(\"Where you want to place the queen?\")\n\nrow = int(input(\"Enter row\"))\ncolumn = int(input('Enter column'))\n\nif row<8 and column < 8:\n array2[row][column] = 9\n print(array2)\nelse:\n print(\"Invalid input\")\n","sub_path":"chess.py","file_name":"chess.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"104726737","text":"import cv2\nimport matplotlib\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\n\nfrom ..modeling.utils import build_targets, bbox_iou\n\nmatplotlib.rc('font', **{'size': 11})\n\n# Set printoptions\ntorch.set_printoptions(linewidth=320, precision=5, profile='long')\nnp.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5\n\n# Prevent OpenCV from multithreading (to use PyTorch DataLoader)\ncv2.setNumThreads(0)\n\n\ndef compute_loss(preds, targets, model): # predictions, targets, model\n ft = torch.cuda.FloatTensor if preds[0].is_cuda else torch.Tensor\n lcls, lbox, lobj = ft([0]), ft([0]), ft([0])\n tcls, tbox, indices, anchor_vec = build_targets(model, targets)\n param = model.param # hyperparameters\n arch = model.arch # # (default, uCE, uBCE) detection architectures\n\n # Define criteria\n BCEcls = nn.BCEWithLogitsLoss(pos_weight=ft([param['cls_pw']]))\n BCEobj = nn.BCEWithLogitsLoss(pos_weight=ft([param['obj_pw']]))\n BCE = nn.BCEWithLogitsLoss()\n CE = nn.CrossEntropyLoss() # weight=model.class_weights\n\n if 'F' in arch: # add focal loss\n g = param['fl_gamma']\n BCEcls, BCEobj, BCE, CE = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g), FocalLoss(BCE, g), FocalLoss(CE, g)\n\n # Compute losses\n for i, pred_layer in enumerate(preds): # layer index, layer predictions\n b, a, gj, gi = indices[i] # image, anchor, gridy, gridx\n tobj = torch.zeros_like(pred_layer[..., 0]) # target obj\n\n # Compute losses\n nb = len(b) # number of targets in this layer\n if nb > 0:\n pred_subset = pred_layer[b, a, gj, gi] # prediction subset corresponding to targets\n tobj[b, a, gj, gi] = 1.0 # obj\n # pred_subset[:, 2:4] = torch.sigmoid(pred_subset[:, 2:4]) # wh power loss (uncomment)\n\n # GIoU\n pxy = torch.sigmoid(pred_subset[:, 0:2]) # pxy = pxy * s - (s - 1) / 2, s = 1.5 (scale_xy)\n pbox = torch.cat((pxy, torch.exp(pred_subset[:, 2:4]) * anchor_vec[i]), 1) # predicted box\n giou = bbox_iou(pbox.t(), tbox[i], x1y1x2y2=False, GIoU=True) # giou computation\n lbox += (1.0 - giou).mean() # giou loss\n\n if 'default' in arch and model.nc > 1: # cls loss (only if multiple classes)\n t = torch.zeros_like(pred_subset[:, 5:]) # targets\n t[range(nb), tcls[i]] = 1.0\n lcls += BCEcls(pred_subset[:, 5:], t) # BCE\n # lcls += CE(pred_subset[:, 5:], tcls[i]) # CE\n\n # Instance-class weighting (use with reduction='none')\n # nt = t.sum(0) + 1 # number of targets per class\n # lcls += (BCEcls(pred_subset[:, 5:], t) / nt).mean() * nt.mean() # v1\n # lcls += (BCEcls(pred_subset[:, 5:], t) / nt[tcls[i]].view(-1,1)).mean() * nt.mean() # v2\n\n # Append targets to text file\n # with open('targets.txt', 'a') as file:\n # [file.write('%11.5g ' * 4 % tuple(x) + '\\n') for x in torch.cat((txy[i], twh[i]), 1)]\n\n if 'default' in arch: # separate obj and cls\n lobj += BCEobj(pred_layer[..., 4], tobj) # obj loss\n\n elif 'BCE' in arch: # unified BCE (80 classes)\n t = torch.zeros_like(pred_layer[..., 5:]) # targets\n if nb:\n t[b, a, gj, gi, tcls[i]] = 1.0\n lobj += BCE(pred_layer[..., 5:], t)\n\n elif 'CE' in arch: # unified CE (1 background + 80 classes)\n t = torch.zeros_like(pred_layer[..., 0], dtype=torch.long) # targets\n if nb:\n t[b, a, gj, gi] = tcls[i] + 1\n lcls += CE(pred_layer[..., 4:].view(-1, model.nc + 1), t.view(-1))\n\n lbox *= param['giou']\n lobj *= param['obj']\n lcls *= param['cls']\n loss = lbox + lobj + lcls\n return loss, torch.cat((lbox, lobj, lcls, loss)).detach()\n\n\nclass FocalLoss(nn.Module):\n # Wraps focal loss around existing loss_fcn() https://arxiv.org/pdf/1708.02002.pdf\n # i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=2.5)\n def __init__(self, loss_fcn, gamma=0.5, alpha=1, reduction='mean'):\n super(FocalLoss, self).__init__()\n loss_fcn.reduction = 'none' # required to apply FL to each element\n self.loss_fcn = loss_fcn\n self.gamma = gamma\n self.alpha = alpha\n self.reduction = reduction\n\n def forward(self, input, target):\n loss = self.loss_fcn(input, target)\n loss *= self.alpha * (1.000001 - torch.exp(-loss)) ** self.gamma # non-zero power for gradient stability\n\n if self.reduction == 'mean':\n return loss.mean()\n elif self.reduction == 'sum':\n return loss.sum()\n else: # 'none'\n return loss\n","sub_path":"demonet/modeling/box_heads/yolov3_heads.py","file_name":"yolov3_heads.py","file_ext":"py","file_size_in_byte":4785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"181539387","text":"from collections import OrderedDict\n\nfrom misoclib.com.liteeth.common import *\nfrom misoclib.com.liteeth.generic import *\nfrom misoclib.com.liteeth.generic.arbiter import Arbiter\nfrom misoclib.com.liteeth.generic.dispatcher import Dispatcher\n\nclass LiteEthCrossbar(Module):\n\tdef __init__(self, master_port, dispatch_param):\n\t\tself.users = OrderedDict()\n\t\tself.master = master_port(8)\n\t\tself.dispatch_param = dispatch_param\n\n\t# overload this in derived classes\n\tdef get_port(self, *args, **kwargs):\n\t\tpass\n\n\tdef do_finalize(self):\n\t\t# TX arbitrate\n\t\tsinks = [port.sink for port in self.users.values()]\n\t\tself.submodules.arbiter = Arbiter(sinks, self.master.source)\n\n\t\t# RX dispatch\n\t\tsources = [port.source for port in self.users.values()]\n\t\tself.submodules.dispatcher = Dispatcher(self.master.sink, sources, one_hot=True)\n\t\tcases = {}\n\t\tcases[\"default\"] = self.dispatcher.sel.eq(0)\n\t\tfor i, (k, v) in enumerate(self.users.items()):\n\t\t\tcases[k] = self.dispatcher.sel.eq(2**i)\n\t\tself.comb += \\\n\t\t\tCase(getattr(self.master.sink, self.dispatch_param), cases)\n","sub_path":"misoclib/com/liteeth/generic/crossbar.py","file_name":"crossbar.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"80481836","text":"# %%\nimport plotly.graph_objs as go\nimport pandas as pd\nimport sys\nimport datetime\n\ndata = pd.read_csv(\"../data/covid_countries.csv\")\ndata.sort_values(by='date', inplace=True)\n# data = data[data.Entity.isin([\"Germany\", \"Poland\", \"United States\", \"Italy\", \"Russia\", \"Sweden\", \"Switzerland\"])]\ndates = pd.DataFrame({'date': data.date.unique()})\n\ndata = pd.merge(dates, data, how=\"left\", on=[\"date\"]).fillna(0)\n\nfig = go.Figure()\n\nfor country, data_for_country in data.groupby(\"location\"):\n\n fig.add_scatter(x=data_for_country.date, y=data_for_country.new_deaths_per_million, name=country, mode='lines+markers',\n hovertemplate=\"Date: %{x}
\" +\n \"Daily deaths per million: %{y}
\" +\n \"\",\n line=dict(width=2))\n \n\nfig.update_layout(legend_title_text='Country')\n\n\nfig.update_layout(\n title={\n 'text': \"Daily deaths per million\",\n 'x': 0.5,\n 'y': 0.92,\n 'xanchor': 'center',\n 'yanchor': 'top',\n \"font\": {\"size\": 20}})\n\nargs = sys.argv\nif len(args) > 1:\n if args[1] == \"1\":\n name = args[0].split(\".\")[0]\n path = \"../plots/\"\n fig.write_html(\"{}{}.html\".format(path, name))\n print(\"The plot was saved to {}{}.html\".format(path, name))\n else:\n fig.show()\nelse:\n fig.show()\n","sub_path":"scripts/daily_deaths_per_million.py","file_name":"daily_deaths_per_million.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"441676264","text":"import os\n\nfrom _pdf_to_sentences import _pdf_to_sentences\n\nfrom _pdf_info import _pdf_info\n\n\n#looks through directories for pdf files\n#add topdown=False as a variable to traverse bottom up\n# \"/\" is the root directiory You can replcae it with another starting directory\n#/Users/username might be a good place to clean\nfor root, dirs, files in os.walk(\"/Users/alierengokcelioglu\"):\n\n for name in files:\n location = root + name\n\n if name.endswith(\".pdf\"):\n location = os.path.join(root, name)\n #some pdf documents can not be opened, and give different exceptions\n #You can't know what kind of erros they might throw.\n print(location)\n try:\n #prints psdf info of doc\n print(_pdf_info(location))\n\n except:\n print(\"couldn't get pdf info\")\n\n try:\n #prints first 4 sentences of pdf\n _pdf_to_sentences(location)\n except:\n print(\"couldn't pare pdf into sentences\")\n #asks if doc should be removed, user presses y or n\n ans=input(\"Do you wish to remove this document? y/n. \\n\") #\n #removes doc if answer is y\n if ans=='y':\n os.remove(location)\n","sub_path":"remove.py","file_name":"remove.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"355705425","text":"import pandas as pd\nimport re\nfrom snownlp import SnowNLP\n\ndef del_word(x):\n s = (x.replace(\"透過行動裝置\", \"\").replace(\"[\", \"\").replace(\"]\", \"\").replace(\",\", \"\").replace(\"...更多\", \"\")\n .replace(\"'\", \"\").strip()).replace(' 由 Asia Online Language Studio 翻譯 評等翻譯', \"\").replace(\"TripAdvisor 會員\", \"\")\n\n result = re.split('體驗日期\\W\\s\\d+年\\d+月', s)\n result2 = re.split('感謝\\s+\\w+', \"\".join(result))\n return result2\n\n\ndf = pd.read_csv(\"E:/專題/景點爬蟲/tripadvisor/tripadvisor/情感分析/tripadvisor/Tokyo Metropolitan Government Buildings Observatories\",encoding=\"utf-8\")\n\n\n#clear data\ncontent = df[\"評論\"]\ncomment = []\nfor i in content:\n b = del_word(''.join(i))\n comment.append(b)\n\ndf[\"comment\"] = comment\ndf = df.drop(columns=[\"評論\"])\n\nstar = df[\"評論星等\"]\nstars = []\nfor i in star:\n a = i.replace(\"ui_bubble_rating bubble_\", \"\")\n stars.append(a)\n\ndf[\"Star\"] = stars\ndf = df.drop(columns=[\"評論星等\"])\n\n\n\n#Define pos&neg\n\npos=''\nneg=''\nfor i in range(df.shape[0]):\n if df.loc[i,\"Star\"] in [\"40\",\"50\"]:\n pos+=(df.loc[i,'comment'][0]+'\\n')\n else:\n neg+=(df.loc[i,'comment'][0]+'\\n')\n\n#Pos score\npoint = 0\nfor i in pos.split(\"\\n\"):\n if i != '':\n s = SnowNLP(i)\n # print(i)\n # print(s.sentiments)\n point += (s.sentiments)\npos_score = point/len(pos.split(\"\\n\"))\n\n\n#neg score\npoint = 0\nfor i in neg.split(\"\\n\"):\n if i != '':\n s = SnowNLP(i)\n # print(i)\n # print(s.sentiments)\n point += (s.sentiments)\nneg_score = point/len(neg.split(\"\\n\"))\n\n# pos + neg score\n# sentences = ''\n# for i in comment:\n# sentences += i[0] + \"\\n\"\n#\n# for i in sentences.split(\"\\n\"):\n# if i != \"\":\n# s = SnowNLP(i)\n# print(i)\n# print(s.sentiments)\n# point += (s.sentiments)\n# Score = point/len(pos.split(\"\\n\"))\n# print(Score)\n\n\nprint(\"*******************\")\nprint(pos_score)\nprint(neg_score)\n\n\n\n#寫到train_data裡面\n# with open(\n# 'C:\\\\Users\\\\Big data\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python37\\\\Lib\\\\site-packages\\\\snownlp\\\\sentiment\\\\pos_test.txt',\n# \"w\", encoding='utf-8') as f:\n# f.write(pos)\n\n\n\n\n\n","sub_path":"NLP/snownlp_1.py","file_name":"snownlp_1.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"611390813","text":"from selenium import webdriver\nfrom datetime import datetime\nimport time\n\nclass Paytm:\n def __init__(self):\n self.name = 'paytm'\n\n def Driver(self):\n self.driver = webdriver.Firefox()\n\n def closeDriver(self):\n self.driver.close()\n\n def scrapeData(self, url, df):\n self.driver.get(url)\n driver = self.driver\n driver = self.driver\n\n\n attributes = driver.find_elements_by_css_selector('.attributes')\n def getData(element):\n for attribute in attributes:\n if attribute.find_element_by_css_selector('.col1').text == element:\n return attribute.find_element_by_css_selector('.col2').text\n\n \n \n try:\n PID = getData('Product Code')\n except:\n PID = ''\n URL_raw = url\n try:\n Title = driver.find_element_by_css_selector('.img-description').find_element_by_tag_name('h1').text\n except:\n Title = ''\n try:\n Brand = getData('Brand')\n except:\n Brand = ''\n try:\n Seller = driver.find_element_by_css_selector('.profile-description').text.split('\\n')[1]\n except:\n Seller = ''\n try:\n IMG_medium = driver.find_element_by_css_selector('.img-dis').find_element_by_tag_name('img').get_attribute('src')\n except:\n IMG_medium = ''\n try:\n IMG_large = driver.find_element_by_css_selector('.img-dis').find_element_by_tag_name('img').get_attribute('ng-src')\n except:\n IMG_large = ''\n try:\n Price_mrp = driver.find_element_by_css_selector('.md-raised.fl.md-button.md-default-theme').find_element_by_tag_name('span')\\\n .text.strip().replace('\"','').split('|')[0].replace('Buy for Rs ','').replace(',','').split('\\n')[1].replace('Rs.','')\n except:\n Price_mrp = ''\n try:\n Price_selling = driver.find_element_by_css_selector('.md-raised.fl.md-button.md-default-theme').find_element_by_tag_name('span')\\\n .text.strip().replace('\"','').split('|')[0].replace('Rs. ','').replace(',','').replace('Buy for Rs ','').split('\\n')[0]\n except:\n Price_selling = Price_mrp\n\n if Price_mrp == '':\n Price_mrp = Price_selling\n try:\n zipcode = driver.find_element_by_css_selector('.ng-pristine.ng-valid.md-input.ng-valid-maxlength.ng-touched')\n zipcode.send_keys('110001')\n driver.find_element_by_css_selector('.apply').click()\n except:\n pass\n time.sleep(1)\n try:\n data = driver.find_element_by_css_selector('.detail-Shipp.dotted-border').find_elements_by_tag_name('li')\n except:\n data = ''\n Price_shipping = ''\n try:\n for d in data:\n if 'Shipping Charges' in d.text:\n Price_shipping = d.text.replace('Shipping Charges: Rs','')\n elif 'Shipping : Free' in d.text:\n Price_shipping = 0\n else:\n Price_shipping = ''\n except:\n Price_shipping = ''\n Delivery = 'Not Available'\n\n try:\n for d in data:\n if 'Delivery available' in d.text:\n Delivery = 'Available'\n elif 'Delivery not available' in d.text:\n Delivery = 'Not Available'\n else:\n Delivery = 'Not Available'\n except:\n Delivery = 'Not Available'\n COD = ''\n try:\n for d in data:\n if 'Cash on Delivery available' in d.text:\n COD = 'Available'\n elif 'Cash on Delivery not available' in d.text:\n COD = 'Not Available'\n else:\n COD = ''\n except:\n COD = 'Not Available'\n try:\n EMI = ''\n except:\n EMI = ''\n try:\n breadcrums = driver.find_element_by_css_selector('.breadcrum').find_elements_by_tag_name('a')\n b = ''\n for bread in breadcrums:\n b = b + '|' + bread.text.strip()\n Category_path = b[1:]\n except:\n Category_path = ''\n try:\n Description = driver.find_element_by_css_selector('.ProductDescription').text\n except:\n Description = ''\n try:\n Offers = driver.find_element_by_css_selector('.offer-cont').text\n except:\n Offers = ''\n try:\n Average_rating = driver.find_element_by_css_selector('.rating-text').text.replace('/5','').replace('ratings','')\n except:\n Average_rating = ''\n Reviews = ''\n try:\n if driver.find_element_by_css_selector('.md-raised.fl.md-button.md-default-theme').find_element_by_tag_name('span').text.strip():\n Status = 'IN STOCK'\n else:\n Status = 'OUT OF STOCK'\n if 'Out of stock' in driver.page_source:\n Status = 'OUT OF STOCK'\n else:\n Status = 'IN STOCK'\n except:\n if 'Out of stock' in driver.page_source:\n Status = 'OUT OF STOCK'\n else:\n Status = 'IN STOCK'\n\n Condition = 'NEW'\n TimeStamp = str(datetime.now())\n\n nrow = df.shape[0]\n df.loc[nrow+1] = [PID, URL_raw, Title, Brand,Seller, IMG_medium, IMG_large, Price_mrp, Price_selling, Price_shipping, Delivery,\\\n COD,EMI, Category_path,Description,Offers,Average_rating,Reviews,Status,Condition,TimeStamp]\n\n return df\n","sub_path":"e-commerce-scraper3/20 April/paytm.py","file_name":"paytm.py","file_ext":"py","file_size_in_byte":5775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"44159966","text":"x=list(input())\nd={}\nfor i in x:\n\tif i not in d:\n\t\td[i]=1\n\telse:\n\t\td[i]+=1\n\n\nif d['(']==d[')'] and d['{']==d['}'] and d['[']==d[']']:\n\tprint('balanced')\nelse:\n\tprint('unbalanced')\t\t\t","sub_path":"bracket balance check.py","file_name":"bracket balance check.py","file_ext":"py","file_size_in_byte":182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"358658448","text":"import time\nfrom threading import Lock\n\nimport tensorflow as tf\nfrom colorama import Fore, Style\nfrom keras.models import *\n\nimport algorithms.ppo_threading.params as params\nfrom algorithms.policy_models.conv_models import ConvLSTMModel\nfrom algorithms.ppo_threading.memory import Memory\n\n\nclass Brain:\n\n def __init__(self, memory: Memory, ModelClass: ConvLSTMModel, collect_data):\n\n self.collect_data = collect_data\n\n # use this to influence the tensorflow behaviour\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = params.TF_ALLOW_GROWTH\n config.log_device_placement = params.TF_LOG_DEVICE_PLACEMENT\n\n self.session = tf.Session(config=config)\n K.set_session(self.session)\n K.manual_variable_initialization(True)\n\n # set up a model for policy and\n self.model = ModelClass()\n\n # the model only contains the function approximator\n # the loss function for training is set up here\n self.__setup_training()\n\n # running tensorflow in a multithreaded environment requires additional setup work\n # and freezing the resulting graph\n self.model.model._make_predict_function()\n self.session.run(tf.global_variables_initializer())\n self.default_graph = tf.get_default_graph()\n self.default_graph.finalize()\n\n # a globally shared memory, this will be filled by the asynchronous agents\n self.memory = memory\n\n def __setup_training(self):\n # due to keras' restrictions on loss functions,\n # we use tensorflow to create a minimization step for the custom loss\n\n # placeholders\n self.action_mask = Input(shape=(params.NUM_ACTIONS,), name=\"action_mask\")\n\n self.target_value = Input(shape=(1,), name=\"target_value\")\n self.advantage = Input(shape=(1,), name=\"advantage\")\n\n # the policies as predicted by old and new network\n # old policy should be cached in the memory, we can feed it here\n self.old_policy = Input(shape=(params.NUM_ACTIONS,), name=\"old_policy\")\n new_policy = self.model.pred_policy\n\n # masking them, only looking at the action that was actually taken\n old_action = self.old_policy * self.action_mask\n new_action = new_policy * self.action_mask\n\n old_action = K.sum(old_action, axis=-1, keepdims=True)\n new_action = K.sum(new_action, axis=-1, keepdims=True)\n\n # set up the policy loss of ppo_threading\n ratio = K.exp(K.log(new_action) - K.log(old_action))\n loss1 = ratio * self.advantage\n loss2 = tf.clip_by_value(ratio, 1.0 - params.RATIO_CLIP_VALUE, 1.0 + params.RATIO_CLIP_VALUE) * self.advantage\n loss_policy = - tf.reduce_mean(tf.minimum(loss1, loss2))\n\n # the values as predicted by old and new,\n # again we can feed the cached prediction\n self.old_value = Input(shape=(1,), name=\"old_value\")\n new_value = self.model.pred_value\n new_value_clipped = self.old_value + tf.clip_by_value(new_value - self.old_value, -params.VALUE_CLIP_RANGE,\n params.VALUE_CLIP_RANGE)\n value_loss_1 = (new_value - self.target_value) ** 2\n value_loss_2 = (new_value_clipped - self.target_value) ** 2\n loss_value = 0.5 * tf.reduce_mean(tf.maximum(value_loss_1, value_loss_2))\n loss_value = params.LOSS_VALUE * loss_value\n\n # the loss contains an entropy component which rewards exploration\n eps = 1e-10\n loss_entropy = - K.sum(new_policy * K.log(new_policy + eps), axis=-1, keepdims=True)\n loss_entropy = params.LOSS_ENTROPY * loss_entropy\n\n # and we also add regularization\n loss_regularization = self.model.loss_regularization\n\n # the sum of all losses is\n loss = tf.reduce_sum(loss_policy + loss_value + loss_regularization + loss_entropy)\n\n # set up a tensorflow minimizer\n new_policy_variables = self.model.trainable_weights\n optimizer = tf.train.AdamOptimizer(learning_rate=params.LEARNING_RATE)\n gradients_variables = optimizer.compute_gradients(loss, new_policy_variables)\n if params.GRADIENT_NORM_CLIP is not None:\n gradients, variables = zip(*gradients_variables)\n gradients, gradient_norms = tf.clip_by_global_norm(gradients, params.GRADIENT_NORM_CLIP)\n gradients_variables = zip(gradients, variables)\n minimize_step = optimizer.apply_gradients(gradients_variables)\n\n self.minimize_step = minimize_step\n\n def optimize(self):\n # we train on blocks of this size\n num_samples = params.BATCH_SIZE * params.NUM_BATCHES\n\n # yield control if there is not enough training data in the memory\n if len(self.memory) < num_samples:\n #print(Fore.RED + \"memsleep\" + Style.RESET_ALL)\n time.sleep(0)\n return\n\n # start the updating process\n # the agent processes will see that this event has been set\n # they will wait for it to be cleared before continuing to generate samples\n self.collect_data.clear()\n\n # get all training data from the memory\n batch = self.memory.pop(None)\n\n (from_observations, from_states, to_observations, to_states, pred_policies, pred_values, actions, rewards,\n advantages,\n terminals, lengths) = batch\n\n from_observations = np.array(from_observations)\n from_states = np.array(from_states)\n to_observations = np.array(to_observations)\n to_states = np.array(to_states)\n pred_policies = np.array(pred_policies).reshape((-1, params.NUM_ACTIONS))\n pred_values = np.array(pred_values).reshape((-1, 1))\n actions = np.vstack(actions).reshape((-1, params.NUM_ACTIONS))\n rewards = np.vstack(rewards)\n terminals = np.vstack(terminals)\n advantages = np.vstack(advantages).reshape((-1, 1))\n lengths = np.vstack(lengths)\n\n num_samples = from_observations.shape[0]\n\n # predict the final value\n # _, end_values, _ = self.predict(to_observations, to_states)\n # target_values = rewards + params.GAMMA ** length * end_values * (1 - terminals)\n\n # TODO: again, this is the baseline version. find out why the z normalize the advantages\n target_values = advantages + pred_values\n #advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8)\n\n indices = np.arange(num_samples)\n\n for epoch in range(params.NUM_EPOCHS):\n np.random.shuffle(indices)\n\n for idx in range(num_samples//params.BATCH_SIZE):\n lower_idx = idx * params.BATCH_SIZE\n upper_idx = (idx + 1) * params.BATCH_SIZE\n batch_indices = indices[lower_idx:upper_idx]\n\n batch_observations = from_observations[batch_indices]\n batch_states = from_states[batch_indices]\n batch_policies = pred_policies[batch_indices]\n batch_values = pred_values[batch_indices]\n batch_action_mask = actions[batch_indices]\n batch_advantages = advantages[batch_indices]\n batch_target_values = target_values[batch_indices]\n\n # z-normalization\n batch_advantages = (batch_advantages - batch_advantages.mean()) / (batch_advantages.std() + 1e-8)\n\n # the model is responsible for plugging in observations and states as needed\n new_model_feed_dict = self.model.create_feed_dict(batch_observations, batch_states)\n\n self.session.run(self.minimize_step, feed_dict={\n **new_model_feed_dict,\n self.old_policy: batch_policies,\n self.old_value: batch_values,\n self.action_mask: batch_action_mask,\n self.advantage: batch_advantages,\n self.target_value: batch_target_values})\n\n print(Fore.RED+\"policy updated\"+Style.RESET_ALL)\n\n # tell the agents to collect data again\n self.collect_data.set()\n\n # the following methods will simply be routed to the model\n # this routing is not really elegant but I didn't want to expose the model outside of the brain\n def predict(self, observation, state):\n with self.default_graph.as_default():\n return self.model.predict(observation, state)\n\n def preprocess(self, observation):\n return self.model.preprocess(observation)\n\n def get_initial_state(self):\n return self.model.get_initial_state()\n","sub_path":"algorithms/ppo_threading/brain.py","file_name":"brain.py","file_ext":"py","file_size_in_byte":8602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"319493320","text":"import numpy as np\n\nsmoke_threshold_int = 50\nsmoke_threshold = 10\n\ndef height8w(d,t):\n \"\"\"\n Compute height at mesh bottom a.k.a. w-points \n :param d: open NetCDF4 dataset\n :param t: number of timestep\n \"\"\"\n ph = d.variables['PH'][t,:,:,:] \n phb = d.variables['PHB'][t,:,:,:]\n return (phb + ph)/9.81 # geopotential height at W points\n\ndef height(d,t):\n \"\"\"\n Compute height of mesh centers\n :param d: open NetCDF4 dataset\n :param t: number of timestep\n \"\"\"\n z8w = height8w(d,t)\n return 0.5*(z8w[0:z8w.shape[0]-1,:,:]+z8w[1:,:,:])\n\ndef plume_center(d,t):\n \"\"\"\n Compute plume center of mass\n :param d: open NetCDF4 dataset\n :param t: number of timestep\n \"\"\"\n tr = d.variables['tr17_1'][t,:,:,:]\n smoke_int = np.sum(tr, axis = 0)\n z = height(d,t) \n h = np.sum(z * tr, axis = 0)\n h[smoke_int <= smoke_threshold_int] = 0\n smoke_int[smoke_int <= smoke_threshold_int] = 1\n #c = np.zeros(tr.shape[1:])\n #for i in range(0, tr.shape[2]):\n # for j in range(0, tr.shape[1]):\n # ss=0\n # zs=0\n # for k in range(tr.shape[0]-1, -1, -1):\n # ss = ss + tr[k,j,i]\n # zs = zs + tr[k,j,i]* z[k,j,i]\n # if ss >= smoke_threshold_int:\n # c[j,i] = zs/ss\n # return c\n return h/smoke_int\n\ndef plume_height(d,t):\n \"\"\"\n Compute plume height \n :param d: open NetCDF4 dataset\n :param t: number of timestep\n \"\"\"\n z = height(d,t)\n tr = d.variables['tr17_1'][t,:,:,:]\n h = np.zeros(tr.shape[1:])\n for i in range(0, tr.shape[2]):\n for j in range(0, tr.shape[1]):\n for k in range(tr.shape[0]-1, -1, -1):\n if tr[k,j,i] > smoke_threshold:\n h[j,i] = z[k,j,i]\n break\n return h\n\n_var_wisdom = {\n 'PLUME_HEIGHT' : {\n 'name' : 'plume height',\n 'native_unit' : 'm',\n 'colorbar' : 'm',\n 'colormap' : 'jet',\n 'transparent_values' : [-np.inf, 0],\n 'scale' : [0, 8000],\n 'retrieve_as' : lambda d,t: plume_height(d,t),\n 'grid' : lambda d: (d.variables['XLAT'][0,:,:], d.variables['XLONG'][0,:,:]),\n },\n 'PLUME_CENTER' : {\n 'name' : 'plume height',\n 'native_unit' : 'm',\n 'colorbar' : 'm',\n 'colormap' : 'jet',\n 'transparent_values' : [-np.inf, 0],\n 'scale' : [0, 8000],\n 'retrieve_as' : lambda d,t: plume_center(d,t),\n 'grid' : lambda d: (d.variables['XLAT'][0,:,:], d.variables['XLONG'][0,:,:]),\n },\n 'FGRNHFX' : {\n 'name' : 'Ground level heat flux [log]',\n 'native_unit' : 'W/m^2',\n 'colorbar' : 'W/m^2',\n 'colormap' : 'jet',\n 'transparent_values' : [-np.inf, 1],\n 'scale' : [0, 6],\n 'retrieve_as' : lambda d,t: np.ma.filled(np.ma.log10(np.ma.masked_less_equal(d.variables['FGRNHFX'][t,:,:], 0)), 0),\n 'grid' : lambda d: (d.variables['FXLAT'][0,:,:], d.variables['FXLONG'][0,:,:]),\n },\n 'SMOKE_INT' : {\n 'name' : 'vertically integrated smoke',\n 'native_unit' : '-',\n 'colorbar' : None,\n 'colormap' : 'gray_r',\n 'transparent_values' : [-np.inf, smoke_threshold_int],\n 'scale' : 'original',\n 'retrieve_as' : lambda d,t: np.sum(d.variables['tr17_1'][t,:,:,:], axis=0),\n 'grid' : lambda d: (d.variables['XLAT'][0,:,:], d.variables['XLONG'][0,:,:]),\n },\n 'T2' : {\n 'name' : 'temperature at 2m',\n 'native_unit' : 'K',\n 'colorbar' : 'C',\n 'colormap' : 'jet',\n 'scale' : 'original',\n 'retrieve_as' : lambda d,t: d.variables['T2'][t,:,:],\n 'grid' : lambda d: (d.variables['XLAT'][0,:,:], d.variables['XLONG'][0,:,:]),\n },\n 'FIRE_AREA' : {\n 'name' : 'fire area',\n 'native_unit' : '-',\n 'colorbar' : None,\n 'colormap' : 'hot_r',\n 'transparent_values' : [-np.inf, 0],\n 'scale' : [0.0, 1.0],\n 'retrieve_as' : lambda d,t: d.variables['FIRE_AREA'][t,:,:],\n 'grid' : lambda d: (d.variables['FXLAT'][0,:,:], d.variables['FXLONG'][0,:,:])\n },\n 'FLINEINT' : {\n 'name' : 'fireline intensity',\n 'native_unit' : '-',\n 'colorbar' : '-',\n 'colormap' : 'jet',\n 'transparent_values' : [-np.inf, 1],\n 'scale' : 'original',\n 'retrieve_as' : lambda d,t: np.ma.filled(np.ma.log10(np.ma.masked_less_equal(d.variables['FLINEINT'][t,:,:], 0)), 0),\n 'grid' : lambda d: (d.variables['FXLAT'][0,:,:], d.variables['FXLONG'][0,:,:])\n },\n 'RH_FIRE' : {\n 'name' : 'relative humidity',\n 'native_unit' : '-',\n 'colorbar' : '-',\n 'colormap' : 'viridis_r',\n 'scale' : [0.0, 1.0],\n 'retrieve_as' : lambda d,t: d.variables['RH_FIRE'][t,:,:],\n 'grid' : lambda d: (d.variables['XLAT'][0,:,:], d.variables['XLONG'][0,:,:])\n },\n 'FIRE_HFX' : {\n 'name' : 'fire heat flux',\n 'native_unit' : 'W/m^2',\n 'colorbar' : 'W/m^2',\n 'colormap' : 'jet',\n 'scale' : 'original',\n 'transparent_values' : [-np.inf, 0],\n 'retrieve_as' : lambda d,t: d.variables['FIRE_HFX'][t,:,:],\n 'grid' : lambda d: (d.variables['FXLAT'][0,:,:], d.variables['FXLONG'][0,:,:])\n },\n 'F_ROS' : {\n 'name' : 'fire spread rate',\n 'native_unit' : 'm/s',\n 'colorbar' : 'm/s',\n 'colormap' : 'jet',\n 'scale' : [0.0, 2.0],\n 'retrieve_as' : lambda d,t: d.variables['F_ROS'][t,:,:],\n 'grid' : lambda d: (d.variables['FXLAT'][0,:,:], d.variables['FXLONG'][0,:,:])\n },\n 'PSFC' : {\n 'name' : 'surface pressure',\n 'native_unit' : 'Pa',\n 'colorbar' : 'Pa',\n 'colormap' : 'rainbow',\n 'scale' : 'original',\n 'retrieve_as' : lambda d, t: d.variables['PSFC'][t,:,:],\n 'grid' : lambda d: (d.variables['XLAT'][0,:,:], d.variables['XLONG'][0,:,:])\n },\n 'WINDSPD' : {\n 'name' : 'wind speed',\n 'native_unit' : 'm/s',\n 'colorbar' : 'm/s',\n 'colormap' : 'jet',\n 'scale' : 'original',\n 'retrieve_as' : lambda d, t: np.sqrt(d.variables['U10'][t,:,:]**2.0 + d.variables['V10'][t,:,:]**2.0),\n 'grid' : lambda d: (d.variables['XLAT'][0,:,:], d.variables['XLONG'][0,:,:])\n },\n 'WINDVEC' : {\n 'name' : 'wind speed',\n 'components' : [ 'U10', 'V10' ],\n 'native_unit' : 'm/s',\n 'scale' : 'original',\n 'grid' : lambda d: (d.variables['XLAT'][0,:,:], d.variables['XLONG'][0,:,:])\n },\n 'U10' : {\n 'name' : 'longitudinal wind component',\n 'retrieve_as' : lambda d, t: d.variables['U10'][t,:,:],\n },\n 'V10' : {\n 'name' : 'latitudinal wind component',\n 'retrieve_as' : lambda d, t: d.variables['V10'][t,:,:],\n },\n 'F_INT' : {\n 'name' : 'fireline intensity',\n 'native_unit' : 'J/m/s^2',\n 'colorbarct' : 'J/m/s^2',\n 'colormap' : 'jet',\n 'scale' : 'original',\n 'retrieve_as' : lambda d,t: d.variables['F_INT'][t,:,:],\n 'grid' : lambda d: (d.variables['FXLAT'][0,:,:], d.variables['FXLONG'][0,:,:])\n },\n 'NFUEL_CAT' : {\n 'name' : 'fuel categories',\n 'native_unit' : 'fuel_type',\n 'colorbar' : 'fuel_type',\n 'colormap' : 'Dark2',\n 'scale' : 'original',\n 'retrieve_as' : lambda d,t: d.variables['NFUEL_CAT'][t,:,:],\n 'grid' : lambda d: (d.variables['FXLAT'][0,:,:], d.variables['FXLONG'][0,:,:])\n },\n 'ZSF' : {\n 'name' : 'terrain height',\n 'native_unit' : 'm',\n 'colorbar' : 'm',\n 'colormap' : 'terrain',\n 'scale' : 'original',\n 'retrieve_as' : lambda d,t: d.variables['ZSF'][t,:,:],\n 'grid' : lambda d: (d.variables['FXLAT'][0,:,:], d.variables['FXLONG'][0,:,:])\n },\n 'FMC_G' : {\n 'name' : 'fuel moisture',\n 'native_unit' : '-',\n 'colorbar' : '-',\n 'colormap' : 'gist_earth_r',\n 'scale' : [0.0, 0.5],\n 'retrieve_as' : lambda d,t: d.variables['FMC_G'][t,:,:],\n 'grid' : lambda d: (d.variables['FXLAT'][0,:,:], d.variables['FXLONG'][0,:,:])\n },\n '1HR_FM' : {\n 'name' : '1-HR fuel moisture',\n 'native_unit' : '-',\n 'colorbar' : '-',\n 'colormap' : 'jet_r',\n 'scale' : [0.0, 0.5],\n 'retrieve_as' : lambda d,t: d.variables['FMC_GC'][t,0,:,:],\n 'grid' : lambda d: (d.variables['XLAT'][0,:,:], d.variables['XLONG'][0,:,:])\n },\n '10HR_FM' : {\n 'name' : '10-HR fuel moisture',\n 'native_unit' : '-',\n 'colorbar' : '-',\n 'colormap' : 'jet_r',\n 'scale' : [0.0, 0.5],\n 'retrieve_as' : lambda d,t: d.variables['FMC_GC'][t,1,:,:],\n 'grid' : lambda d: (d.variables['XLAT'][0,:,:], d.variables['XLONG'][0,:,:])\n },\n '100HR_FM' : {\n 'name' : '100-HR fuel moisture',\n 'native_unit' : '-',\n 'colorbar' : '-',\n 'colormap' : 'jet_r',\n 'scale' : [0.0, 0.5],\n 'retrieve_as' : lambda d,t: d.variables['FMC_GC'][t,2,:,:],\n 'grid' : lambda d: (d.variables['XLAT'][0,:,:], d.variables['XLONG'][0,:,:])\n },\n 'FMC_EQUI' : {\n 'name' : 'fuel moisture equilibrium',\n 'native_unit' : '-',\n 'colorbar' : '-',\n 'colormap' : 'jet_r',\n 'scale' : [0.0, 1.0],\n 'retrieve_as' : lambda d,t: d.variables['FMC_EQUI'][t,0,:,:],\n 'grid' : lambda d: (d.variables['XLAT'][0,:,:], d.variables['XLONG'][0,:,:])\n }\n}\n\n# contains functions to transform values from one unit to another in a simple format.\n# it's a dictionary with keys in the form (from_unit, to_unit) and the value is a lambda\n# that maps the value from to .\n_units_wisdom = {\n ('K', 'C') : lambda x: x - 273.15,\n ('K', 'F') : lambda x: 9.0 / 5.0 * (x - 273.15) + 32,\n ('m/s', 'ft/s') : lambda x: 3.2808399 * x,\n ('m', 'ft') : lambda x: 3.2808399 * x,\n ('ft/s','m/s') : lambda x: x / 3.2808399,\n ('ft', 'm') : lambda x: x / 3.2808399\n}\n\n\n\ndef get_wisdom(var_name):\n \"\"\"Return rendering wisdom for the variable .\"\"\"\n return _var_wisdom[var_name]\n\ndef get_wisdom_variables():\n \"\"\"Return the variables for which wisdom is available.\"\"\"\n return _var_wisdom.keys()\n\ndef convert_value(unit_from, unit_to, value):\n # handle the simple case\n if unit_from == unit_to:\n return value\n\n func = _units_wisdom.get((unit_from, unit_to))\n if func is None:\n return None\n else:\n return func(value)\n\n\n","sub_path":"src/vis/var_wisdom.py","file_name":"var_wisdom.py","file_ext":"py","file_size_in_byte":10636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"286281213","text":"#!/usr/bin/python3\nimport numpy\nfrom collections import OrderedDict, defaultdict\ndimension = 100\nfold = \"1\"\n\ndef LoadEntity2Id(filename):\n mapping = OrderedDict()\n with open(filename, 'r') as f:\n # skep the first line, which is a total number.\n f.readline()\n for line in f:\n items = line.strip().split(\"\\t\")\n mapping[items[0]] = items[1]\n return mapping\n\ndef LoadEntityVectors(entityVectorFile, dimension): \n entity2vector = OrderedDict()\n id = 0\n with open(entityVectorFile, 'r') as entityVectorsStream:\n for line in entityVectorsStream:\n items = line.strip()\n entity2vector[str(id)] = items\n id += 1\n return entity2vector\n\nprint(\"Load entity vectors...\")\nentity2vector = LoadEntityVectors(\"/home/laboratory/lab/BioCreative/codePlayer/Fast-TransX/transE/output/100d/entity2vec.vec\", dimension)\nprint(\"Load entity id mapping...\")\nentity2id = LoadEntity2Id(\"/home/laboratory/lab/BioCreative/codePlayer/Fast-TransX/data/entity2id.txt\")\n\nfilelist = [\n \"/home/laboratory/lab/BioCreative/2017/BC6/corpus_train_sentence.txt\"\n]\nmaxId = max([int(elem) for elem in entity2id.values()]) + 1\nfor filename in filelist:\n with open(filename, 'r') as f:\n for line in f:\n items = line.strip().split(\"\\t\")\n if items[2] not in entity2id:\n entity2id[items[2]] = maxId\n maxId += 1\n if items[3] not in entity2id:\n entity2id[items[3]] = maxId\n maxId += 1\n\nentity2idFile = \"/home/laboratory/lab/BioCreative/codePlayer/Fast-TransX/data/entity2id.txt.new\"\nentity2vecFile = \"/home/laboratory/lab/BioCreative/codePlayer/Fast-TransX/transE/output/100d/entity2vec.vec.new\"\n\nentity2idStream = open(entity2idFile, 'w')\nentity2vecStream = open(entity2vecFile, 'w')\n\nentity2idStream.write(str(len(entity2id)) + \"\\n\")\nfor vec in entity2vector:\n entity2vecStream.write(entity2vector[vec] + \"\\n\")\nfor key in entity2id:\n entityid = entity2id[key]\n entity2idStream.write(\"{}\\t{}\\n\".format(key, entityid))\n if entityid not in entity2vector:\n print(entityid)\n entity2vector[entityid] = \"\\t\".join([str(elem) for elem in list(numpy.random.uniform(-0.1, 0.1, dimension))])\n entity2vecStream.write(entity2vector[entityid] + \"\\n\")\nentity2vecStream.close()\nentity2idStream.close()","sub_path":"preprocessing/initUnknowEntityVec.py","file_name":"initUnknowEntityVec.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"506699069","text":"#!/bin/env python\n# -*- coding: utf-8 -*-\n# encoding=utf-8 vi:ts=4:sw=4:expandtab:ft=python\n#======================================================================\n#\n# Copyright (c) 2017 Baidu.com, Inc. All Rights Reserved\n#\n#======================================================================\n\"\"\"\n/***************************************************************************\n *\n * Copyright (c) 2019 Baidu.com, Inc. All Rights Reserved\n * @file test_sgd.py\n * @author liyang109@baidu.com\n * @date 2021-03-24 15:46\n * @brief \n *\n **************************************************************************/\n\"\"\"\nimport paddle\nimport numpy as np\nimport paddle.fluid as fluid\n# global params\ntypes = [np.float64, np.float32]\nif fluid.is_compiled_with_cuda() is True:\n places = [fluid.CPUPlace(), fluid.CUDAPlace(0)]\nelif paddle.is_compiled_with_npu() is True:\n places = [fluid.CPUPlace(), paddle.NPUPlace(7)]\nelse:\n places = [fluid.CPUPlace()]\n\n\n\ndef test_static_learning_rate():\n \"\"\"\n test_static_learning_rate\n \"\"\"\n for place in places:\n for t in types:\n paddle.enable_static()\n paddle.set_default_dtype(t)\n main_program = fluid.Program()\n startup_program = fluid.Program()\n with fluid.program_guard(main_program=main_program, startup_program=startup_program):\n input1 = paddle.static.data(name=\"x\", shape=[3, 1])\n input2 = paddle.static.data(name=\"y\", shape=[3, 2])\n bilinear = paddle.nn.Bilinear(1, 2, 4,\n weight_attr=fluid.initializer.ConstantInitializer(value=2.0),\n bias_attr=None)\n sgd = paddle.optimizer.SGD(parameters=[bilinear.weight, bilinear.bias],\n learning_rate=0.01, weight_decay=0.0)\n output = bilinear(input1, input2)\n output = paddle.mean(output)\n sgd.minimize(output)\n exe = fluid.Executor(place)\n exe.run(startup_program)\n x = np.arange(3, 6).reshape((3, 1)).astype(t)\n y = np.arange(6, 12).reshape((3, 2)).astype(t)\n for i in range(10):\n out, weight = exe.run(main_program, feed={'x': x, 'y': y}, fetch_list=[output, bilinear.weight])\n res = np.array([[[1.1666663, 1.0666664]], [[1.1666663, 1.0666664]],\n [[1.1666663, 1.0666664]], [[1.1666663, 1.0666664]]])\n assert np.allclose(np.array(weight).shape, res.shape)","sub_path":"npu/test_sgd.py","file_name":"test_sgd.py","file_ext":"py","file_size_in_byte":2615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"448663821","text":"from heapq import heappush, heappop, heapify\nfrom aStar import aStar\nfrom dijkstra import dijkstra\nfrom bfs import bfs\nimport board\nfrom node import Node\n\n# Run BFS\ndef doBfs(map, startNode, goalNode):\t\n\tprint('BFS algorithm')\n\n\t# Start the search\n\tmap, numberOfOpenNodes, numberOfClosedNodes = bfs(map, startNode, goalNode)\n\tprintMap(map, numberOfOpenNodes, numberOfClosedNodes)\n\n# Run Dijkstra\ndef doDijkstra(map, startNode, goalNode):\t\n\tprint('Dijkstra algorithm')\n\t\n\t# Start the search\n\tmap, numberOfOpenNodes, numberOfClosedNodes = dijkstra(map, startNode, goalNode)\n\tprintMap(map, numberOfOpenNodes, numberOfClosedNodes)\n\n# Run A*\ndef doAStar(map, startNode, goalNode):\t\n\tprint('A* algorithm')\n\t\n\t# Start the search\n\tmap, numberOfOpenNodes, numberOfClosedNodes = aStar(map, startNode, goalNode)\n\tprintMap(map, numberOfOpenNodes, numberOfClosedNodes)\n\n# All the search algoritms returns the edited map and total number of\n# opened and closed nodes.\ndef printMap(map, numberOfOpenNodes, numberOfClosedNodes):\n\tprint('Number of closed nodes: ' + str(numberOfClosedNodes))\n\tprint('Number of opened nodes: ' + str(numberOfOpenNodes))\n\tboard.printBoard(map)\t\n\tprint('__________________________________________')\n\tprint('')\n\ndef main():\n\t# Find shortest path on all the boards\n\tboards = ['boards/board-1-1.txt', 'boards/board-1-2.txt', 'boards/board-1-3.txt', 'boards/board-1-4.txt', 'boards/board-2-1.txt', 'boards/board-2-2.txt', 'boards/board-2-3.txt', 'boards/board-2-4.txt']\n\tfor i in xrange(len(boards)):\n\t\tprint(str(i) + ': ' + boards[i])\n\t\t\n\tboardNumber = int(raw_input('Enter board number: '))\n\tprint('')\n\t\n\t# Read the board from file\n\tdijkstraMap = board.readBoardFromFile(boards[boardNumber])\n\tbfsMap = board.readBoardFromFile(boards[boardNumber])\n\tastarMap = board.readBoardFromFile(boards[boardNumber])\n\n\t# Get start and goal node\n\tstartNode = Node(board.findStart(bfsMap))\n\tgoalNode = Node(board.findGoal(bfsMap))\n\n\t# Do all the search algoritms\n\tdoBfs(bfsMap, startNode, goalNode)\n\tdoDijkstra(dijkstraMap, startNode, goalNode)\n\tdoAStar(astarMap, startNode, goalNode)\n\nmain()","sub_path":"exercise3/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"539237715","text":"import matplotlib.pyplot as plt\r\nimport matplotlib as mpl\r\nimport csv\r\n\r\n'''读取csv文件'''\r\n\r\n\r\ndef readcsv(files):\r\n csvfile = open(files, 'r')\r\n plots = csv.reader(csvfile, delimiter=',')\r\n x = []\r\n y = []\r\n for row in plots:\r\n y.append((row[1]))\r\n x.append((row[0]))\r\n return x, y\r\n\r\n\r\nmpl.rcParams['font.family'] = 'sans-serif'\r\nmpl.rcParams['font.sans-serif'] = 'NSimSun,Times New Roman'\r\n\r\nplt.figure()\r\n#################################################################\r\nx1, y1 = readcsv(\"cifar_1.csv\")\r\na1=2000\r\nb1=0.103\r\nplt.plot(x1, y1, color='r', linestyle='-',label='Gauss')\r\nplt.scatter(a1, b1,s=250, color='r', marker='^')\r\n\r\n\r\nx2, y2 = readcsv(\"cifar_2.csv\")\r\na2=3100\r\nb2=0.116\r\nplt.plot(x2, y2, color='g', linestyle='-.',label='He')\r\nplt.scatter(a2, b2, s=250,color='g', marker='^')\r\n\r\nx3, y3 = readcsv(\"cifar_3.csv\")\r\n\r\na3=1400\r\nb3=0.08\r\nplt.plot(x3, y3, color='b', linestyle=':',label='Our algorithm')\r\nplt.scatter(a3, b3, s=250,color='b', marker='^')\r\n# ##################################################################\r\n# x1, y1 = readcsv(\"corel_1.csv\")\r\n# a1=180\r\n# b1=0.109\r\n# plt.plot(x1, y1, color='r', linestyle='-',label='Gauss')\r\n# plt.scatter(a1, b1,s=250, color='r', marker='^')\r\n#\r\n#\r\n# x2, y2 = readcsv(\"corel_2.csv\")\r\n# a2=210\r\n# b2=0.1\r\n# plt.plot(x2, y2, color='g', linestyle='-.',label='He')\r\n# plt.scatter(a2, b2, s=250,color='g', marker='^')\r\n#\r\n# x3, y3 = readcsv(\"corel_3.csv\")\r\n# a3=150\r\n# b3=0.070\r\n# plt.plot(x3, y3, color='b', linestyle=':',label='Our algorithm')\r\n# plt.scatter(a3, b3, s=250,color='b', marker='^')\r\n##################################################################\r\n\r\nplt.xticks(fontsize=16)\r\nplt.yticks(fontsize=16)\r\n\r\nplt.ylim(0, 2)\r\nplt.xlim(0, 4000)\r\n# plt.ylim(0, 2)\r\n# plt.xlim(0, 300)\r\nplt.xlabel('Steps', fontsize=20)\r\nplt.ylabel('Loss', fontsize=20)\r\nplt.legend(fontsize=16)\r\nplt.show()","sub_path":"8_Me_paper_two/picture.py","file_name":"picture.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"464356889","text":"\nclass Node(object):\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\nclass Tree(object):\n def __init__(self, value):\n self.root = Node(value)\n\n def isbalanced(self, root):\n if not root: return True\n\n buf = []\n delim = None\n eachlevelcount = [1]\n\n buf.insert(0, root)\n buf.insert(0, delim)\n\n while True:\n node = buf.pop()\n if node:\n print(str(node.value) + \" \", end=\"\")\n if node.left:\n buf.insert(0, node.left)\n if node.right:\n buf.insert(0, node.right)\n else:\n print('\\n')\n #print(\"buf length = \" + str(len(buf)))\n nextlevelcount = len(buf)\n if len(buf) == 0: break\n eachlevelcount.append(len(buf))\n buf.insert(0, delim)\n\n print(eachlevelcount)\n\n\n\nbalancedtree = Tree(1)\nbalancedtree.root.left = Node(2)\nbalancedtree.root.right = Node(3)\nbalancedtree.root.left.left = Node(4)\nbalancedtree.root.right.left = Node(5)\nbalancedtree.root.right.right = Node(6)\n\n'''\nbalanced\n 1\n / \\\n 2 3\n / / \\\n 4 5 6\n\nimbalanced\n 1\n / \\\n 2 3\n \\\n 4\n \\\n 5\n'''\nimbalancedtree = Tree(1)\nimbalancedtree.root.left = Node(2)\nimbalancedtree.root.right = Node(3)\nimbalancedtree.root.right.right = Node(4)\nimbalancedtree.root.right.right.right = Node(5)\n\n#print(imbalancedtree.isbalanced(imbalancedtree.root))\nprint(balancedtree.isbalanced(balancedtree.root))\n","sub_path":"ic_4_superbalanced_bin_tree.py","file_name":"ic_4_superbalanced_bin_tree.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"388193315","text":"#see sorce: https://github.com/chibueze07/Machine-Learning-In-Law/blob/master/project.ipynb\n\nfrom sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer\nfrom sklearn.decomposition import LatentDirichletAllocation\nimport pandas as pd\nimport numpy as np\nimport mglearn\n\nclass SimpleTopicModel():\n def __init__(self, cleaned_text=None, topic_qn=5, words_qn=10, ngr=(1,1)):\n self.text = cleaned_text\n self.tq = topic_qn\n self.wq = words_qn\n self.ngr=ngr\n self.model()\n \n def model(self):\n vect=CountVectorizer(ngram_range=self.ngr)\n dtm=vect.fit_transform(self.text)\n dtm\n lda=LatentDirichletAllocation(n_components=self.tq)\n _=lda.fit_transform(dtm)\n sorting=np.argsort(lda.components_)[:,::-1]\n features=np.array(vect.get_feature_names())\n mglearn.tools.print_topics(topics=range(self.tq), feature_names=features, \\\n sorting=sorting, topics_per_chunk=self.tq, n_words=self.wq)\n","sub_path":"simpletopicmodel.py","file_name":"simpletopicmodel.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"431976284","text":"import math\nimport datetime\nfrom django.conf import settings\nfrom django.utils import timezone\nfrom django.db import models\nfrom django.db.models import Count, Sum, Avg\nfrom django.db.models.signals import pre_save,post_save\nfrom django.core.urlresolvers import reverse\nfrom technofresh.utils import unique_order_id_generator\nfrom addresses.models import Address\nfrom billing.models import BillingProfile\nfrom carts.models import Cart\nfrom products.models import Product\n# Create your models here.\n\nORDERS_STATUS_CHOICES= (\n\t\t('created','Created'),\n\t\t('paid','Paid'),\n\t\t('shipped','Shipped'),\n\t\t('refunded','Refunded'),)\n\nclass OrderManagerQuerySet(models.query.QuerySet):\n\tdef recent(self):\n\t\treturn self.order_by(\"-updated\",\"-timestamp\")\n\tdef get_sales_breakdown(self):\n\t\trecent = self.recent().not_refunded()\n\t\trecent_data = recent.totals_data()\n\t\trecent_cart_data = recent.cart_data()\n\t\tshipped = recent.not_refunded().by_status(status='shipped')\n\t\tshipped_data = shipped.totals_data()\n\t\tpaid = recent.by_status(status='paid')\n\t\tpaid_data = paid.totals_data()\n\t\tdata = {\n\t\t\t\t'recent': recent,\n\t\t\t\t'recent_data':recent_data,\n\t\t\t\t'recent_cart_data': recent_cart_data,\n\t\t\t\t'shipped': shipped,\n\t\t\t\t'shipped_data': shipped_data,\n\t\t\t\t'paid': paid,\n\t\t\t\t'paid_data': paid_data,\n\t\t\t\t}\n\t\treturn data\n\n\tdef by_weeks_range(self,weeks_ago=7,number_of_weeks=2):\n\t\tif number_of_weeks > weeks_ago :\n\t\t\tnumber_of_weeks = weeks_ago\n\t\tdays_ago_start = weeks_ago * 7\n\t\tdays_ago_end = days_ago_start - ( number_of_weeks * 7 )\n\t\tstart_date = timezone.now() - datetime.timedelta(days=days_ago_start)\n\t\tend_date = timezone.now() - datetime.timedelta(days=days_ago_end)\n\t\treturn self.by_range(start_date,end_date=end_date)\n\n\tdef by_range(self,start_date,end_date= None):\n\t\tif end_date is None:\n\t\t\treturn self.filter(updated__gte=start_date)\n\t\treturn self.filter(updated__gte=start_date).filter(updated__lte=end_date)\n\t\treturn\n\tdef by_date(self):\n\t\tnow = timezone.now() - datetime.timedelta(days=9)\n\t\treturn self.filter(updated__day__gte =now.day)\n\tdef totals_data(self):\n\t\treturn self.aggregate(Sum(\"total\"), Avg(\"total\"))\n\tdef cart_data(self):\n\t\treturn self.aggregate(Sum(\"cart__products__price\"),\n\t\t\t\t\t\t\t Avg(\"cart__products__price\"),\n\t\t\t\t\t\t\t Count(\"cart__products\")\n\t\t\t\t\t\t\t )\n\tdef by_status(self,status=\"shipped\"):\n\t\treturn self.filter(status=status)\n\tdef not_refunded(self):\n\t\treturn self.exclude(status='refunded')\n\tdef by_request(self,request):\n\t\tbilling_profile ,created= BillingProfile.objects.new_or_get(request)\n\t\treturn self.filter(billing_profile=billing_profile)\n\n\tdef not_created(self):\n\t\treturn self.exclude(status='created')\n\nclass OrderManager(models.Manager):\n\n\tdef get_queryset(self):\n\t\treturn OrderManagerQuerySet(self.model,using=self._db)\n\n\tdef by_request(self,request):\n\t\treturn self.get_queryset().by_request(request)\n\n\n\tdef new_or_get(self,billing_profile,cart_obj):\n\t\tqs =self.get_queryset().filter(\n\t\t\tbilling_profile=billing_profile,\n\t\t\tcart=cart_obj,\n\t\t\tactive=True,\n\t\t\tstatus='created'\n\t\t)\n\t\tcreated = False\n\t\tif qs.count() == 1:\n\t\t\tobj\t= qs.first()\n\t\telse:\n\n\t\t\tobj = self.model.objects.create(billing_profile=billing_profile,cart=cart_obj)\n\t\t\tcreated = True\n\t\treturn obj, created\n\nclass Order(models.Model):\n\tbilling_profile = models.ForeignKey(BillingProfile,null=True,blank=True )\n\torder_id \t\t= models.CharField(max_length=120,blank=True)\n\tbilling_address\t= models.ForeignKey(Address,related_name=\"billing_address\",null=True,blank=True)\n\tshipping_address= models.ForeignKey(Address,related_name=\"shipping_address\",null=True,blank=True)\n\tcart \t\t= models.ForeignKey(Cart)\n\tstatus \t\t= models.CharField(max_length=120,default='created',choices=ORDERS_STATUS_CHOICES)\n\t#order_total\n\tshipping_total\t= models.DecimalField(default=50.00,max_digits=100,decimal_places=2)\n\ttotal\t\t\t= models.DecimalField(default=0.00,max_digits=100,decimal_places=2)\n\tactive\t\t\t= models.BooleanField(default=True)\n\ttimestamp\t\t= models.DateTimeField(auto_now_add=True)\n\tupdated\t\t\t= models.DateTimeField(auto_now=True)\n\tobjects \t\t= OrderManager()\n\n\tdef __str__(self):\n\t\treturn self.order_id\n\n\tclass Meta:\n\t\tordering = ['-timestamp','-updated']\n\tdef get_absolute_url(self):\n\t\treturn reverse(\"orders:detail\",kwargs={'order_id':self.order_id})\n\n\tdef get_status(self):\n\t\tif self.status == \"refunded\" :\n\t\t\treturn \"Refunded\"\n\t\telif self.status == 'shipped':\n\t\t\treturn \"shipped\"\n\t\treturn \"Shipping soon\"\n\tdef update_total(self):\n\t\tcart_total = self.cart.total\n\t\tif cart_total < 200 :\n\t\t\tshipping_total = self.shipping_total\n\t\t\tnew_total \t\t\t= math.fsum([cart_total,shipping_total])\n\t\telse:\n\t\t\tshipping_total = 0\n\t\t\tnew_total \t\t\t= math.fsum([cart_total,shipping_total])\n\t\tformatted_total = format(new_total,'.2f')\n\t\tself.total = formatted_total\n\t\tself.save()\n\t\treturn new_total\n\n\tdef check_done(self):\n\t\tbilling_profile \t= self.billing_profile\n\t\tshipping_address \t= self.shipping_address\n\t\tbilling_address\t \t= self.billing_address\n\t\ttotal \t\t\t\t=self.total\n\t\tif billing_profile and shipping_address and billing_address and total > 0:\n\t\t\treturn True\n\t\treturn False\n\tdef update_purchases(self):\n\t\tfor p in self.cart.products.all():\n\t\t\t\t\tobj, created=ProductPurchase.objects.get_or_create(\n\t\t\t\t\t\torder_id= self.order_id,\n\t\t\t\t\t\tproduct = p,\n\t\t\t\t\t\tbilling_profile=self.billing_profile\n\t\t\t\t\t)\n\t\treturn ProductPurchase.objects.filter(order_id=self.order_id).count()\n\n\tdef mark_paid(self):\n\t\tif self.status != \"paid\" : \n\t\t\tif self.check_done():\n\t\t\t\tself.status = \"created\"\n\t\t\t\tself.save()\n\t\t\t\tself.update_purchases()\n\t\t\t\t\t#obj.refunded = False\n\t\t\t\t\t#obj.save()\n\n\t\treturn self.status\n\t#order id should be unique and random\ndef pre_save_create_order_id(sender,instance,*args,**kwargs):\n\tif not instance.order_id:\n\t\tinstance.order_id = unique_order_id_generator(instance)\n\tqs= Order.objects.filter(cart=instance.cart).exclude(billing_profile=instance.billing_profile)\n\tif qs.exists():\n\t\tqs.update(active=False)\npre_save.connect(pre_save_create_order_id,sender=Order)\n\n\ndef post_save_cart_total(sender,instance,created,*args,**kwargs):\n\tif not created:\n\t\tcart_obj \t= instance\n\t\tcart_total \t= cart_obj.total\n\t\tcart_id \t= cart_obj.id\n\t\tqs\t\t\t= Order.objects.filter(cart_id=cart_id)\n\t\tif qs.count() == 1 :\n\t\t\torder_obj = qs.first()\n\t\t\torder_obj.update_total()\n\n\npost_save.connect(post_save_cart_total,sender=Cart)\n\ndef post_save_order(sender,instance,created,*args,**kwargs):\n\tif created:\n\t\tinstance.update_total()\n\npost_save.connect(post_save_order,sender=Order)\n\nclass ProductPurchaseManager(models.Manager):\n\tdef all(self):\n\t\treturn self.get_queryset().filter(refunded=False)\n\nclass ProductPurchase(models.Model):\n\torder_id \t\t= models.CharField(max_length=120)\n\tuser \t\t\t= models.ForeignKey(settings.AUTH_USER_MODEL,blank=True,null=True)\n\tbilling_profile = models.ForeignKey(BillingProfile,null=True,blank=True)\n\tproduct \t\t= models.ForeignKey(Product)\n\trefunded = models.BooleanField(default=False)\n\tupdated\t\t= models.DateTimeField(auto_now=True)\n\ttimestamp\t\t= models.DateTimeField(auto_now_add=True)\n\n\tobjects = ProductPurchaseManager()\n\n\tdef __str__(self):\n\t\treturn self.product.title\n\n\nclass OrderItem(models.Model):\n order = models.ForeignKey(Order, related_name='items')\n product = models.ForeignKey(Product, related_name='order_items')\n price = models.DecimalField(max_digits=10, decimal_places=2)\n quantity = models.PositiveIntegerField(default=1)\n\n def __str__(self):\n return '{}'.format(self.id)\n\n def get_cost(self):\n return self.price * self.quantity\n","sub_path":"src/orders/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"144733571","text":"from stop_words import STOP_WORDS_LIST\nfrom ukrainian_stemmer import UkrainianStemmer\nfrom pymongo import MongoClient\n\n\n\n\ndef clean_word(word):\n try:\n if word in STOP_WORDS_LIST:\n return '' # clean from stop words\n return UkrainianStemmer(word).stem_word()\n except Exception as e:\n print(e)\n return ''\n\n\ndef clean_document(text):\n words = text.split()\n return ' '.join([clean_word(w) for w in words])\n\n\nclient = MongoClient()\ndb = client.diplom\ncursor = db.news.find()\n\nfor document in cursor:\n document['text'] = clean_document(document['text'])\n db.news.save(document)","sub_path":"utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"379122201","text":"import unittest\nimport random\nimport string\nimport uuid\nimport sys\nfrom datetime import datetime, timedelta\n\nfrom ctools import *\n\n\nclass T(unittest.TestCase):\n\n def test_int8_to_datetime(self):\n start = datetime(2000, 1, 1)\n for i in range(1024):\n date = start + timedelta(days=i)\n d_int = date.year * 10000 + date.month * 100 + date.day\n self.assertEqual(date, int8_to_datetime(d_int))\n\n with self.assertRaises(ValueError):\n int8_to_datetime(1)\n\n def test_jump_consistent_hash(self):\n count = 1024\n bucket = 100\n m = {\n i: jump_consistent_hash(i, bucket)\n for i in range(count)\n }\n for i in range(count):\n b = jump_consistent_hash(i, bucket)\n self.assertEqual(m[i], b)\n n = {\n i: jump_consistent_hash(i, bucket + 1)\n for i in range(count)\n }\n equal_count = 0\n for i in range(count):\n if m[i] == n[i]:\n equal_count += 1\n\n # At most 1/6 keys is changed\n self.assertTrue(equal_count > (5 / 6 * count))\n\n def test_strhash(self):\n s = \"\".join(random.choice(string.printable) for _ in range(1024))\n us = \"文字テキスト텍스트كتابة\"\n a = strhash(s)\n for i in range(1024):\n self.assertEqual(strhash(s), a)\n\n for meth in (\"fnv1a\", \"fnv1\", \"djb2\", \"murmur\"):\n a = strhash(s, meth)\n b = strhash(us, meth)\n self.assertEqual(a, strhash(s, meth))\n self.assertEqual(b, strhash(us, meth))\n\n self.assertEqual(strhash(s), strhash(s, \"fnv1a\"))\n self.assertEqual(strhash(us), strhash(us, 'fnv1a'))\n\n self.assertNotEqual(strhash(s), strhash(s, \"fnv1\"))\n self.assertNotEqual(strhash(s), strhash(s, \"fnv1\"))\n\n with self.assertRaises(TypeError):\n strhash(s, method='fnv1a')\n\n\ndef set_random(mp):\n key = str(uuid.uuid1())\n val = str(uuid.uuid1())\n mp[key] = val\n return key\n\n\nclass LFUMemoryLeakTest(unittest.TestCase):\n\n def assertRefEqual(self, v1, v2, msg=None):\n self.assertEqual(sys.getrefcount(v1), sys.getrefcount(v2), msg)\n\n def assert_ref_equal(self, lfu_cache, lkey, d, dkey):\n lval = lfu_cache[lkey]\n dval = d[dkey]\n lval = lfu_cache[lkey]\n dval = d[dkey]\n self.assertEqual(sys.getrefcount(lval), sys.getrefcount(dval))\n\n del lfu_cache[lkey]\n del d[dkey]\n self.assertEqual(sys.getrefcount(lval), sys.getrefcount(dval))\n\n del d\n del lfu_cache\n self.assertEqual(sys.getrefcount(lval), sys.getrefcount(dval))\n\n def test_one_ref_eq(self):\n cache = LFUCache(10)\n mp = {}\n\n lkey = set_random(cache)\n dkey = set_random(mp)\n\n self.assert_ref_equal(cache, lkey, mp, dkey)\n\n lkey = set_random(cache)\n dkey = set_random(mp)\n\n lval = cache[lkey]\n dval = mp[dkey]\n\n del cache\n del mp\n self.assertRefEqual(lval, dval)\n\n def test_replace_ref_eq(self):\n cache = LFUCache(10)\n mp = {}\n\n lkey = set_random(cache)\n dkey = set_random(mp)\n\n lval = cache[lkey]\n dval = mp[dkey]\n lval = cache[lkey]\n dval = mp[dkey]\n self.assertRefEqual(lval, dval)\n\n cache[lkey] = str(uuid.uuid1())\n mp[dkey] = str(uuid.uuid1())\n\n self.assertRefEqual(lval, dval)\n self.assertRefEqual(cache[lkey], mp[dkey])\n self.assertRefEqual(lkey, dkey)\n\n def test_many_ref_eq(self):\n\n lfu_cache = LFUCache(257)\n d = {}\n for i in range(1024):\n set_random(lfu_cache)\n set_random(d)\n\n while True:\n try:\n lkey = list(lfu_cache.keys())[0]\n except IndexError:\n break\n dkey = list(d.keys())[0]\n self.assert_ref_equal(lfu_cache, lkey, d, dkey)\n\n def test_raw_ref_eq(self):\n cache = LFUCache(10)\n store = cache._store()\n d = {}\n\n lkey = set_random(cache)\n dkey = set_random(d)\n\n lval = cache[lkey]\n lval = store[lkey]\n lval = cache[lkey]\n dval = d[dkey]\n\n self.assertRefEqual(lval, dval)\n\n del cache[lkey]\n del d[dkey]\n self.assertRefEqual(lval, dval)\n\n del cache\n del d\n self.assertRefEqual(lval, dval)\n\n\nclass LFUTest(unittest.TestCase):\n def test_get_set(self):\n d = LFUCache(2)\n d['a'] = 1\n d['c'] = 2\n d['e'] = 3\n self.assertEqual(len(d), 2)\n\n for i in range(10):\n self.assertEqual(d['c'], 2)\n\n def test_len(self):\n for m in range(254, 1024):\n d = LFUCache(m)\n for i in range(m + 1):\n d[str(i)] = str(i)\n\n self.assertEqual(len(d), m)\n\n def test_keys(self):\n cache = LFUCache(257)\n keys = []\n for m in range(1024):\n keys.append(set_random(cache))\n\n for k in cache.keys():\n self.assertIn(k, keys)\n\n def test_values(self):\n cache = LFUCache(257)\n values = []\n for m in range(1024):\n values.append(cache[set_random(cache)])\n\n for v in cache.values():\n self.assertIn(v, values)\n\n def test_items(self):\n cache = LFUCache(257)\n values = []\n keys = []\n for m in range(1024):\n k = set_random(cache)\n keys.append(k)\n values.append(cache[k])\n\n for k, v in cache.items():\n self.assertIn(k, keys)\n self.assertIn(v, values)\n\n def test_contains(self):\n cache = LFUCache(2)\n keys = []\n for m in range(2):\n keys.append(set_random(cache))\n\n for k in keys:\n self.assertIn(k, cache)\n\n def test_setdefault(self):\n cache = LFUCache(2)\n for m in range(2):\n set_random(cache)\n k = str(uuid.uuid1())\n v = str(uuid.uuid1())\n val = cache.setdefault(k, v)\n self.assertEqual(v, val)\n self.assertIn(k, cache)\n self.assertEqual(cache[k], v)\n\n def test_get(self):\n cache = LFUCache(2)\n for m in range(2):\n set_random(cache)\n k = str(uuid.uuid1())\n v = str(uuid.uuid1())\n self.assertEqual(v, cache.get(k, v))\n self.assertNotIn(k, cache)\n cache[k] = v\n self.assertEqual(v, cache.get(k, 1))\n\n def test_update(self):\n d = {'1': '1'}\n cache = LFUCache(len(d))\n cache.update(d)\n for k in d:\n self.assertIn(k, cache)\n self.assertEqual(len(cache), len(d))\n\n d = {'abc': '1'}\n cache = LFUCache(len(d))\n cache.update(**d)\n for k in d:\n self.assertIn(k, cache)\n self.assertEqual(len(cache), len(d))\n\n def test_setnx(self):\n cache = LFUCache(10)\n key = str(uuid.uuid1())\n val = str(uuid.uuid1())\n\n with self.assertRaises(TypeError):\n cache.setnx(1, 1)\n\n v = cache.setnx(key, lambda: val)\n self.assertEqual(val, v)\n\n v = cache.setnx(key, lambda: 1)\n self.assertEqual(v, val)\n\n def test_iter(self):\n cache = LFUCache(257)\n keys = []\n for m in range(1024):\n k = set_random(cache)\n keys.append(k)\n\n for k in cache:\n self.assertIn(k, keys)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":7530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"306288100","text":"import numpy as np\r\n\r\ndef f(x1,x2):\r\n\r\n w1 = x1\r\n dw1 = 0\r\n w2 = x2\r\n dw2 = 1\r\n w3 = w1*w2\r\n dw3 = dw1 * w2 + w1 * dw2\r\n w4 = np.sin(w1)\r\n dw4 = np.cos(w1) * dw1\r\n w5 = w3 + w4\r\n dw5 = dw3 + dw4\r\n return w5, dw5\r\n\r\nval, deriv = f(1,2)\r\nprint(\"df/dx2 (1,2)=\" + str(deriv)) # df/dx2 = x1\r\n","sub_path":"new_stuff/01_autodiff/forwardmode/forwardmode3.py","file_name":"forwardmode3.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"393397174","text":"# coding=utf-8\n# 编译日期:2020-10-29 14:32:23\n# 版权所有:www.i-search.com.cn\nimport ubpa.init_input as iinput\nfrom ubpa.base_util import StdOutHook, ExceptionHandler\nimport ubpa.iimg as iimg\nimport ubpa.ikeyboard as ikeyboard\nimport ubpa.itools.rpa_fun as rpa_fun\nimport ubpa.iexcel as iexcel\nimport ubpa.itools.rpa_str as rpa_str\nimport time\nimport pdb\nfrom ubpa.ilog import ILog\nfrom ubpa.base_img import set_img_res_path\nimport getopt\nfrom sys import argv\nimport sys\nimport os\n\nclass NewProject1:\n \n def __init__(self,**kwargs):\n self.__logger = ILog(__file__)\n self.path = set_img_res_path(__file__)\n self.robot_no = ''\n self.proc_no = ''\n self.job_no = ''\n self.input_arg = ''\n if('robot_no' in kwargs.keys()):\n self.robot_no = kwargs['robot_no']\n if('proc_no' in kwargs.keys()):\n self.proc_no = kwargs['proc_no']\n if('job_no' in kwargs.keys()):\n self.job_no = kwargs['job_no']\n ILog.JOB_NO, ILog.OLD_STDOUT = self.job_no, sys.stdout\n sys.stdout = StdOutHook(self.job_no, sys.stdout)\n ExceptionHandler.JOB_NO, ExceptionHandler.OLD_STDERR = self.job_no, sys.stderr\n sys.excepthook = ExceptionHandler.handle_exception\n if('input_arg' in kwargs.keys()):\n self.input_arg = kwargs['input_arg']\n if(len(self.input_arg) <= 0):\n self.input_arg = iinput.load_init(__file__)\n if self.input_arg is None:\n sys.exit(0)\n \n def flow1(self):\n #鼠标点击\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow1,StepNodeTag:2020102811431669279,Title:鼠标点击,Note:')\n iimg.do_click_pos(waitfor=30.000,button='left',curson='Center',offsetX=100,times=2,image=r'snapshot_20201029102745076.png',image_size=r'107X19',win_title=r'银行日记账-条件查询',continue_on_error='break',img_res_path = self.path)\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow1,StepNodeTag:2020102811443953682,Title:模拟按键,Note:')\n time.sleep(0.3)\n ikeyboard.key_send_cs(waitfor=10.000,text='2016')\n time.sleep(0.3)\n #鼠标点击\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow1,StepNodeTag:20201029104525554947,Title:鼠标点击,Note:')\n iimg.do_click_pos(waitfor=30.000,button='left',curson='Center',offsetX=240,times=2,image=r'snapshot_20201029102745076.png',image_size=r'107X19',win_title=r'银行日记账-条件查询',continue_on_error='break',img_res_path = self.path)\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow1,StepNodeTag:20201029104628537954,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text=11)\n #鼠标点击\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow1,StepNodeTag:20201029103034188926,Title:鼠标点击,Note:')\n iimg.do_click_pos(waitfor=30.000,button='left',curson='Center',offsetX=100,times=2,image=r'snapshot_20201029103053436.png',image_size=r'94X18',win_title=r'银行日记账-条件查询',continue_on_error='break',img_res_path = self.path)\n time.sleep(0.3)\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow1,StepNodeTag:20201029102936035924,Title:模拟按键,Note:')\n time.sleep(0.3)\n ikeyboard.key_send_cs(waitfor=10.000,text='2017')\n time.sleep(0.3)\n #鼠标点击\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow1,StepNodeTag:20201029104712257957,Title:鼠标点击,Note:')\n iimg.do_click_pos(waitfor=30.000,button='left',curson='Center',offsetX=240,times=2,image=r'snapshot_20201029103053436.png',image_size=r'94X18',win_title=r'银行日记账-条件查询',continue_on_error='break',img_res_path = self.path)\n time.sleep(0.3)\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow1,StepNodeTag:20201029104741631965,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text='11')\n #鼠标点击\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow1,StepNodeTag:2020102811454933884,Title:鼠标点击,Note:')\n iimg.do_click_pos(waitfor=30.000,button='left',curson='Center',image=r'snapshot_20201028114606050.png',image_size=r'79X24',win_title=r'银行日记账-条件查询',continue_on_error='break',img_res_path = self.path)\n #鼠标点击\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow1,StepNodeTag:20201028133001493128,Title:鼠标点击,Note:')\n iimg.do_click_pos(waitfor=30.000,button='left',curson='Center',image=r'snapshot_20201028133026462.png',image_size=r'73X91',win_title=r'金蝶EAS-IT_Test',continue_on_error='break',img_res_path = self.path)\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow1,StepNodeTag:20201028133117833130,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text='1102{Enter}{Enter}')\n #图片检测\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow1,StepNodeTag:20201029092629318884,Title:图片检测,Note:')\n tvar_20201029092629318885=iimg.img_exists(waitfor=30.000,win_title=r'金蝶EAS-IT_Test',image=r'snapshot_20201029092535882.png',img_res_path = self.path)\n print('[flow1] [图片检测] [20201029092629318884] 返回值:[' + str(type(tvar_20201029092629318885)) + ']' + str(tvar_20201029092629318885))\n #鼠标点击\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow1,StepNodeTag:2020102813020652490,Title:鼠标点击,Note:')\n iimg.do_click_pos(waitfor=30.000,button='left',curson='Center',image=r'snapshot_20201029091730871.png',image_size=r'79X23',win_title=r'金蝶EAS-IT_Test',continue_on_error='break',img_res_path = self.path)\n \n def flow2(self,fangshi=None,leixing=None,initial=4,num=0,excel=0):\n #鼠标点击\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201029100501969918,Title:鼠标点击,Note:')\n iimg.do_click_pos(waitfor=30.000,button='left',curson='Center',offsetX=10,image=r'snapshot_20201029100607886.png',image_size=r'14X24',win_title=r'金蝶EAS-IT_Test',continue_on_error='break',img_res_path = self.path)\n #鼠标点击\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201029100714286921,Title:鼠标点击,Note:')\n iimg.do_click_pos(waitfor=30.000,button='left',curson='Center',image=r'snapshot_20201029100801595.png',image_size=r'85X22',win_title=r'金蝶EAS-IT_Test',continue_on_error='break',img_res_path = self.path)\n #工作表行数获取\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028230910820504,Title:工作表行数获取,Note:')\n excel=iexcel.get_rows_count(path='C:/Users/Administrator/Desktop/银行日记账20201020112540会计录入收款信息.xlsx')\n print('[flow2] [工作表行数获取] [20201028230910820504] 返回值:[' + str(type(excel)) + ']' + str(excel))\n #鼠标点击\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028143452321202,Title:鼠标点击,Note:')\n iimg.do_click_pos(waitfor=30.000,button='left',curson='Center',image=r'snapshot_20201028143508572.png',image_size=r'77X29',win_title=r'金蝶EAS-IT_Test',continue_on_error='break',img_res_path = self.path)\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201029015023339827,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text='{Tab}')\n # For循环\n self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:flow2,StepNodeTag:20201028230954859509,Title:For循环,Note:')\n for num in range(excel-3):\n #单元格读取\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201029012445614787,Title:单元格读取,Note:')\n time.sleep(0.3)\n tvar_20201029012445614788=iexcel.read_cell(path='C:/Users/Administrator/Desktop/银行日记账20201020112540会计录入收款信息.xlsx',cell='B'+str(initial),cell_type='time')\n print('[flow2] [单元格读取] [20201029012445614787] 返回值:[' + str(type(tvar_20201029012445614788)) + ']' + str(tvar_20201029012445614788))\n time.sleep(0.3)\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028143734693212,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text=tvar_20201029012445614788)\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028150809975282,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text='{Tab}')\n #单元格读取\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028144321938225,Title:单元格读取,Note:')\n time.sleep(0.3)\n tvar_20201028144321939226=iexcel.read_cell(path='C:/Users/Administrator/Desktop/银行日记账20201020112540会计录入收款信息.xlsx',cell='C'+str(initial),cell_type='time')\n print('[flow2] [单元格读取] [20201028144321938225] 返回值:[' + str(type(tvar_20201028144321939226)) + ']' + str(tvar_20201028144321939226))\n time.sleep(0.3)\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028144335510228,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text=tvar_20201028144321939226)\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028144459937234,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text='{Tab}')\n #单元格读取\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028144459937236,Title:单元格读取,Note:')\n time.sleep(0.3)\n tvar_20201028144459937237=iexcel.read_cell(path='C:/Users/Administrator/Desktop/银行日记账20201020112540会计录入收款信息.xlsx',cell='I'+str(initial),cell_type='string')\n print('[flow2] [单元格读取] [20201028144459937236] 返回值:[' + str(type(tvar_20201028144459937237)) + ']' + str(tvar_20201028144459937237))\n time.sleep(0.3)\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028144459937235,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text=tvar_20201028144459937237)\n time.sleep(0.5)\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028151111503295,Title:模拟按键,Note:')\n time.sleep(0.5)\n ikeyboard.key_send_cs(waitfor=10.000,text='{Tab}')\n #单元格读取\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:202010291412063991055,Title:单元格读取,Note:')\n time.sleep(0.3)\n leixing=iexcel.read_cell(path='C:/Users/Administrator/Desktop/银行日记账20201020112540会计录入收款信息.xlsx',cell='D'+str(initial),cell_type='string')\n print('[flow2] [单元格读取] [202010291412063991055] 返回值:[' + str(type(leixing)) + ']' + str(leixing))\n time.sleep(0.3)\n # IF分支\n self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:flow2,StepNodeTag:202010291416021701074,Title:IF分支,Note:')\n if leixing == '银收':\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:202010291416444871078,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text='{Down 15}')\n elif leixing == '银付':\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:202010291417369811080,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text='{Down 8}')\n else:\n pass\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028153949690307,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text='{Enter}')\n #单元格读取\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028154040326309,Title:单元格读取,Note:')\n time.sleep(0.3)\n tvar_20201028154040327310=iexcel.read_cell(path='C:/Users/Administrator/Desktop/银行日记账20201020112540会计录入收款信息.xlsx',cell='E'+str(initial),cell_type=None)\n print('[flow2] [单元格读取] [20201028154040326309] 返回值:[' + str(type(tvar_20201028154040327310)) + ']' + str(tvar_20201028154040327310))\n time.sleep(0.3)\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028154124182312,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text=tvar_20201028154040327310)\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028173223637496,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text='{Tab 4}')\n #单元格读取\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:202010291422234261086,Title:单元格读取,Note:')\n time.sleep(0.3)\n fangshi=iexcel.read_cell(path='C:/Users/Administrator/Desktop/银行日记账20201020112540会计录入收款信息.xlsx',cell='J'+str(initial),cell_type='string')\n print('[flow2] [单元格读取] [202010291422234261086] 返回值:[' + str(type(fangshi)) + ']' + str(fangshi))\n time.sleep(0.3)\n # IF分支\n self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:flow2,StepNodeTag:202010291423319511100,Title:IF分支,Note:')\n if fangshi =='电汇':\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:202010291426471281103,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text='{Down 8}')\n elif fangshi =='银行承兑汇票(收)':\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:202010291427017501104,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text='{Down 3}')\n elif fangshi =='转帐':\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:202010291427022791107,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text='{Down 17}')\n else:\n pass\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028154301537329,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text='{Enter}')\n #单元格读取\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028154445770331,Title:单元格读取,Note:')\n time.sleep(0.3)\n tvar_20201028154445771332=iexcel.read_cell(path='C:/Users/Administrator/Desktop/银行日记账20201020112540会计录入收款信息.xlsx',cell='K'+str(initial),cell_type='string')\n print('[flow2] [单元格读取] [20201028154445770331] 返回值:[' + str(type(tvar_20201028154445771332)) + ']' + str(tvar_20201028154445771332))\n time.sleep(0.3)\n #replace\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028165150667415,Title:replace,Note:')\n tvar_20201028165150667416=rpa_str.replace(string=tvar_20201028154445771332,old='#',new='{#}')\n print('[flow2] [replace] [20201028165150667415] 返回值:[' + str(type(tvar_20201028165150667416)) + ']' + str(tvar_20201028165150667416))\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028165226010429,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text=tvar_20201028165150667416)\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028154630210337,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text='{Tab}')\n #单元格读取\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028154707544339,Title:单元格读取,Note:')\n time.sleep(0.3)\n tvar_20201028154707545340=iexcel.read_cell(path='C:/Users/Administrator/Desktop/银行日记账20201020112540会计录入收款信息.xlsx',cell='L'+str(initial),cell_type=None)\n print('[flow2] [单元格读取] [20201028154707544339] 返回值:[' + str(type(tvar_20201028154707545340)) + ']' + str(tvar_20201028154707545340))\n time.sleep(0.3)\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028154718140342,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text=tvar_20201028154707545340)\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028154748193347,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text='{Tab}')\n #单元格读取\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028154805912349,Title:单元格读取,Note:')\n time.sleep(0.3)\n tvar_20201028154805912350=iexcel.read_cell(path='C:/Users/Administrator/Desktop/银行日记账20201020112540会计录入收款信息.xlsx',cell='M'+str(initial),cell_type=None)\n print('[flow2] [单元格读取] [20201028154805912349] 返回值:[' + str(type(tvar_20201028154805912350)) + ']' + str(tvar_20201028154805912350))\n time.sleep(0.3)\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028154840804352,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text=tvar_20201028154805912350)\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201028172525264494,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text='{Tab 4}')\n #相加\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201029015908212843,Title:相加,Note:')\n initial=rpa_fun.add(a=initial,b=1)\n print('[flow2] [相加] [20201029015908212843] 返回值:[' + str(type(initial)) + ']' + str(initial))\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:flow2,StepNodeTag:20201029100341149915,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000)\n \n def leixing(self):\n pass\n \n def login(self):\n #热键输入\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:login,StepNodeTag:2020102716440633945,Title:热键输入,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text=r'#d')\n #鼠标双击\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:login,StepNodeTag:2020102716440633944,Title:鼠标双击,Note:')\n iimg.do_click_pos(waitfor=30.000,button='left',curson='Center',times=2,image=r'snapshot_20201029103253721.png',image_size=r'38X29',img_res_path = self.path)\n #鼠标点击\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:login,StepNodeTag:2020102716440633942,Title:鼠标点击,Note:')\n iimg.do_click_pos(waitfor=30.000,button='left',curson='Center',image=r'snapshot_20201027163736752.png',image_size=r'272X15',win_title=r'金蝶EAS系统登录',continue_on_error='break',img_res_path = self.path)\n #模拟按键\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:login,StepNodeTag:2020102716440633941,Title:模拟按键,Note:')\n ikeyboard.key_send_cs(waitfor=10.000,text=\"123456\")\n #鼠标点击\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:login,StepNodeTag:2020102716440633943,Title:鼠标点击,Note:')\n iimg.do_click_pos(waitfor=30.000,button='left',curson='Center',image=r'snapshot_20201027164204785.png',image_size=r'76X18',win_title=r'金蝶EAS系统登录',continue_on_error='break',img_res_path = self.path)\n \n def Main(self):\n #子流程\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:2020102716441979756,Title:子流程,Note:')\n tvar20201027164419797561=self.login()\n print('[Main] [子流程] [2020102716441979756] 返回值:[' + str(type(tvar20201027164419797561)) + ']' + str(tvar20201027164419797561))\n # Try异常\n self.__logger.dlogs(job_no=self.job_no, logmsg='Flow:Main,StepNodeTag:2020102813042663292,Title:Try异常,Note:')\n try:\n #图片检测\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:2020102813045662794,Title:图片检测,Note:')\n tvar_2020102813045662895=iimg.img_exists(waitfor=30.000,win_title=r'账号重复登录',image=r'snapshot_20201028130520424.png',img_res_path = self.path)\n print('[Main] [图片检测] [2020102813045662794] 返回值:[' + str(type(tvar_2020102813045662895)) + ']' + str(tvar_2020102813045662895))\n #鼠标点击\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:2020102813052718697,Title:鼠标点击,Note:')\n iimg.do_click_pos(waitfor=30.000,button='left',curson='Center',image=r'snapshot_20201028130553617.png',image_size=r'80X21',win_title=r'账号重复登录',continue_on_error='break',img_res_path = self.path)\n except Exception as e:\n pass\n finally:\n #鼠标点击\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:2020102716442586158,Title:鼠标点击,Note:')\n time.sleep(5)\n iimg.do_click_pos(waitfor=30.000,button='left',curson='Center',image=r'snapshot_20201029105623930.png',image_size=r'82X13',win_title=r'金蝶EAS-IT_Test',continue_on_error='break',img_res_path = self.path)\n #鼠标点击\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:2020102716463348960,Title:鼠标点击,Note:')\n iimg.do_click_pos(waitfor=30.000,button='left',curson='Center',image=r'snapshot_20201027164652739.png',image_size=r'151X20',win_title=r'金蝶EAS-IT_Test',continue_on_error='break',img_res_path = self.path)\n #鼠标点击\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:2020102716465797562,Title:鼠标点击,Note:')\n iimg.do_click_pos(waitfor=30.000,button='left',curson='Center',image=r'snapshot_20201027164724771.png',image_size=r'223X28',win_title=r'金蝶EAS-IT_Test',continue_on_error='break',img_res_path = self.path)\n #鼠标双击\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:2020102716515656866,Title:鼠标双击,Note:')\n iimg.do_click_pos(waitfor=30.000,button='left',curson='Center',times=2,image=r'snapshot_20201027165408189.png',image_size=r'212X21',win_title=r'金蝶EAS-IT_Test',img_res_path = self.path)\n #子流程\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:2020102811290944859,Title:子流程,Note:')\n tvar20201028112909448591=self.flow1()\n print('[Main] [子流程] [2020102811290944859] 返回值:[' + str(type(tvar20201028112909448591)) + ']' + str(tvar20201028112909448591))\n #图片检测\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:20201029092656397894,Title:图片检测,Note:')\n tvar_20201029092656397895=iimg.img_exists(waitfor=30.000,win_title=r'金蝶EAS-IT_Test',image=r'snapshot_20201029092735462.png',img_res_path = self.path)\n print('[Main] [图片检测] [20201029092656397894] 返回值:[' + str(type(tvar_20201029092656397895)) + ']' + str(tvar_20201029092656397895))\n #子流程\n self.__logger.dlogs(job_no=self.job_no,logmsg='Flow:Main,StepNodeTag:20201028173523203502,Title:子流程,Note:')\n tvar202010281735232035021=self.flow2()\n print('[Main] [子流程] [20201028173523203502] 返回值:[' + str(type(tvar202010281735232035021)) + ']' + str(tvar202010281735232035021))\n \nif __name__ == '__main__':\n ILog.begin_init()\n robot_no = ''\n proc_no = ''\n job_no = ''\n input_arg = ''\n try:\n argv = sys.argv[1:]\n opts, args = getopt.getopt(argv,\"hr:p:j:i:\",[\"robot = \",\"proc = \",\"job = \",\"input = \"])\n except getopt.GetoptError:\n print ('robot.py -r -p -j ')\n for opt, arg in opts:\n if opt == '-h':\n print ('robot.py -r -p -j ')\n elif opt in (\"-r\", \"--robot\"):\n robot_no = arg\n elif opt in (\"-p\", \"--proc\"):\n proc_no = arg\n elif opt in (\"-j\", \"--job\"):\n job_no = arg\n elif opt in (\"-i\", \"--input\"):\n input_arg = arg\n pro = NewProject1(robot_no=robot_no,proc_no=proc_no,job_no=job_no,input_arg=input_arg)\n pro.Main()\n","sub_path":"codes/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":25733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"136634863","text":"# Tic Tac Toe Terminal Game\n# Version 2.0 Python 3\n# Nicklas Vraa\n\n# Rewritten to object form.\n\nimport time, os, random, sys\n\nclass Game:\n def __init__(self, board):\n self.GRN, self.RED, self.STD = \"\\033[92m\", \"\\033[91m\", \"\\x1b[0m\" # Colors.\n self.wins = [{0,1,2}, {3,4,5}, {6,7,8}, {0,3,6}, {1,4,7}, {2,5,8}, {0,4,8}, {2,4,6}]\n self.turn = 0\n self.winner = \"Tie\"\n self.board = board\n self.player_first = True\n \n def setup(self, p1, p2):\n self.p1, self.p2 = p1, p2\n while True:\n self.board.clear()\n print(\"|\" + self.GRN + \"T\" + self.STD + \"|I|C| Welcome to TicTacToe.\")\n print(\"|\" + self.GRN + \"T\" + self.STD + \"|A|C| To win, place 3 in a straight line.\")\n ans = input(\"|\" + self.GRN + \"T\" + self.STD + \"|O|E| What symbol would you like? (x/o): \")\n if ans == \"x\": \n p1.set_symbol(\"x\")\n p2.set_symbol(\"o\")\n break\n elif ans == \"o\":\n p1.set_symbol(\"o\")\n p2.set_symbol(\"x\")\n self.player_first = False\n break\n else: \n print(\"\\nInvalid answer. Try again.\")\n time.sleep(1)\n\n def play(self):\n p1, p2 = Player(self), AI(self)\n self.setup(p1, p2)\n self.board.print_board()\n\n if self.player_first:\n first = p1.make_move\n second = p2.make_move\n else:\n first = p2.make_move\n second = p1.make_move\n\n while True:\n first()\n self.board.print_board()\n if self.__is_finished(): break\n second()\n self.board.print_board()\n if self.__is_finished(): break\n\n self.board.print_board()\n print(\"\\nGame Over. \" + self.winner + \".\\n\")\n\n def reset(self):\n self.board.board = [\" \",\" \",\" \",\" \",\" \",\" \",\" \",\" \",\" \"]\n self.p1.moves, self.p2.moves = set(), set()\n self.p1.set_symbol(\"\"), self.p2.set_symbol(\"\")\n self.player_first = True\n self.turn = 0\n self.winner = \"Tie\"\n\n def editor_specific(self):\n while True:\n self.board.clear()\n ans = input(\"Can your editor show colors, Allan? (y/n): \")\n if ans == \"y\": break\n if ans == \"n\": \n self.GRN, self.RED, self.STD = \"\", \"\", \"\"\n break\n else:\n print(\"Invalid input, try again.\")\n time.sleep(1)\n\n def __highlight(self, win, winner):\n for position in win:\n if winner == \"You won\":\n self.board.board[position] = self.GRN + self.board.board[position].upper() + self.STD\n else:\n self.board.board[position] = self.RED + self.board.board[position].upper() + self.STD\n\n def __is_finished(self):\n for win in self.wins:\n if win.issubset(self.p1.get_moves()):\n self.winner = \"You won\"\n self.__highlight(win, self.winner)\n return True\n if win.issubset(self.p2.get_moves()):\n self.winner = \"AI won\"\n self.__highlight(win, self.winner)\n return True\n\n if self.turn > 8: # Tie\n return True\n else: \n return False\n \nclass Board:\n def __init__(self):\n self.board = [\" \",\" \",\" \",\" \",\" \",\" \",\" \",\" \",\" \"]\n \n def print_board(self):\n self.clear()\n print(\"----+---+----\")\n for i in range(3):\n for j in range(3):\n print(\"| \" + self.board[i*3 + j] + \" \", end = '')\n print(\"|\\n\" + \"----+---+----\")\n\n def clear(self):\n os.system(\"cls\" if os.name == \"nt\" else \"clear\")\n\nclass AI:\n def __init__(self, game):\n self.moves = set()\n self.game = game\n\n def set_symbol(self, symbol):\n self.symbol = symbol\n\n def get_moves(self):\n return self.moves\n \n def make_move(self):\n offense, defense = False, False\n\n for win in self.game.wins: # Check for potential offensive moves.\n ai_line = set()\n for i in win: \n if i in self.moves: ai_line.add(i)\n\n if len(ai_line) == 2:\n offense_move = (win - ai_line).pop()\n if offense_move not in self.moves and offense_move not in self.game.p1.get_moves():\n offense = True # input(\"DEBUG - Offensive move: \" + str(offense_move))\n break\n\n for win in self.game.wins: # Check for potential defensive moves.\n player_line = set()\n for i in win:\n if i in self.game.p1.get_moves(): player_line.add(i)\n\n if len(player_line) == 2:\n defense_move = (win - player_line).pop()\n if defense_move not in self.moves and defense_move not in self.game.p1.get_moves():\n defense = True # input(\"DEBUG - Defensive move: \" + str(defense_move))\n break\n\n if offense: move = offense_move\n elif defense: move = defense_move\n else:\n valid_move = False\n while not valid_move:\n move = random.randint(0,8) # Random to avoid ties every time.\n if move not in self.moves and move not in self.game.p1.get_moves():\n valid_move = True\n\n self.game.board.board[move] = self.game.RED + self.symbol + self.game.STD\n self.moves.add(move)\n self.game.turn += 1\n time.sleep(1)\n\nclass Player:\n def __init__(self, game):\n self.moves = set()\n self.game = game\n \n def set_symbol(self, symbol):\n self.symbol = symbol\n\n def get_moves(self):\n return self.moves\n\n def make_move(self):\n valid_move = False\n\n while not valid_move: \n move = input(\"\\nPlace your \" + self.symbol + \": \")\n if move.isdigit():\n move = int(move)\n if move >= 0 and move <= 8:\n if move not in self.moves and move not in self.game.p2.get_moves():\n self.game.board.board[move] = self.game.GRN + self.symbol + self.game.STD\n self.moves.add(move)\n valid_move = True\n self.game.turn += 1\n else:\n print(\"Position already used.\")\n time.sleep(1)\n else:\n print(\"Invalid position. Has to be between 0 and 8.\")\n time.sleep(1)\n else:\n print(\"Not a number. Try again.\")\n time.sleep(1)\n self.game.board.print_board()\n\ndef main():\n board = Board()\n game = Game(board)\n game.editor_specific()\n game.play()\n while True:\n ans = input(\"Play again? (y/n): \")\n if ans == \"y\":\n game.reset()\n game.play()\n elif ans == \"n\":\n break\n else:\n print(\"Invalid answer. Try again.\")\n time.sleep(1)\n board.clear()\n\nmain()\n","sub_path":"tictactoeOOP.py","file_name":"tictactoeOOP.py","file_ext":"py","file_size_in_byte":7174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"474256417","text":"#! /usr/bin/python\n'''\nGrover: a grain size-measuring rover using Pixhawk 2.0 connected via a serial connecti$\n\nDeveloped by Grant Otto, Courtney Cowger, Zach El-Azom, Eriq Gloria, Cole Stinger, Aar$\nUniversity of Delaware Department of Mechanical Engineering\nFaculty Advisor: Adam Wickenheiser\n\nDeveloped for use at the Robotics Discovery Lab, University of Delaware School of Mari$\nSponsor and PI of Robotics Discovery Lab: Arthur Trembanis\n\nwwww.udel.edu\n\nAll code is public and free to use.\n'''\n\n'''\n***** KNOWN ISSUES *****\n- take image function needs to add in all code for taking the image, gps point, stepper control, etc\n- if the switch for the image capture is left down, the vehicle will continuously take image after image.\n\tIn the future, the r/c channel will be changed to a button but this will require a bit more troubleshooting\n\ton the controller.\n\n'''\n\nfrom dronekit import *\nvehicle = connect('/dev/ttyS0', wait_ready=False, baud=921600)\nprint(\"Hello, my name is Grover. The current firmware version is: \")\nprint(vehicle.version)\nprint(vehicle.system_status.state)\nprint(vehicle.armed)\nprint(vehicle.mode)\nprint('done checks')\n\n\ndef take_image():\n\t'''\n\tcontrols the stepper motor going down, the image being taken,\n\tand the stepper coming back up\n\t'''\n\tprint('take image')\n\n\t'''\n\tfrom whiteboard code:\n\twhile switch = LOW\n lower stepper\n stop stepper\n retrieve gps point\n take usb image\n modify exif tag to include gps point\n save to directory\n raise stepper #may need a switch for the top of the stepper\n\n\t'''\n\n\ndef distance_to_current_waypoint():\n \"\"\"\n Gets distance in metres to the current waypoint. \n It returns None for the first waypoint (Home location).\n \"\"\"\n nextwaypoint = vehicle.commands.next\n if nextwaypoint==0:\n return None\n missionitem=vehicle.commands[nextwaypoint-1] #commands are zero indexed\n lat = missionitem.x\n lon = missionitem.y\n alt = missionitem.z\n targetWaypointLocation = LocationGlobalRelative(lat,lon,alt)\n distancetopoint = get_distance_metres(vehicle.location.global_frame, targetWaypointLocation)\n return distancetopoint\n\ndistancetopoint=distance_to_current_waypoint()\nprint('distance to waypoint: ', distancetopoint)\n\n\n\n\nwhile True: \t\t\t\t\t\t\t# starts a perpetual loop any time the vehicle is connected\n\twhile vehicle.mode==VehicleMode(\"AUTO\"): \t# if the vehicle is in auto\n\t\tprint('AUTO')\t\n\t\tdist=distance_to_current_waypoint()\n\t\twhile dist>1 and not dist == None:\n\t\t\tprint('travelling to next waypoint...')\n\t\t\tprint('distance to next waypoint: %f', dist)\n\t\t\ttime.sleep(1)\n\t\t\tdist=distance_to_current_waypoint()\t\n\t\tif dist<1 and not dist == None: \t\t# if the vehicle is less than a meter away from the current WP\n\t\t\tvehicle.mode = VehicleMode(\"HOLD\") \t# put it on hold (on a rover, will stop the vehicle)\n\t\t\ttime.sleep(3) \t\t\t\t# wait for the vehicle to come to a stop (3 seconds)\n\t\t\tprint(vehicle.mode)\n\t\t\tprint('take image')\n\t\t\t#take_image()\n\t\t\tvehicle.mode = VehicleMode(\"AUTO\") \t# put it back in AUTO\n\t\t\tprint(vehicle.mode)\n\t\t\ttime.sleep(15) \t\t\t\t# wait for 15 seconds so the vehicle can exit\n\t\telif dist==None:\n\t\t\tprint('At Home')\n\t\t\ttime.sleep(1)\n\twhile vehicle.mode==VehicleMode(\"MANUAL\"): \t\t# if the vehicle is in MANUAL (remotely operated) mode:\n\t\t#print('MANUAL')\n\t\tif vehicle.channels['5'] < 1750: \t\t\t# if the switch by the H button on the Lightbridge is lowered\n\t\t\tvehicle.mode = VehicleMode(\"HOLD\") \t# put the vehicle in HOLD (on a rover, will stop the vehicle)\n\t\t\ttime.sleep(3)\n\t\t\tprint(vehicle.mode) \t\t\t\t# wait for the vehicle to come to a stop\n\t\t\ttake_image()\n\t\t\tvehicle.mode = VehicleMode(\"MANUAL\")\n\t\t\ttime.sleep(3)\n\t\t\tprint(vehicle.mode)\n\t\ttime.sleep(.5)\n\t\t\t\t\t\t\t\t# ***make sure the switch is immediately put back up after turning down\n\twhile vehicle.mode==VehicleMode(\"HOLD\"):\n\t\tprint('holding')\n\t\ttime.sleep(1)\n\n\n\n\n\n","sub_path":"tests/Main_AlternateVersionsAndTests/Grover_main_controlOnly.py","file_name":"Grover_main_controlOnly.py","file_ext":"py","file_size_in_byte":3886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"320127406","text":"#!/usr/bin/env python\nfrom arduino_driver import ArduinoDriver\n\nimport rospy\nfrom geometry_msgs.msg import Point\n\nclass ArduinoDriverNode:\n __driver = ArduinoDriver()\n\n def __init__(self):\n rospy.init_node('driver', anonymous=False)\n rospy.Subscriber('tracked_coordinates', Point, self.callback)\n\n rospy.loginfo(\"Buscando porta serial no servidor de parametros...\")\n serial_port = rospy.get_param('~serial_port', '/dev/ttyACM0')\n rospy.loginfo(\"Porta: %s\" % serial_port)\n\n rospy.loginfo(\"Abrindo a porta serial...\")\n self.__driver.port = serial_port\n self.__driver.open()\n rospy.loginfo(\"Sucesso!\")\n\n\n\n def spin(self):\n rospy.spin()\n\n def callback(self, point):\n rospy.loginfo(\"recebi ponto: (%d,%d)\" % (point.x, point.y) )\n x_pwm = int( (255/640)*point.x )\n y_pwm = int( (255/480)*point.y )\n\n self.__driver.mov_xservo(x_pwm)\n self.__driver.mov_yservo(y_pwm)\n\n def close(self):\n self.__driver.close()\n\nif __name__ == '__main__':\n try:\n node = ArduinoDriverNode()\n node.spin()\n except rospy.ROSInterruptException:\n node.close()\n pass\n","sub_path":"scripts/arduino.py","file_name":"arduino.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"297965798","text":"#!/usr/bin/env python\n\n\"\"\"Pirograph Image processing\n\nImplemented loading an image from disk, to avoid camera faffing while we try\nto benchmark and performance-tune the image processing.\n\nOn the Mac, 12.9% of execution time is in screen.blit,\n 48.4% in pygame.display.flip()\n\nIf we init the Pygame display with FULLSCREEN | DOUBLEBUF | OPENGL | HWSURFACE,\nthat drops to 28.7% and overall perforamcne is about 50% better. Blimey.\n\n\"\"\"\n\nimport io, time, sys\nimport pygame\nfrom PIL import Image, ImageStat, ImageOps, ImageDraw\nimport numpy as np\nimport os.path\n\nimport multiprocessing # Boomfaster\n\n# Set working frame size. Stick with multiples of 32:\n# eg. 736, 800, 864, 896, 960, 1024, 1056.\n# A good compromise for a 1080-line HD display is 854 px square.\nsize = width, height = 1056, 1056\n\n# Set up some configuration variables\nvideo_framerate = 8\n# Default image processing settings\nthreshold_low = 40\nthreshold_high = 230\n\nframe_count = 1\n\n# Initialise PyGame surface\npygame.init()\npygame.OPENGL = True\n# Toggle next two for faster mode, but without console display (unless shelled in)\nscreen = pygame.display.set_mode(size, 0, 32) \n# screen = pygame.display.set_mode(size, pygame.OPENGL | pygame.FULLSCREEN | pygame.HWSURFACE | pygame.DOUBLEBUF, 32)\nscreen.fill((0, 0, 0))\npygame.display.flip()\n\n# Initialise PIL image to black background\ncomposite = Image.frombytes('RGB', size, \"\\x00\" * width * height * 3)\ncomposite = composite.convert('RGBA')\nraw_str = composite.tobytes(\"raw\", 'RGBA')\npygame.surface = pygame.image.fromstring(raw_str, size, 'RGBA')\n\n# Set up overlay mask image\n# Oversize so it anti-aliases on scaledown\novermask_size = (width * 3, height * 3)\novermask_centre = [ overmask_size[0] / 2 , overmask_size[1] / 2 ]\novermask_radius = overmask_size[0] / 2\n\ndef drawOvermask():\n global overmask\n global overmask_size\n global overmask_radius\n global overmask_centre\n overmask = Image.new('L', overmask_size, 0)\n draw = ImageDraw.Draw(overmask)\n draw.ellipse ( (\n (overmask_centre[0] - overmask_radius),\n (overmask_centre[1] - overmask_radius),\n (overmask_centre[0] + overmask_radius),\n (overmask_centre[1] + overmask_radius) ), fill = 255)\n overmask = overmask.resize(size, Image.ANTIALIAS)\n\n\ndef get_brightness(image):\n \"\"\"Return overall brightness value for image\"\"\"\n stat = ImageStat.Stat(image)\n return stat.rms[0]\n\n\ndef handlePygameEvents():\n global threshold_low\n global threshold_high\n global composite\n global frame_count\n global overmask_size\n global overmask_centre\n global overmask_radius\n for event in pygame.event.get():\n if event.type == pygame.QUIT: sys.exit()\n elif event.type is pygame.KEYDOWN:\n key_press = event.key\n # key_press = pygame.key.name(event.key)\n # print key_press # For diagnostic purposes, but messes up output\n if key_press == pygame.K_e:\n if (threshold_low + 1) < 256:\n threshold_low += 1\n print(\"threshold_low set to %i\" % threshold_low)\n elif key_press == pygame.K_d:\n if (threshold_low - 1) >= 0:\n threshold_low -= 1\n print(\"threshold_low set to %i\" % threshold_low)\n elif key_press == pygame.K_r:\n if (threshold_high + 1) < 256:\n threshold_high += 1\n print(\"threshold_high set to %i\" % threshold_high)\n elif key_press == pygame.K_f:\n if (threshold_high -1) >= 0:\n threshold_high -= 1\n print(\"threshold_high set to %i\" % threshold_high)\n \n # Check for left shift and allow rapid threshold changes\n if pygame.key.get_mods() & pygame.KMOD_LSHIFT:\n if key_press == pygame.K_q:\n sys.exit()\n if key_press == pygame.K_e:\n if (threshold_low + 10) < 256:\n threshold_low += 10\n print(\"threshold_low set to %i\" % threshold_low)\n elif key_press == pygame.K_d:\n if (threshold_low - 10) >= 0:\n threshold_low -= 10\n print(\"threshold_low set to %i\" % threshold_low)\n elif key_press == pygame.K_r:\n if (threshold_high + 10) < 256:\n threshold_high += 10\n print(\"threshold_high set to %i\" % threshold_high)\n elif key_press == pygame.K_f:\n if (threshold_high -10) >= 0:\n threshold_high -= 10\n print(\"threshold_high set to %i\" % threshold_high)\n # Check for SHIFT+P and if found, set working image to pure black again\n elif key_press == pygame.K_p:\n print(\"*** STARTING OVER ***\")\n composite = Image.frombytes('RGB', size, \"\\x00\" * width * height * 3)\n composite = composite.convert('RGBA')\n\n# Set up mask image\ndrawOvermask()\n\n# Note that array size arguments are the other way around to the camera resolution. Just to catch you out.\n# rawCapture = PiRGBArray(camera, size=(height, width))\nthisFrame = Image.open('test_image.jpeg')\n#rawCapture = PiYUVArray(camera, size=(height, width))\n\ntime_begin = time.time()\ntime_start = time.time()\nframe_count = 1\n\n# Work through the stream of images from the camera\n\n@profile\ndef process_frame(frame):\n # frame_new = Image.frombytes('RGB', size, frame.array)\n # frame_yuv = Image.frombytes('yuv', size, frame.array)\n #frame_rgb_array = frame.array\n #frame_rgb_image = Image.fromarray(frame_rgb_array)\n frame_rgb_image = Image.new('RGBA', frame.size)\n frame_rgb_image.paste(frame)\n\n # BEGIN Image processing code \n \n # Create YUV conversion for luminosity mask processing\n #frame_yuv = frame_rgb_image.convert(\"YCbCr\")\n #frame_yuv_array = np.array(frame_yuv)\n #frame_yuv_array = np.array(frame_rgb_image.convert(\"YCbCr\"))\n #frame_y = frame_yuv_array[0:width, 0:height, 0]\n frame_y = np.array(frame_rgb_image.convert(\"YCbCr\"))[0:width, 0:height, 0]\n\n # ***** MASK PROCESSING *****\n # Clip low values to black (transparent)\n # First index the low values...\n low_clip_indices = frame_y < threshold_low\n # ...then set values at those indices to zero\n frame_y[low_clip_indices] = 0\n\n # Clip high values to white (solid)\n # First index the high values...\n high_clip_indices = frame_y > threshold_high\n # ...then set values at those indices to 255\n frame_y[high_clip_indices] = 255\n \n # Make mask image from Numpy array frame_y\n mask = Image.fromarray(frame_y, \"L\")\n \n # ***** COMPOSITE NEW FRAME *****\n # Convert captured frame to RGBA\n frame_rgb_image = frame_rgb_image.convert(\"RGBA\") \n \n return composite, mask\n\nx = 0\ncompImage = Image.new('RGBA', size)\npool = multiprocessing.Pool()\nwhile x in range(50):\n # Do image processing things\n\n compImage, mask = process_frame(thisFrame)\n\n # slap processed frame + alpha mask over rolling composite\n composite.paste(compImage, (0,0), mask)\n\n # Apply overlay mask (round aperture)\n composite.paste(overmask, (0,0), ImageOps.invert(overmask))\n\n # ***** DISPLAY NEW FRAME ***** \n raw_str = compImage.tobytes(\"raw\", 'RGBA')\n pygame_surface = pygame.image.fromstring(raw_str, size, 'RGBA')\n \n # Finally, update the window\n screen.blit(pygame_surface, (0,0))\n pygame.display.flip()\n\n\n # Handle PyGame events (ie. keypress controls)\n handlePygameEvents()\n\n time_taken = time.time() - time_start\n time_since_begin = time.time() - time_begin\n print(\"Frame %d in %.3f secs, at %.2f fps, Low: %d High: %d\" % (frame_count, time_taken, (frame_count/time_since_begin), threshold_low, threshold_high))\n \n time_start = time.time()\n frame_count += 1\n x += 1\n","sub_path":"experiments/pirograph_multiprocess.py","file_name":"pirograph_multiprocess.py","file_ext":"py","file_size_in_byte":7975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"27939326","text":"## outside modules\nimport kivy\nkivy.require('1.11.1')\n\nfrom kivy.app import App\nfrom kivy.uix.button import Button\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.image import Image\nfrom kivy.graphics import Color, Rectangle\nfrom kivy.uix.popup import Popup\nfrom kivy.uix.label import Label\nfrom kivy.core.text import LabelBase\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.filechooser import FileChooserListView, FileChooserIconView\nimport webbrowser\nimport os\n\n\nclass ScoresToplineView(BoxLayout):\n\n def __init__(self, **kwargs):\n super(ScoresToplineView, self).__init__(**kwargs)\n\n self.open_file_prompt = self.create_open_file_prompt()\n self.open_file_dialog = self.create_open_file_dialog()\n self.report_descriptions = self.create_report_descriptions()\n self.save_file_prompt = self.create_save_file_prompt()\n self.save_file_dialog = self.create_save_file_dialog()\n\n self.open_filepath = \"\"\n self.location = \"\"\n self.round = 0\n self.save_filepath = \"\"\n\n def create_report_descriptions(self):\n inputter = BoxLayout(orientation='vertical')\n\n region_layout = BoxLayout()\n region_label = Label(text=\"Reporting region:\")\n region_label.font_family = \"Y2\"\n region_label.size_hint = (1, .3)\n region_label.pos_hint={'center_x': 0.5, 'center_y': 0.3} \n region_input = TextInput(text=\"REGION ABR (ex. MT/NJ-11/PA)\")\n region_input.size_hint = (1, .3)\n region_input.pos_hint={'center_x': 0.5, 'center_y': 0.3}\n region_input.write_tab = False\n\n region_layout.add_widget(region_label)\n region_layout.add_widget(region_input)\n inputter.add_widget(region_layout)\n\n round_layout = BoxLayout()\n round_label = Label(text=\"Round number:\")\n round_label.font_family = \"Y2\"\n round_label.size_hint = (1, .3)\n round_label.pos_hint={'center_x': 0.5, 'center_y': 0.7}\n round_input = TextInput(text=\"#\")\n round_input.size_hint = (1, .3) \n round_input.pos_hint={'center_x': 0.5, 'center_y': 0.7}\n round_input.write_tab = False\n \n round_layout.add_widget(round_label)\n round_layout.add_widget(round_input)\n\n inputter.add_widget(round_layout)\n\n def inputted_details(region, round):\n try:\n self.report_desc_to_open_prompt(region, int(round))\n except:\n self.error_message(\"Error reading round number\")\n\n enter_btn = Button(text=\"Enter\", size_hint=(.2, .3), pos_hint={'center_x': 0.5, 'center_y': 0.5},\n on_press=lambda x: inputted_details(region_input.text, round_input.text))\n\n inputter.add_widget(enter_btn)\n\n detail_inputter = Popup(title='Enter report labelling details',\n content=inputter,\n size_hint=(.7, .5 ), pos_hint={'center_x': 0.5, 'center_y': 0.5})\n\n return detail_inputter\n\n def create_open_file_prompt(self):\n popup_layout = BoxLayout(orientation='vertical')\n help_text = \"Choose scores topline data (.csv) file \\n\\n\"\n help_text += \"[ref=click][color=F3993D]Click here for scores topline data examples[/color][/ref]\"\n\n def examples_link(instance, value):\n webbrowser.open(\"https://www.dropbox.com/sh/39pt0d7mjt7ywlz/AACyIGiGKaifcrHdFJc0fYeEa?dl=0\")\n\n report_label = Label(text=help_text, markup=True)\n report_label.bind(on_ref_press=examples_link)\n report_label.font_family = \"Y2\"\n\n popup_layout.add_widget(report_label)\n\n save_btn = Button(text='>', size_hint=(.2,.2))\n save_btn.pos_hint={'center_x': 0.5, 'center_y': 0.5}\n save_btn.bind(on_release=self.open_file_prompt_to_dialog)\n\n popup_layout.add_widget(save_btn)\n\n popup = Popup(title=\"Select scores data file\",\n content=popup_layout,\n size_hint=(.7, .5), pos_hint={'center_x': 0.5, 'center_y': 0.5})\n\n return popup\n\n def create_open_file_dialog(self):\n chooser = BoxLayout()\n container = BoxLayout(orientation='vertical')\n\n def open_file(path, filename):\n try:\n filepath = os.path.join(path, filename[0])\n self.open_filepath = filepath\n self.open_file_dialog_to_save_prompt()\n except IndexError:\n self.error_message(\"Please pick a scores topline data (.csv) file\")\n\n filechooser = FileChooserListView()\n filechooser.path = os.path.expanduser(\"~\")\n filechooser.bind(on_selection=lambda x: filechooser.selection)\n filechooser.filters = [\"*.csv\"]\n\n open_btn = Button(text='open', size_hint=(.2,.1), pos_hint={'center_x': 0.5, 'center_y': 0.5})\n open_btn.bind(on_release=lambda x: open_file(filechooser.path, filechooser.selection))\n\n container.add_widget(filechooser)\n container.add_widget(open_btn)\n chooser.add_widget(container)\n\n file_chooser = Popup(title='Open file',\n content=chooser,\n size_hint=(.9, .7 ), pos_hint={'center_x': 0.5, 'center_y': 0.5})\n\n return file_chooser \n\n def create_save_file_prompt(self):\n popup_layout = BoxLayout(orientation='vertical')\n label = Label(text=\"Choose a file location and name for scores topline report\")\n label.font_family= \"Y2\"\n\n popup_layout.add_widget(label)\n\n save_btn = Button(text='>', size_hint=(.2,.2))\n save_btn.pos_hint={'center_x': 0.5, 'center_y': 0.5}\n save_btn.bind(on_release=self.save_file_prompt_to_dialog)\n\n popup_layout.add_widget(save_btn)\n\n popup = Popup(title=\"Select save file location\",\n content=popup_layout,\n size_hint=(.7, .5), pos_hint={'center_x': 0.5, 'center_y': 0.5})\n\n return popup\n\n def create_save_file_dialog(self):\n chooser = BoxLayout()\n container = BoxLayout(orientation='vertical')\n\n filechooser = FileChooserIconView()\n filechooser.path = os.path.expanduser(\"~\")\n\n container.add_widget(filechooser)\n\n def save_file(path, filename):\n filepath = os.path.join(path, filename)\n path, ext = os.path.splitext(filepath)\n if ext != \".xlsx\":\n filepath += \".xlsx\"\n self.save_filepath = filepath\n self.finish()\n\n button_layout = BoxLayout()\n button_layout.size_hint = (1, .1)\n\n file_name = TextInput(text=\"File name.xlsx\")\n button_layout.add_widget(file_name)\n\n save_btn = Button(text='save', size_hint=(.2,1))\n save_btn.bind(on_release=lambda x: save_file(filechooser.path, file_name.text))\n\n button_layout.add_widget(save_btn)\n container.add_widget(button_layout)\n chooser.add_widget(container)\n\n file_chooser = Popup(title='Save report',\n content=chooser,\n size_hint=(.9, .7 ), pos_hint={'center_x': 0.5, 'center_y': 0.5})\n\n return file_chooser\n\n def run(self, controller):\n self.__controller = controller\n self.report_descriptions.open()\n\n def report_desc_to_open_prompt(self, region, round):\n self.region = region\n self.round = round\n self.report_descriptions.dismiss()\n self.open_file_prompt.open()\n\n def open_file_prompt_to_dialog(self, instance):\n self.open_file_prompt.dismiss()\n self.open_file_dialog.open()\n\n def open_file_dialog_to_save_prompt(self):\n try:\n self.__controller.build_scores_model(self.open_filepath, self.round, self.region)\n self.open_file_dialog.dismiss()\n self.save_file_prompt.open()\n except:\n self.error_message(\"Error reading data file\") \n\n def save_file_prompt_to_dialog(self, instance):\n self.save_file_prompt.dismiss()\n self.save_file_dialog.open()\n\n def finish(self):\n try:\n self.__controller.build_scores_report(self.save_filepath)\n self.save_file_dialog.dismiss()\n except:\n self.error_message(\"Issue formatting report\")\n\n def error_message(self, error):\n label = Label(text=error)\n label.font_family= \"Y2\"\n\n popup = Popup(title=\"Something Went Wrong\",\n content=label,\n size_hint=(.5, .8), pos_hint={'center_x': 0.5, 'center_y': 0.5})\n\n popup.open()\n","sub_path":"internbot/view/rnc_view/scores_topline_view.py","file_name":"scores_topline_view.py","file_ext":"py","file_size_in_byte":8346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"403559709","text":"from collections import defaultdict, deque\n\n\ndef topological_sort(feeddict):\n nodes = [node for node in feeddict.keys()]\n in_count = defaultdict(int)\n out_edges = defaultdict(list)\n for node in nodes:\n for out in node.outbound_nodes:\n in_count[out] += 1\n out_edges[node].append(out)\n\n queue = deque([node for node in in_count.keys() if in_count[node]==0])\n res = []\n while(queue):\n cur = queue.popleft()\n res.append(cur)\n for i in out_edges[cur]:\n in_count[i] -= 1\n if in_count[i]==0:\n queue.append(cur)\n\n return res\n\n\ndef forward_and_backward(graph):\n for n in graph:\n n.forward()\n\n\n for n in graph[::-1]:\n n.backward()\n\n\ndef gradient_descent_update(x, gradx, learning_rate):\n x = x - learning_rate*gradx\n return x\n\n\ndef sgd(trainables, learning_rate=0.01):\n for t in trainables:\n t.value -= learning_rate*t.gradients[t]\n","sub_path":"miniflow/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"257077745","text":"#!/usr/bin/env python3\n\nimport RPi.GPIO as GPIO\nimport time\nimport schedule\nfrom influxdb import InfluxDBClient\n\nfrom batchCollector import BatchCollector\nfrom timer import Timer\n\n# ------------------------------------------------------\n# Influx cfg\nUSER = 'root'\nPASSWORD = 'root'\nDBNAME = 'test'\nHOST = 'localhost'\nPORT = 8086\n\n# defines\nVERBOSE = False\nPULSE_IO_NBR = 20\nLED_IO_NBR = 21\nPULSE_DEBOUNCE_ms = 5\nDB_LOG_INTERVAL_minutes = 1\nPULSE_LEN_MIN_s = 0.015\nPULSE_LEN_MAX_s = 0.15\n\n# Global\ntmr = Timer()\npulseStat = BatchCollector()\npoints = []\n# ------------------------------------------------------\n# Callback for writing data to database\ndef log_to_db():\n global pulseStat, points\n\n # Sample pulse counter\n pulseStat.sampleAndReset()\n cnt = pulseStat.getCnt()\n print(\"(#{:d}, mean:{:.4f}s, min:{:.4f} max:{:.4f})\".format(cnt, pulseStat.getMean(), pulseStat.getMin(), pulseStat.getMax()))\n\n # Insert into db\n point = {\n \"measurement\": 'PulseCnt',\n \"tags\": {\n \"location\": \"home\",\n \"sensor\": \"p.1\",\n \"resolution\": \"10000\",\n \"batch_length_s\": \"60\" \n },\n \"fields\": {\n \"value\": cnt,\n \"pulse_mean\": pulseStat.getMean(),\n \"pulse_min\": pulseStat.getMin(),\n \"pulse_max\": pulseStat.getMax(),\n \"pulse_stdSqr\": pulseStat.getStdSqr()\n }\n }\n points.append(point)\n client = InfluxDBClient(HOST, PORT, USER, PASSWORD, DBNAME)\n\n if(client.write_points(points)):\n points = []\n if VERBOSE:\n print(\"Inserting into influxdb, cnt: {}\".format(cnt))\n else:\n \t# failure, keep the pulses and try again next time\n print(\"Warning: failed inserting {} pulses into influxdb\".format(cnt))\n\n# ------------------------------------------------------\n# Callback function to run in another thread when edges are detected\ndef edge_cb(channel):\n global pulseStat, tmr\n\n pulseLen = 0\n timeSinceLast = 0\n PulseDetected = False\n\n if GPIO.input(PULSE_IO_NBR):\n pulseLen = tmr.sampleAndReset()\n if(pulseLen > PULSE_LEN_MIN_s and pulseLen < PULSE_LEN_MAX_s):\n PulseDetected = True\n else:\n timeSinceLast = tmr.sampleAndReset()\n if VERBOSE:\n print(\"\\n{}, tp {}\".format(pulseStat.getCntNow(), timeSinceLast))\n\n if PulseDetected:\n if VERBOSE:\n print(\"{}, len {}\".format(pulseStat.getCntNow(), pulseLen))\n\n pulseStat.add(pulseLen)\n print(\".\", end=\"\", flush=True)\n\n # New pulse detected, toggle the led\n if GPIO.input(LED_IO_NBR):\n GPIO.output(LED_IO_NBR, GPIO.LOW)\n else:\n GPIO.output(LED_IO_NBR,GPIO.HIGH)\n else:\n if pulseLen > 0:\n print(\"Pulse discarded, len {}\".format(pulseLen))\n\n# ------------------------------------------------------\n# Setup\nGPIO.setmode(GPIO.BCM) # set up BCM GPIO numbering\nGPIO.setwarnings(True)\n\n# Setup pulse input with pull up and connect callback on all edges\nGPIO.setup(PULSE_IO_NBR, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.add_event_detect(PULSE_IO_NBR, GPIO.BOTH, callback=edge_cb, bouncetime=PULSE_DEBOUNCE_ms)\n\n# Led output\nGPIO.setup(LED_IO_NBR,GPIO.OUT)\n\n# Schedule logging of pulse counter value\nschedule.every(DB_LOG_INTERVAL_minutes).minutes.do(log_to_db)\n\n# ------------------------------------------------------\n# Run forever\ntry:\n while True:\n \tschedule.run_pending()\n time.sleep(1)\nfinally:\n GPIO.cleanup() # clean up \n","sub_path":"pulseCounter.py","file_name":"pulseCounter.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"204445159","text":"import asyncio\nimport logging\n\nfrom aiohttp import web\n\nfrom servicelib.application_keys import APP_CONFIG_KEY\nfrom servicelib.application_setup import ModuleCategory, app_module_setup\nfrom servicelib.rest_routing import (\n get_handlers_from_namespace,\n iter_path_operations,\n map_handlers_with_operations,\n)\n\nfrom ..rest_config import APP_OPENAPI_SPECS_KEY\nfrom . import handlers\nfrom .config import CONFIG_SECTION_NAME\n\nlogger = logging.getLogger(__name__)\n\n\n@app_module_setup(\n __name__,\n category=ModuleCategory.ADDON,\n depends=[\"simcore_service_webserver.rest\"],\n logger=logger,\n)\ndef setup(app: web.Application):\n\n # setup routes ------------\n specs = app[APP_OPENAPI_SPECS_KEY]\n\n def include_path(tup_object):\n _method, path, _operation_id, _tags = tup_object\n return any(tail in path for tail in [\"/activity/status\"])\n\n handlers_dict = {\"get_status\": handlers.get_status}\n\n routes = map_handlers_with_operations(\n handlers_dict, filter(include_path, iter_path_operations(specs)), strict=True\n )\n app.router.add_routes(routes)\n\n\n# alias\nsetup_activity = setup\n\n__all__ = \"setup_activity\"\n","sub_path":"services/web/server/src/simcore_service_webserver/activity/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"521148689","text":"from django.db import models\n\nfrom edc_base.audit_trail import AuditTrail\nfrom edc_base.model.fields import OtherCharField\nfrom edc_base.model.validators import date_not_future\n\nfrom bhp066.apps.bcpp.choices import DXTB_CHOICE\n\nfrom .base_scheduled_visit_model import BaseScheduledVisitModel\nfrom .subject_consent import SubjectConsent\n\n\nclass Tubercolosis (BaseScheduledVisitModel):\n\n \"\"\"A model completed by the user to record any diagnosis of\n Tuberculosis in the past 12 months.\"\"\"\n\n CONSENT_MODEL = SubjectConsent\n\n date_tb = models.DateField(\n verbose_name=\"Date of the diagnosis of tuberculosis:\",\n validators=[date_not_future],\n help_text=\"\",\n )\n\n dx_tb = models.CharField(\n verbose_name=\"[Interviewer:]What is the tuberculosis diagnosis as recorded?\",\n max_length=50,\n choices=DXTB_CHOICE,\n help_text=\"\",\n )\n dx_tb_other = OtherCharField(\n null=True,\n )\n\n history = AuditTrail()\n\n class Meta:\n app_label = 'bcpp_subject'\n verbose_name = \"Tubercolosis\"\n verbose_name_plural = \"Tubercolosis\"\n","sub_path":"bhp066/apps/bcpp_subject/models/tubercolosis.py","file_name":"tubercolosis.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"561457538","text":"#!/usr/bin/env python3\n# built-in {{{\nimport re\nimport sys\nimport logging\n# }}}\n# {{{\nimport requests\nfrom pyhocon import ConfigFactory\nfrom lxml.html import fromstring, tostring, document_fromstring\n# }}}\n\nDEFAULT_SONG_ID = 'twy100012x69x11' # 五月天 - 成名在望\n\ndef remove_BOM(s):# {{{\n \"\"\"\n 移除在 htm 檔案開頭的 \\ufeff,這個字元在 編輯器上是看不到的。\n \"\"\"\n if u'\\ufeff' in s:\n logging.info('✔ | Byte Order Mark is removed ...')\n return s.replace(u'\\ufeff', '')\n# }}}\n\ndef remove_ads(obj):# {{{\n \"\"\"\n 因為 \"更多更詳盡歌詞 在 ※ Mojim.com 魔鏡歌詞網\" 這個字串的後半部是個 tag,因此選擇在 處理 dom 元件時就替代掉,以方便後續處理。\n \"\"\"\n ads = obj.xpath('//a[@href=\"http://mojim.com\"]')\n ols = obj.xpath('//ol')\n\n for ad in ads:\n obj.remove(ad)\n logging.info('✔ | 移除廣告')\n for ol in ols:\n obj.remove(ol)\n logging.info('✔ | 移除感謝詞')\n\n return obj\n# }}}\n\ndef config():# {{{\n hocon = ConfigFactory.parse_file('config/config.conf')\n return hocon\n# }}}\n\n\nif '__main__' == __name__:\n # User input {{{\n try:\n song_id = sys.argv[1]\n except:\n song_id = DEFAULT_SONG_ID\n # }}}\n\n # logginhg config {{{\n conf = config()\n logging.basicConfig(\n level=logging.INFO,\n format=conf.logging['format_string'],\n datefmt=conff.logging['date_format_string'],\n handlers=[\n logging.FileHandler(F\"log/{song_id}.log\"),\n logging.StreamHandler()\n ])\n # }}}\n\n # lyrics url\n url = F\"https://mojim.com/{song_id}.htm\"\n raw_html = requests.get(url).text # utf-8 encoding\n # Process raw html\n html = remove_BOM(raw_html)\n\n # Turn html into element tree\n root = fromstring(html)\n\n # Get lyrics
\n element_lyrics = root.get_element_by_id('fsZx3')\n element_lyrics = remove_ads(element_lyrics)\n # Get title
\n element_title = root.get_element_by_id('fsZx2')\n title = element_title.text\n logging.info(F\"✔ | 歌名:{title}\")\n\n # 將 lyrics div object 轉成 string\n lyrics_div_string = tostring(element_lyrics, encoding='unicode')\n\n # Filter\n # 由於 lyrics div 中,有以下幾種資訊\n # 1. 歌曲資訊\n # - 作詞 (author)\n # - 作曲 (composer)\n # - 編曲 (arranger) --> 不一定會有\n\n # 2. 在歌曲資訊前,可能會出現專輯相關的字串,因此必須判斷是否為歌詞\n # - [ ] is_lyrics\n\n lyrics = []\n lyrics_with_track = []\n is_lyric = False\n\n author = ''\n composer = ''\n arranger = ''\n\n for s in lyrics_div_string.split('
'):\n if '作詞' in s:\n author = s.replace('作詞:', '')\n logging.info(F\"✔ | 作詞:{author}\")\n is_lyric = True\n continue\n if '作曲' in s:\n composer = s.replace('作曲:', '')\n logging.info(F\"✔ | 作曲:{composer}\")\n continue\n if '編曲' in s:\n arranger = s.replace('編曲:', '')\n logging.info(F\"✔ | ��曲:{arranger}\")\n continue\n if not is_lyric: continue\n if '更多更詳盡歌詞 在' in s:\n logging.info('✔ | 移除\"更多更詳盡歌詞\"')\n continue\n if not s: continue\n if any(re.match(regex, s) for regex in [r'']): continue\n\n\n\n # 區分有無時間軌\n if re.match(r'\\[\\d+:\\d+.\\d+\\].*', s):\n lyrics_with_track.append(s)\n else:\n lyrics.append(s)\n\n # Write file\n path = 'tmp/lyrics'\n with open(F\"{path}/{song_id}_{title}.txt\", 'w+') as f:\n f.write(F\"title : {title}\\n\")\n f.write(F\"author : {author}\\n\")\n f.write(F\"composer : {composer}\\n\")\n f.write(F\"arranger : {arranger}\\n\")\n f.write('\\n')\n for line in lyrics:\n f.write(line + '\\n')\n logging.info(F\"✔ | 歌詞存檔(無時間軌) | {path} | {song_id}_{title}.txt\")\n if lyrics_with_track:\n with open(F\"{path}/{song_id}_track_{title}.txt\", 'w+') as f:\n f.write(F\"song_name : {title}\\n\")\n f.write(F\"author : {author}\\n\")\n f.write(F\"composer : {composer}\\n\")\n f.write(F\"arranger : {arranger}\\n\")\n f.write('\\n')\n for line in lyrics:\n f.write(line + '\\n')\n logging.info(F\"✔ | 歌詞存檔(有時間軌) | {path} | {song_id}_track_{title}.txt\")\n\n # End of experiment\n logging.info(\"Complete\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"481086690","text":"from .userprefs import UserPrefs\nfrom ..necrodb import NecroDB\n\n\nclass PrefsManager(object):\n def __init__(self, necrobot):\n self.necrobot = necrobot\n\n def refresh(self):\n pass\n\n def close(self):\n pass\n\n def set_prefs(self, user_prefs, user):\n prefs = self.get_prefs(user)\n prefs.merge_prefs(user_prefs)\n\n params = (int(user.id), False, 2 if prefs.daily_alert else 0, 1 if prefs.race_alert else 0,)\n print(params)\n NecroDB().set_prefs(params)\n\n @staticmethod\n def get_prefs(user):\n user_prefs = UserPrefs()\n params = (int(user.id),)\n for row in NecroDB().get_prefs(params):\n user_prefs.daily_alert = (row[2] != 0)\n user_prefs.race_alert = (row[3] != 0)\n return user_prefs\n\n # get all user id's matching the given user prefs\n def get_all_matching(self, user_prefs):\n users_matching_dailyalert = []\n users_matching_racealert = []\n lists_to_use = []\n\n if user_prefs.daily_alert is not None:\n lists_to_use.append(users_matching_dailyalert)\n params = (2,) if user_prefs.daily_alert else (0,)\n\n for row in NecroDB().get_all_matching_prefs(\"dailyalert\", params):\n userid = row[0]\n for member in self.necrobot.server.members:\n if int(member.id) == int(userid):\n users_matching_dailyalert.append(member)\n\n if user_prefs.race_alert is not None:\n lists_to_use.append(users_matching_racealert)\n params = (1,) if user_prefs.race_alert else (0,)\n\n for row in NecroDB().get_all_matching_prefs(\"racealert\", params):\n userid = row[0]\n for member in self.necrobot.server.members:\n if int(member.id) == int(userid):\n users_matching_racealert.append(member)\n\n users_matching = []\n if lists_to_use:\n for member in lists_to_use[0]:\n in_intersection = True\n for l in lists_to_use:\n if member not in l:\n in_intersection = False\n if in_intersection:\n users_matching.append(member)\n\n return users_matching\n","sub_path":"necrobot/prefs/prefsmanager.py","file_name":"prefsmanager.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"537707607","text":"import argparse\nimport os\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import TimeSeriesSplit\n\nfrom features import lag_all_stores, add_lags_to_single_store, add_sales_per_customer, add_datetime_features_day_of_week, add_datetime_features_week, mean_encode, identify_competition_and_promo_start_date, identify_whether_promo2_or_competition_running\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--data', default='local', nargs='?')\n parser.add_argument('--cpu', default=8, nargs='?')\n args = parser.parse_args()\n\n validation_sets = 3\n max_train_size = 0.95\n\n store = pd.read_csv('data/raw/store.csv')\n train = pd.read_csv('data/raw/train.csv')\n print('train shape {}'.format(train.shape))\n\n for i, store_number in enumerate(train.Store):\n if pd.isna(store_number) == True:\n if np.absolute(train.loc[i-1, 'Store'] - train.loc[i+1, 'Store']) == 2:\n train.loc[i, 'Store'] = (train.loc[i-1, 'Store'] + train.loc[i+1, 'Store'] / 2)\n\n data = train[~train['Store'].isna()]\n assert sum(data.loc[:, 'Store'].isnull()) == 0\n print('train shape {}'.format(data.shape))\n\n data = add_sales_per_customer(data, data)\n\n print('Adding promo and competition start dates')\n store = identify_competition_and_promo_start_date(store)\n\n # why merge with stores here?\n data = data.merge(store, how='left', left_on='Store', right_on='Store')\n data = data.sort_values(by=['Date','Store'], ascending=['True','True']).reset_index(drop=True)\n\n data['Date'] = pd.to_datetime(data['Date'])\n data['DayOfWeek'] = data['Date'].dt.dayofweek\n\n print('Filling customer and sales nulls with store / day of week mean')\n data['Customers'] = data.groupby(['Store','DayOfWeek'])['Customers'].transform(lambda x: x.fillna(x.mean()))\n data['Customers'] = data.groupby(['Store'])['Customers'].transform(lambda x: x.fillna(x.mean()))\n data['Customers'] = data['Customers'].transform(lambda x: x.fillna(x.mean()))\n data['Sales'] = data.groupby(['Store','DayOfWeek'])['Sales'].transform(lambda x: x.fillna(x.mean()))\n data['Sales'] = data.groupby(['Store'])['Sales'].transform(lambda x: x.fillna(x.mean()))\n print('Nulls after filling:')\n print('Customers {}'.format(data.Customers.isna().sum()))\n print('Sales {}'.format(data.Sales.isna().sum()))\n\n assert sum(data.loc[:, 'Store'].isnull()) == 0\n data = mean_encode(data, col='Store', on='Sales')\n assert sum(data.loc[:, 'Store'].isnull()) == 0\n\n cleanup = {\n \"StateHoliday\": {'0': 0, 'a': 1, 'b': 2, 'c': 3},\n \"Assortment\": {'a': 0, 'b': 1, 'c': 2},\n \"StoreType\": {'a': 0, 'b': 1, 'c': 2, 'd': 3}\n }\n data.replace(cleanup, inplace=True)\n\n print('Identifying whether promo2 or competition running on a day')\n data = identify_whether_promo2_or_competition_running(data)\n\n data = data.drop(['DayOfWeek', 'PromoInterval', 'promoMonths', 'month_test'], axis=1)\n # data = add_datetime_features_day_of_week(data)\n # data = add_datetime_features_week(data)\n data.loc[:, 'month'] = data.loc[:, 'Date'].dt.month\n data.loc[:, 'week'] = data.loc[:, 'Date'].dt.week\n data.loc[:, 'day-of-week'] = data.loc[:, 'Date'].dt.dayofweek\n assert sum(data.loc[:, 'Store'].isnull()) == 0\n\n # drop zero target\n print('dropping target')\n print('train shape before drop of zero sales {}'.format(data.shape))\n mask = data.loc[:, 'Sales'] != 0\n data = data.loc[mask, :]\n data = data.dropna(subset=['Sales'], axis=0)\n print('train shape after drop of zero sales {}'.format(data.shape))\n\n fill_with_token = ['StateHoliday', 'SchoolHoliday']\n for tok in fill_with_token:\n data.loc[:, tok] = data.loc[:, tok].fillna(0)\n assert sum(data.loc[:, tok].isnull()) == 0\n\n print('filling in comp distances from store info')\n fill_with_store = ['CompetitionDistance', 'CompetitionOpenSinceYear', 'Promo', 'Assortment', 'StoreType']\n\n for tok in fill_with_store:\n print('filling {} with store median'.format(tok))\n data.loc[:, tok] = data.groupby('Store').transform(lambda x: x.fillna(x.median()))\n\n for tok in fill_with_store:\n data.loc[:, tok].fillna(data.loc[:, tok].median(), inplace=True)\n\n assert sum(data.loc[:, 'Store'].isnull()) == 0\n for col in data.columns:\n print(col, ' - ', sum(data.loc[:, col].isnull()))\n\n old_cols = data.columns\n data = data.dropna(axis=1)\n new_cols = data.columns\n print('dropping {} columns due to nulls'.format(len(old_cols) - len(new_cols)))\n print('those cols are {}'.format(set(old_cols).difference(set(new_cols))))\n print('train shape after drop {}'.format(data.shape))\n\n print(' ')\n print('data shape before split {}'.format(data.shape))\n print(data.loc[:, 'Date'].iloc[0], data.loc[:, 'Date'].iloc[-1])\n\n assert(sum(data.loc[:, 'Sales'] == 0)) == 0\n\n lag_column = 'Sales'\n lags = 2\n # hack because lags need the date\n # maybe best to do lags first - not a big deal\n data2 = lag_all_stores(data, lag_column, lags)\n # need to rename to get the drop to work in split_dataset\n data2 = data2.rename({'Sales-lag-0': 'Sales'}, axis=1)\n data2 = data2.dropna(subset=['Sales-lag-1','Sales-lag-2'], axis=0).reset_index(drop=True)\n\n data = data.drop('Date', axis=1)\n data2 = data2.drop('Date', axis=1)\n\n def split_dataset(data, base, validation_sets):\n data = data.copy()\n print('starting {}'.format(base))\n # tscv = TimeSeriesSplit(max_train_size=round(max_train_size*data.shape[0]), n_splits=validation_sets)\n tscv = TimeSeriesSplit(n_splits=validation_sets)\n for fold, (train_index, test_index) in enumerate(tscv.split(data)):\n fold_name = 'fold' + str(fold)\n os.makedirs(base + fold_name, exist_ok=True)\n\n data.iloc[train_index,:].drop('Sales',axis=1).to_csv(base + fold_name + '/' + 'train_X.csv', index=False)\n data.iloc[train_index,:]['Sales'].to_csv(base + fold_name + '/' + 'train_y.csv', index=False, header=True)\n data.iloc[test_index,:].drop('Sales',axis=1).to_csv(base + fold_name + '/' + 'test_X.csv', index=False)\n data.iloc[test_index,:]['Sales'].to_csv(base + fold_name + '/' + 'test_y.csv', index=False, header=True)\n print('done for {}'.format(base))\n\n split_dataset(data, 'data/scenario_1_control/', validation_sets)\n split_dataset(data2, 'data/scenario_2_lags/', validation_sets)\n split_dataset(data, 'data/scenario_3_pred/', validation_sets)\n","sub_path":"clean.py","file_name":"clean.py","file_ext":"py","file_size_in_byte":6628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"522020255","text":"import os\n\nnewdir = \"python_test\"\ncurrentdir = os.getcwd()\nprint(\"列出目前工作資料夾:\",currentdir)\n\n# 如果newdir資料夾不存在,就新建一個\nif os.path.exists(newdir):\n print(\"%s資料夾已存在\" % newdir)\nelse:\n os.mkdir(newdir)\n print(\"建立%s資料夾成功\" % newdir)\n\n# 將目前的工作資料夾改至newdir\nos.chdir(newdir)\nprint(\"列出最新工作資料夾:\", os.getcwd())\n\n# 將目前工作資料夾返回\nos.chdir(currentdir)\nprint(\"列出返回工作資料夾\", currentdir)\n\n","sub_path":"file/ch14_8.py","file_name":"ch14_8.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"398470791","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 20 14:17:19 2020\n\n@author: Bareq\neffective image splcing detection based on image chroma\n\"\"\"\nimport multiprocessing\nimport os\nimport time\nimport skimage.feature as feature\nimport csv\nfrom PIL import Image\nfrom skimage.feature import greycoprops\nimport numpy as np\n\nthreshold = 10\nlevel = threshold + 1\nband = 'cb'\ndef read(path):\n img = Image.open(path)\n return img.convert('YCbCr')\n\ndef GLCM(image, angle):\n glcm = feature.greycomatrix(image, distances=[1], angles=[angle], levels=level, symmetric=False, normed=True) \n contrast = greycoprops(glcm, 'contrast')\n dissimilarity = greycoprops(glcm, 'dissimilarity')\n homogeneity = greycoprops(glcm, 'homogeneity')\n correlation=greycoprops(glcm, 'correlation') \n energy=greycoprops(glcm, 'energy')\n ASM=greycoprops(glcm, 'ASM')\n glcmpros = [contrast.item() ,dissimilarity.item(),homogeneity.item(),energy.item(),correlation.item(),ASM.item()]\n args = (np.array(glcm[:, :, 0, 0]).flatten(),glcmpros)\n x = np.concatenate(args)\n return x\n\n\n\ndef extract_features(image, label):\n (y, cb, cr) = image.split()\n arr = np.array(cb)\n \n Harr = np.clip(np.abs(arr[:,:-1].astype(np.int16) -arr[:,1:].astype(np.int16)),0,threshold)\n Varr = np.clip(np.abs(arr[:-1,:].astype(np.int16) -arr[1:,:].astype(np.int16)),0,threshold)\n Darr = np.clip(np.abs(arr[:-1,:-1].astype(np.int16)-arr[1:,1:].astype(np.int16)),0,threshold)\n Marr = np.clip(np.abs(arr[:-1,1:].astype(np.int16) -arr[1:,:-1].astype(np.int16)),0,threshold)\n \n Cmh = GLCM(Harr, 0)\n Cmv = GLCM(Varr, 90)\n Cmd = GLCM(Darr, 45)\n Cmm = GLCM(Marr, -45)\n\n args = (Cmh,Cmv,Cmd,Cmm)\n\n FeatureVector = np.concatenate(args)\n FeatureVector = np.array(FeatureVector).tolist()\n FeatureVector.append(label)\n\n return FeatureVector\n\ndef getPersantage (iteration, total):\n return 100 * (iteration / float(total))\n\n\ndef work(index, filename, totalfiles, path, label):\n start = time.perf_counter()\n\n result = 0\n try:\n image = read(os.path.join(path, filename))\n result = extract_features(image, label)\n except:\n print(f\"error in: {filename}\")\n\n finish = time.perf_counter()\n\n current_time = time.strftime(\"%H:%M:%S\", time.localtime())\n print(f'[{current_time}] '\n f'{filename} done in: {round((finish - start), 2): <5} seconds '\n f'{round(getPersantage(index, totalfiles), 2): 6}% of {label}')\n\n return result\n\n\nif __name__ == \"__main__\":\n \n cores = os.cpu_count()\n path = 'F:/casia1sp'\n list = os.listdir(path)\n totalFiles1 = len(list)\n label1 = 'unknown'\n\n start = time.perf_counter()\n\n results = []\n with multiprocessing.Pool(processes=cores) as pool:\n for index, name in enumerate(list, start=1):\n results.append(pool.apply_async(work, args=(index, name, totalFiles1, path, label1)))\n results = [result.get() for result in results]\n\n finish = time.perf_counter()\n time1 = round((finish - start)/60, 2)\n print(f'\\nAuthentic total time: {time1} minutes')\n with open('f:/test.csv', 'w', newline='') as myfile:\n wr = csv.writer(myfile, dialect='excel')\n wr.writerows(results)\n myfile.close()\n '''\n###################################################################################\n path = 'F:/Research/DataSets/CASIA2/Tp'\n list = os.listdir(path)\n totalFiles2 = len(list)\n\n start = time.perf_counter()\n label2 = '1'\n results = []\n with multiprocessing.Pool(processes=cores) as pool:\n for index, name in enumerate(list, start=1):\n results.append(pool.apply_async(work, args=(index, name, totalFiles2, path, label2)))\n\n results = [result.get() for result in results]\n\n finish = time.perf_counter()\n time2 = round((finish - start)/60, 2)\n print(f'\\nspliced total time: {time2} minutes')\n\n with open('f:/casia2 CB12.csv', 'a', newline='') as myfile:\n wr = csv.writer(myfile, dialect='excel')\n wr.writerows(results)\n myfile.close()\n\n # print(f\"\\nFinished {totalFiles1} images as {label1} in {time1} minutes\"\n # f\"\\n and {totalFiles2} images as {label2} in {time2} minutes\\n\\n\")\n\n '''","sub_path":"chroma - prediction.py","file_name":"chroma - prediction.py","file_ext":"py","file_size_in_byte":4236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"366572634","text":"from django.db import models\nfrom datetime import *\n\n# Create your models here.\n# Работа с Базами Данных\n\nclass Category(models.Model):\n name = models.CharField(max_length=255, verbose_name='Название категории') # строка\n alias = models.SlugField(verbose_name='Псевдоним категории')\n\n class Meta: # описание в админке\n verbose_name = 'Категория'\n verbose_name_plural = 'Категории'\n\n def __str__(self):\n return 'Категория %s' % self.name\n\n\nclass Item(models.Model):\n name = models.CharField(max_length=255, verbose_name='Название товара') # строка\n price = models.IntegerField(default=0, verbose_name='Цена товара') # integer\n image = models.CharField(max_length=255, verbose_name='Путь к изображению') # integer\n alias = models.SlugField(verbose_name='Псевдоним товара')\n description = models.CharField(max_length=255, verbose_name='Описание товара')\n\n category = models.ForeignKey(Category) # ссылаемся на категорию\n\n class Meta: # описание в админке\n verbose_name = 'Товар'\n verbose_name_plural = 'Товары'\n\n def __str__(self):\n return 'Товар %s' % self.name","sub_path":"main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"636501409","text":"import json\nimport traceback\nimport requests\nimport re\nimport datetime\nfrom bs4 import BeautifulSoup\nfrom pymongo import MongoClient\n\n'''\nClass to scrap the economic time data\n'''\n\nclass EconomicScrapper(object):\n \n def __init__(self):\n with open(\"./config.json\", \"r\") as fp:\n self.config_dct = json.load(fp)\n try:\n self.client = MongoClient('localhost', 27017)\n print (\"connected to mongodb\")\n except Exception as e:\n print (\"exception occured while connecting to database\",e)\n # db = self.client.scrap_econo\n \n '''\n Main crawler function\n '''\n def crawler(self):\n result = {}\n try:\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36\"\n }\n result_content = requests.get(self.config_dct[\"target_url\"], headers= headers, proxies = self.config_dct[\"proxy_config\"], timeout = 5 )\n if result_content.status_code == 200:\n if result_content.content:\n crawled_data = result_content.content\n rgex_search = re.search(b'ajaxResponse\\((.*)\\)(\\r)?(\\n)?', crawled_data)\n if rgex_search:\n result = json.loads(rgex_search.group(1))\n # print json.dumps(result, indent=3)\n else:\n print (\"Data is blank.\")\n else:\n print (\"*\"*50, \" Site is blocking the crawling activity. Hit again.\\n Error Code\", result_content.status_code, \"*\"*50)\n \n except Exception as e:\n print (\"Exception in crawler for crawling: \", e)\n return result\n\n\n \n def crawlerNseBse(self,co_id):\n result = {}\n try:\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36\"\n }\n result_content = requests.get(\"https://json.bselivefeeds.indiatimes.com/ET_Community/companypagedata?companyid=\"+str(co_id)+\"&companytype=&callback=ets.hitMarket\",\n headers= headers, proxies = self.config_dct[\"proxy_config\"], timeout = 5 )\n if result_content.status_code == 200:\n if result_content.content:\n crawled_data = result_content.content\n rgex_search = re.search(b'ets.hitMarket\\((.*)\\)(\\r)?(\\n)?', crawled_data)\n if rgex_search:\n result = json.loads(rgex_search.group(1))\n # print json.dumps(result, indent=3)\n else:\n print (\"Data is blank.\")\n else:\n print (\"*\"*50, \" Site is blocking the crawling activity. Hit again.\\n Error Code\", result_content.status_code, \"*\"*50)\n \n except Exception as e:\n print (\"Exception in crawler for crawling: \", e)\n # print result\n return result\n\n\n '''\n Dump in mongodb\n '''\n def dump_db(self, data_to_dump):\n companyId = []\n db_name = self.config_dct[\"db_name\"]\n db_ref = self.client[db_name]\n collection = db_ref[\"historic_data\"]\n data_to_insert = {}\n try:\n if data_to_dump:\n for items in data_to_dump['searchresult']:\n data_to_insert = items\n co_id = items['companyid']\n date_str = items['xdividenddatestr'].strip()\n format_str = '%d-%m-%Y'\n dividendDate = datetime.datetime.strptime(date_str,format_str) \n # print co_id\n print (type(dividendDate))\n bse_nse_data = self.crawlerNseBse(co_id)\n bseNseJson = bse_nse_data['bseNseJson']\n bsePrice = ''\n nsePrice = ''\n bseDividend = ''\n nseDividend = ''\n if len(bseNseJson) > 0:\n for item_d in bseNseJson:\n \n if 'segment' in item_d:\n if item_d['segment'] == 'BSE':\n \n print (\"bse found\")\n bsePrice = item_d['lastTradedPrice']\n bseDividend = float(items['dividendvalue']) / float(bsePrice) \n \n else:\n print (\"nse found\")\n \n nsePrice = item_d['lastTradedPrice']\n nseDividend = float(items['dividendvalue']) / float(nsePrice) \n\n else:\n bsePrice = ''\n nsePrice = ''\n bseNseJson = []\n bseDividend = ''\n nseDividend = '' \n \n data_to_insert['dividendDate'] = dividendDate\n data_to_insert['bseNseJson'] = bseNseJson\n data_to_insert['bsePrice'] = bsePrice\n data_to_insert['nsePrice'] = nsePrice\n data_to_insert['bseDividend'] = bseDividend\n data_to_insert['nseDividend'] = nseDividend\n collection.update(\n {\n 'companyid':items['companyid']\n },data_to_insert,upsert=True)\n \n print (\"Data inserted successfully in historic_data of data_center db\")\n\n except Exception as e:\n print (\"Exception in mongodb dump operation\", e)\n \n \nif __name__ == '__main__':\n obj = EconomicScrapper()\n return_data = obj.crawler()\n obj.dump_db(return_data)\n\n\n\n# // \"https://mfapps.indiatimes.com/etcal/currencycontroller?pagesize=25&pid=58&pageno=1&sortby=mcap&sortorder=asc&year=2017&callback=ajaxResponse\",\n","sub_path":"script_python3.py","file_name":"script_python3.py","file_ext":"py","file_size_in_byte":6188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"241946466","text":"import sys\nimport numpy as N\nimport matplotlib.pyplot as plt\n\nimport matplotlib\nmatplotlib.rc('xtick', labelsize=19)\nmatplotlib.rc('ytick', labelsize=19)\nmatplotlib.rcParams.update({'font.size': 21})\nmatplotlib.rcParams.update({'lines.linewidth':2.0})\nmatplotlib.rcParams.update({'lines.markersize':10.0})\nmatplotlib.rcParams.update({'legend.numpoints': 1})\nmatplotlib.rcParams.update({'legend.fontsize': 19})\nmatplotlib.rcParams.update({'legend.frameon': False})\nmatplotlib.rcParams.update({'figure.autolayout': True})\n\n#--------------------------------------------------------------\ndef get_offset(filename):\n FileIn = open(filename, \"r\")\n level = []\n time = []\n voffset = []\n root_cycle = []\n\n rec = -1\n for line in FileIn:\n if 'TopGrid' in line:\n rec += 1\n if 'Level' in line:\n lst = line.split()\n level.append(int(lst[2][0]))\n level.append(int(lst[2][0]))\n if 'PARTICLE' in line:\n lst = line.split()\n root_cycle.append(rec)\n time.append(float(lst[1]))\n vx = float(lst[5])\n vy = float(lst[6])\n vz = float(lst[7])\n dv2 = (vx - 1.0)**2 + (vy - 1.0)**2 + (vz - 1.0)**2\n dv = N.sqrt(dv2/3.)\n voffset.append(dv)\n FileIn.close()\n\n level = N.array(level)\n time = N.array(time)\n voffset = N.array(voffset)\n root_cycle = N.array(root_cycle)\n\n # only take the last point in a root grid cycle\n Ind = []\n Ind.append(0)\n for i in range(0,N.size(level),1):\n if (i0)):\n legen_str = 'level %i' %rec\n plt.plot(time1[Ind][0],voffset1[Ind][0]/1e-4,colors1[rec],label=legen_str)\n already_plot1[rec] = 1\n\nfor rec in range(0,N.max(level2)+1,1):\n Ind = N.where(level2 == rec)\n plt.plot(time2[Ind],voffset2[Ind]/1e-4,colors2[rec])\n if ((already_plot2[rec]==0) and (N.size(Ind)>0)):\n legen_str = 'level %i' %rec\n plt.plot(time2[Ind][0],voffset2[Ind][0]/1e-4,colors2[rec],label=legen_str)\n already_plot2[rec] = 1\nplt.xlabel('$t$')\nplt.ylabel('$\\Delta v / 10^{-4}$')\nplt.ylim(-0.1,1.5)\nplt.xticks(N.arange(0.0, 0.411, 0.1))\nplt.savefig(fig_name)\n","sub_path":"run/APMGravitySolver/TestSelfForce/make_plot.py","file_name":"make_plot.py","file_ext":"py","file_size_in_byte":3179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"16803903","text":"import pandas as pd\nfrom lib import dataloader\nimport xlrd,xlwt\nfrom xlutils.copy import copy\n\n# 统计每个航班的人数(带星号航班不考虑)\n# 输出table:{ 航班名:人数 }\ndef calc_passenger(pucks, tickets):\n table = {}\n # 遍历字典\n for pkey, pval in pucks.items():\n for tkey, tval in tickets.items():\n if pval['到达航班'] == tval['到达航班'] and pval['到达日期'] == tval['到达日期']:\n if pkey in table.keys():\n table[pkey] = [tval['乘客数'], 0]\n else:\n table[pkey][0] += tval['乘客数']\n else:\n pass\n\n if pval['出发航班'] == tval['出发航班'] and pval['出发日期'] == tval['出发日期']:\n if pkey in table.keys():\n table[pkey] = [0,tval['乘客数']]\n else:\n table[pkey][1] += tval['乘客数']\n else:\n pass\n\n return table\n\n# 获取出入类型计算的系数\ndef getIta(stra,strb):\n '''\n :param stra: 行索引,字符串\n :param strb: 列索引,字符串\n :return: η值,整型\n '''\n dicRow = {'II':0,'ID':1,'IDI':2,'DI':3,'DD':4,'DDI':5,'DII':6,'DII':7,'DID':8,'DIDI':9}\n filePath = (r'InputData4.xlsx')\n data = pd.read_excel(filePath, encoding='gbk')\n res = data[stra][dicRow[strb]]\n return int(res)\n\n# 旅客流程\ndef passengerFlow(stra,strb):\n '''\n 数字a为表格InputData2.xlsx的列索引,数字b为其行索引\n :param a:表格索引{0:'DT',1:'DS',2:'IT',3:'IS'}\n :param b:表格索引{0:'DT',1:'DS',2:'IT',3:'IS'}\n :return:route:最短流程时间,cnt:捷运乘坐次数\n '''\n filePath = (r'../../InputData2.xlsx')\n data = pd.read_excel(filePath, encoding='gbk')\n # dict_temp = {0: 'DT', 1: 'DS', 2: 'IT', 3: 'IS'}\n dict_b = {'DT':0, 'DS':1, 'IT':2, 'IS':3}\n res = data[strb][dict_b[stra]]\n route = int(res[:2])\n cnt = int(res[-1])\n return route, cnt\n\n#旅客行走时间,从登机口区域a走到b\ndef walkTime(stra,strb):\n '''\n :param a:表格索引{0:'T-North',1:'T-Center',2:'T-South',3:'S-North',4:'S-Center',5:'S-South',6:'S-East'}\n :param b:表格索引{0:'T-North',1:'T-Center',2:'T-South',3:'S-North',4:'S-Center',5:'S-South',6:'S-East'}\n :return:从登机口区域a走到b的时间\n '''\n filePath = (r'../../InputData3.xlsx')\n data = pd.read_excel(filePath, encoding='gbk')\n dict_temp = {'T-North':0,'T-Center':1,'T-South':2,'S-North':3,'S-Center':4,'S-South':5,'S-East':6}\n res = data[strb][dict_temp[stra]]\n time = int(res)\n return time\n\n#计算时间a和时间b的时间间隔,以分表示\ndef calcTime(stra,strb):\n t1 = int(stra[:2]) * 60 + int(stra[2:])\n t2 = int(strb[:2]) * 60 + int(strb[2:])\n return abs(t1 - t2)\n\n#计算换乘紧张度\ndef calcTransferTension(a,b,arr,leave,gatea,gateb):\n '''\n :param a: 出发时间,str,如:1700\n :param b: 到达时间,str,如:0000\n :param arr: 到达,字典{0:'DT',1:'DS',2:'IT',3:'IS'}的key\n :param leave: 出发,字典{0:'DT',1:'DS',2:'IT',3:'IS'}的key\n :param gatea: 登机口a,{0:'T-North',1:'T-Center',2:'T-South',3:'S-North',4:'S-Center',5:'S-South',6:'S-East'}\n :param gate: 登机口b,{0:'T-North',1:'T-Center',2:'T-South',3:'S-North',4:'S-Center',5:'S-South',6:'S-East'}\n :return: 换乘紧张度\n '''\n linktime = calcTime(a,b) - 45\n route, cnt =passengerFlow(arr,leave)\n waltime = walkTime(gatea,gateb)\n excTime = route+cnt*8+waltime\n JZD = excTime/linktime\n return JZD,linktime\n\ndef distributeOfExcTime(excTimeList):\n totalDic = {}\n m = int((max(excTimeList)/10))*10+5\n for i in range(5,m,5):\n #iList.append(i)\n subs = str(i)\n dics = {subs:0}\n totalDic.update(dics)\n dics.clear()\n for times in excTimeList:\n for keys in totalDic:\n if int(times)<= int(keys):\n totalDic[keys] +=1\n return sorted(totalDic.items(),key=lambda item:item[1])\n\ndef distributeOfJZD(JZDlist):\n m = int(max(JZDlist)*10)\n totalDic = {}\n for i in range(1,m):\n subs = str(float(i)/10.)\n dics = {subs:0}\n totalDic.update(dics)\n dics.clear()\n for jzd in JZDlist:\n for keys in totalDic:\n if float(jzd)<= float(keys):\n totalDic[keys] +=1\n return sorted(totalDic.items(),key=lambda item:item[1])\n\ndef drawPictime(list):\n dict = distributeOfExcTime(list)\n import matplotlib.pyplot as plt\n plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签\n plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号\n xlist = []\n ylist = []\n for keys in dict:\n xlist.append(int(keys[0]))\n ylist.append(int(keys[-1]))\n maxNum = max(ylist)\n for index,num in enumerate(ylist):\n ylist[index]=float(float(num)/float(maxNum))\n plt.plot(xlist, ylist)\n plt.bar(xlist, ylist,color='rgb', tick_label=xlist)\n # for a, b in zip(xlist, ylist):\n # plt.text(a, b + 0.05, '%.2f' % b, ha='center', va='bottom', fontsize=11)\n plt.xticks(xlist[::50], xlist[::50], rotation=0)\n plt.xlabel(u'换乘时间(分钟)')\n plt.ylabel(u'比率')\n plt.title(u'总体旅客换乘时间分布图')\n plt.savefig(u'总体旅客换乘时间分布图.jpg')\n plt.show()\n\ndef drawPicjzd(list):\n colors = ['red', 'blue', 'green', 'orange', 'black']\n dict = distributeOfJZD(list)\n import matplotlib.pyplot as plt\n plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签\n plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号\n xlist = []\n ylist = []\n for keys in dict:\n xlist.append(str(keys[0]))\n ylist.append(float(keys[-1]))\n maxNum = max(ylist)\n for index,num in enumerate(ylist):\n ylist[index]=float(float(num)/float(maxNum))\n if int(num) == 1:\n break\n xlist = xlist[:50]\n ylist = ylist[:50]\n plt.plot(xlist, ylist,c='black')\n plt.bar(xlist, ylist,color='rgb', tick_label=xlist)\n plt.xticks(xlist[::10], xlist[::10], rotation=30)\n plt.xlabel(u'紧张度')\n plt.ylabel(u'比率')\n plt.title(u'总体旅客换乘紧张度分布图')\n plt.savefig(u'总体旅客换乘紧张度分布图.jpg')\n plt.show()\n\ndef read_dict(file_dir):\n # 读取结果\n with open(file_dir, 'r') as f:\n a = f.read()\n dic_name = eval(a)\n f.close()\n return dic_name\n\n# 保存最终结果到excel文件中\ndef saveresults():\n res1 = read_dict('../solution/problem1/result.txt')\n res2 = read_dict('../solution/problem2/result.txt')\n res3 = read_dict('../solution/problem3/result.txt')\n\n old_excel = xlrd.open_workbook('../InputData.xlsx')\n new_excel = copy(old_excel)\n ws = new_excel.get_sheet(0) # Pucks\n\n # for i in range(1,753):\n # for j in range(12,14):\n # ws.write()\n\n for rkey, rval in res1.items():\n for r in rval:\n ws.write(int(r.replace('PK','')),12,rkey)\n\n for rkey, rval in res2.items():\n for r in rval:\n ws.write(int(r.replace('PK','')),13,rkey)\n\n for rkey, rval in res3.items():\n for r in rval:\n ws.write(int(r.replace('PK','')),14,rkey)\n\n new_excel.save('../result.xls')\n\nif __name__ == '__main__':\n # 保存三个问题的分配结果\n saveresults()","sub_path":"lib/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"112937830","text":"# Jeb Gipson\n# CTEC 121 / Winter 2019\n# Module 4 / Problem Set 5\n# Problem 3 (25 points)\n\n\"\"\"\nDevelop a program that draws some sort of substantial face that includes two eyes, a nose, a mouth with some teeth, \ntwo ears and some hair.\n\nYou will find faces that were drawn by students in prior classes in a file named faces.png.\n\"\"\"\n\nfrom graphics import *\n\ndef main():\n win = GraphWin(\"Abstract Face\",600,600)\n\n faceBase = Oval(Point(50,500),Point(500,100))\n faceBase.setFill(\"blue\")\n faceBase.draw(win)\n \n rightEar = Polygon(Point(501,305),Point(533,271),Point(533,335))\n rightEar.setFill(\"blue\")\n rightEar.draw(win)\n \n leftEar = Polygon(Point(50,305),Point(9,271),Point(18,335))\n leftEar.setFill(\"purple\")\n leftEar.draw(win)\n\n hair = Polygon(Point(97,80),Point(444,82),Point(359,193))\n hair.setFill(\"green\")\n hair.setOutline(\"brown\")\n hair.setWidth(4)\n hair.draw(win)\n\n eye1 = Circle(Point(204,399),10)\n eye1.setFill(\"yellow\")\n eye1.setOutline(\"red\")\n eye1.setWidth(15)\n eye1.draw(win)\n\n eye2 = eye1.clone()\n eye2.move(40,9)\n eye2.draw(win)\n\n noseBase = Polygon(Point(242,327),Point(318,320),Point(309,250))\n noseBase.setFill(\"purple\")\n noseBase.draw(win)\n \n nostril1 = Circle(Point(271,326),10)\n nostril1.setFill(\"black\")\n nostril1.draw(win)\n\n nostril2 = nostril1.clone()\n nostril2.move(30,-4)\n nostril2.draw(win)\n\n mouth = Circle(Point(250,215),32)\n mouth.setFill(\"black\")\n mouth.setOutline(\"tan\")\n mouth.setWidth(8)\n mouth.draw(win)\n\n tooth = Line(Point(239,249),Point(239,225))\n tooth.setFill(\"white\")\n tooth.setWidth(6)\n tooth.draw(win)\n\n tooth2 = tooth.clone()\n tooth2.move(12,0)\n tooth2.draw(win)\n\n tooth3 = tooth2.clone()\n tooth3.move(12,0)\n tooth3.draw(win)\n\n print(input(\"Whoa!\")) \n\n\nmain()","sub_path":"problem-set-5-problem-3.py","file_name":"problem-set-5-problem-3.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"23018479","text":"from bs4 import BeautifulSoup\nimport pickle\nimport urllib.request\nimport os\n\nfrom stringUtil import unpunctuate\n\nwith open('data.pkl', 'rb') as fp:\n\tdata = pickle.load(fp)\n\tgenre_list = data['genre_list']\n\n\ndef create_dirs(soup):\n\tfor page in soup.find_all(\"div\", {\"id\" : [\"mw-pages\"]}):\n\t\tfor link in page.find_all('a'):\n\t\t\tpage_name = link.get('title')\n\t\t\t\t\n\t\t\t#print(page_name)\n\t\t\tdirectory = genre.replace(\" \", \"_\") +\"/\" + unpunctuate(page_name)\n\t\t\t#if not os.path.exists(directory):\n\t\t\t#\tos.makedirs(directory)\n\nerror_count = 0\n\t\t\t\nfor genre in genre_list:\n\tprint(genre)\n\t\"\"\"\n\tdirectory = genre.replace(\" \", \"_\") +\"\\\" + page_name\n\tif not os.path.exists(directory):\n\t\tos.mkdir(dir)#os.makedirs(directory)\n\t\"\"\"\n\tgenre = genre.replace(\" \", \"_\")\n\turl = \"http://lyrics.wikia.com/wiki/Category:\" + genre\n\turl = (url.encode('utf-8')).decode()\n\t\n\tpg_no = 1\n\tcond = True\n\n\twhile cond:\n\t\tprint(url)\n\t\ttry:\n\t\t\tcontent = urllib.request.urlopen(url).read()\n\t\t\tsoup = BeautifulSoup(content, 'html.parser')\n\t\t\tpages = soup.find_all(\"div\", {\"id\" : [\"mw-pages\"]})\n\t\t\t\n\t\t\tfor page in pages:\n\t\t\t\tfor link in page.find_all('a'):\n\t\t\t\t\tpage_name = link.get('title')\n\t\t\t\t\t\t\n\t\t\t\t\tif page_name:\n\t\t\t\t\t\tdirectory = genre.replace(\" \", \"_\") +\"/\" + unpunctuate(page_name.replace(\" \", \"_\"))\n\t\t\t\t\t\tif not os.path.exists(directory):\n\t\t\t\t\t\t\tos.makedirs(directory)\n\t\t\t\n\t\t\tpg_no += 1\n\t\t\tif pg_no == 2:\n\t\t\t\turl += \"?page=2\"\n\t\t\telif pg_no > 9:\n\t\t\t\ttemp = list(url)\n\t\t\t\tif temp[-2] == \"=\":\n\t\t\t\t\ttemp = temp[:-1]\n\t\t\t\t\ttemp += str(pg_no)\n\t\t\t\t\turl = \"\".join(temp)\n\t\t\t\telse:\n\t\t\t\t\ttemp[-2:] = str(pg_no)\n\t\t\t\t\turl = \"\".join(temp)\t\t\t\t\n\t\t\telse:\n\t\t\t\ttemp = list(url)\n\t\t\t\ttemp[-1] = str(pg_no)\n\t\t\t\turl = \"\".join(temp)\n\t\t\tcond = page.find(\"a\", {\"class\" : \"paginator-next button secondary\"})\n\t\texcept:\n\t\t\terror_count += 1\n\t\t\tprint(\"Error for \", url)\n\t\t\tcond = False\n\t\t\t\nprint(\"Number of errors: \", error_count)\n","sub_path":"main/Scraping/scrapeArtists.py","file_name":"scrapeArtists.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"568992624","text":"from calendar import monthrange\nimport datetime\nimport Config\nimport dbAPIs.TrendingHistoryDB as TrendingHistoryDB\nimport dbAPIs.TrendingTop10DB as TrendingTop10DB\nimport logging\nimport utils.Utils as Utils\nimport utils.CollectionUtils as CollectionUtils\nimport utils.Top10Utils as Top10Utils\n\n'''\nMain program loop.\n''' \ndef main():\n #Initializing\n logging.basicConfig(filename=Config.getTwendingTop10LoggingFile(), level=logging.WARNING)\n con = True\n while (con):\n dateObj, utcToday = Utils.getDateObj()\n todaysTrends = TrendingHistoryDB.getTrends(dateObj, None)\n if todaysTrends:\n todaysTrends = CollectionUtils.sortTrendsByName(todaysTrends)\n todaysTop10 = Top10Utils.getTop10(todaysTrends)\n todaysTrends = None\n \n '''\n Daily Top10 Update\n '''\n updateDay(dateObj, utcToday, todaysTop10)\n \n '''\n Weekly Top10 Update\n '''\n updateWeek(utcToday)\n \n '''\n Monthly Top10 Update\n '''\n updateMonth(utcToday)\n \n '''\n Yearly Top10 Update\n '''\n updateYear(utcToday)\n \n '''\n Alltime Top10 Update\n '''\n updateAllTime()\n \n else:\n Utils.emitWarning([str(datetime.datetime.utcnow()),\"No trends to use for updating, DB return False.\"])\n Utils.goToSleep(300)\n Utils.emitWarning([str(datetime.datetime.utcnow()),\"Main Loop Failed! Program Ending!\"])\n\n\n'''\nDaily Top10 Update\n'''\ndef updateDay(dateObj, utcToday, todaysTop10):\n if utcToday != None:\n dayTop10 = todaysTop10\n #get date information for the new top10\n dayTop10 = Top10Utils.getDateDataForSaving(dayTop10)\n #save/update top10DB\n TrendingTop10DB.updateDailyTop10Collection(dayTop10, dateObj)\n else:\n Utils.emitWarning([str(datetime.datetime.utcnow()),\"No utcToday to use for generating Top10s.\"])\n\n\n'''\nWeekly Top10 Update\n'''\ndef updateWeek(utcToday):\n if utcToday != None:\n #calculate query\n dayOfTheWeek = int(utcToday.strftime('%w'))\n if dayOfTheWeek == 0:\n endOfWeek = utcToday\n startOfWeek = utcToday - datetime.timedelta(days=6)\n else:\n endOfWeek = utcToday + datetime.timedelta(days=(7 - int(dayOfTheWeek)))\n startOfWeek = utcToday - datetime.timedelta(days=(int(dayOfTheWeek) - 1))\n \n #create top10 for week\n top10Collection = []\n currentDate = startOfWeek\n while(currentDate <= endOfWeek):\n dateObj = Utils.getDateObjGivenDateTime(currentDate)\n data = TrendingTop10DB.getTop10('day', dateObj)\n if data != False and data[0]['top10']:\n for item in data[0]['top10']:\n obj = {\n 'name' : item['name'],\n 'count' : item['count'],\n 'url' : item['url']\n }\n top10Collection.append(obj)\n currentDate = currentDate + datetime.timedelta(days=1)\n \n if len(top10Collection) > 0:\n weekTop10 = Top10Utils.createTop10List(top10Collection)\n if weekTop10 and len(weekTop10) == 10:\n #get date information for the new top10\n weekTop10 = Top10Utils.getDateDataForSaving(weekTop10)\n #save/update top10DB\n TrendingTop10DB.updateWeeklyTop10Collection(weekTop10, Utils.getDateObjGivenDateTime(startOfWeek), Utils.getDateObjGivenDateTime(endOfWeek))\n else:\n Utils.emitWarning([str(datetime.datetime.utcnow()),\"Top10 was either False or did not have 10 items exactly.\"])\n else:\n Utils.emitWarning([str(datetime.datetime.utcnow()),\"Top10 Collection for week was empty.\"])\n else:\n Utils.emitWarning([str(datetime.datetime.utcnow()),\"No utcToday to use for generating Top10s.\"])\n\n\n'''\nMonthly Top10 Update\n''' \ndef updateMonth(utcToday):\n if utcToday != None:\n currentMonth = utcToday.strftime('%m')\n currentYear = utcToday.strftime('%Y')\n monthStart = 1\n temp, monthEnd = monthrange(int(currentYear), int(currentMonth))\n \n top10Collection = []\n for i in range(1, monthEnd + 1):\n if i < 10: iStr = \"0\" + str(i)\n else: iStr = str(i)\n date = datetime.datetime.strptime(\"\" + str(currentMonth) + \" \" + iStr + \" \" + str(currentYear), \"%m %d %Y\")\n dateObj = Utils.getDateObjGivenDateTime(date)\n data = TrendingTop10DB.getTop10('day', dateObj)\n if data != False and data[0]['top10']:\n for item in data[0]['top10']:\n obj = {\n 'name' : item['name'],\n 'count' : item['count'],\n 'url' : item['url']\n }\n top10Collection.append(obj)\n \n if len(top10Collection) > 0:\n monthTop10 = Top10Utils.createTop10List(top10Collection)\n if monthTop10 and len(monthTop10) == 10:\n #get date information for the new top10\n monthTop10 = Top10Utils.getDateDataForSaving(monthTop10)\n #save/update top10DB\n TrendingTop10DB.updateMonthlyTop10Collection(monthTop10, Utils.getMonthStr(currentMonth), str(currentYear))\n else:\n Utils.emitWarning([str(datetime.datetime.utcnow()),\"Top10 was either False or did not have 10 items exactly.\"])\n else:\n Utils.emitWarning([str(datetime.datetime.utcnow()),\"Top10 Collection for month was empty.\"])\n else:\n Utils.emitWarning([str(datetime.datetime.utcnow()),\"No utcToday to use for generating Top10s.\"])\n\n\n'''\nYearly Top10 Update\n''' \ndef updateYear(utcToday):\n if utcToday != None:\n currentYear = utcToday.strftime('%Y')\n data = TrendingTop10DB.getTop10('day', {'year':str(currentYear)})\n top10Collection = []\n if data != False:\n for top10 in data:\n for item in top10['top10']:\n obj = {\n 'name' : item['name'],\n 'count' : item['count'],\n 'url' : item['url']\n }\n top10Collection.append(obj)\n \n if len(top10Collection) > 0:\n yearTop10 = Top10Utils.createTop10List(top10Collection)\n if yearTop10 and len(yearTop10) == 10:\n #get date information for the new top10\n yearTop10 = Top10Utils.getDateDataForSaving(yearTop10)\n #save/update top10DB\n TrendingTop10DB.updateYearlyTop10Collection(yearTop10, str(currentYear))\n else:\n Utils.emitWarning([str(datetime.datetime.utcnow()),\"Top10 was either False or did not have 10 items exactly.\"])\n else:\n Utils.emitWarning([str(datetime.datetime.utcnow()),\"Top10 Collection for month was empty.\"])\n else:\n Utils.emitWarning([str(datetime.datetime.utcnow()),\"No utcToday to use for generating Top10s.\"])\n \n \n'''\nAlltime Top10 Update\n'''\ndef updateAllTime():\n data = TrendingTop10DB.getTop10('day',{})\n if data != False:\n top10Collection = []\n if data != False and data[0]['top10']:\n for top10 in data:\n for item in top10['top10']:\n obj = {\n 'name' : item['name'],\n 'count' : item['count'],\n 'url' : item['url']\n }\n top10Collection.append(obj)\n\n if len(top10Collection) > 0:\n allTimeTop10 = Top10Utils.createTop10List(top10Collection)\n if allTimeTop10 and len(allTimeTop10) == 10:\n #get date information for the new top10\n allTimeTop10 = Top10Utils.getDateDataForSaving(allTimeTop10)\n #save/update top10DB\n TrendingTop10DB.updateAllTimeTop10Collection(allTimeTop10)\n else:\n Utils.emitWarning([str(datetime.datetime.utcnow()),\"Top10 was either False or did not have 10 items exactly.\"])\n else:\n Utils.emitWarning([str(datetime.datetime.utcnow()),\"Top10 Collection for month was empty.\"])\n else:\n Utils.emitWarning([str(datetime.datetime.utcnow()),\"No day top10s were returned from DB. Cannot generate alltime top10.\"])\n\n\n'''\nStarts the main function.\n''' \nif __name__ == '__main__':\n while(True):\n try:\n main()\n except Exception as e:\n Utils.emitException([str(datetime.datetime.utcnow()),\"Fatal Error.\",type(e),e.args,e])\n continue","sub_path":"dataControllers/TrendingTop10.py","file_name":"TrendingTop10.py","file_ext":"py","file_size_in_byte":8895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"540573899","text":"import logging\nimport os\nimport bioformats\nimport javabridge\nfrom mytardisbf import previewimage\nfrom xml.etree import ElementTree as et\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_original_metadata(omexml):\n \"\"\" Get the original metadata from structured annotations in OME XML.\n Note: this is currently not used at this stage.\n\n Parameters\n ----------\n omexml: str\n OME XML metadata\n\n Returns\n -------\n orig_meta: dict\n Dict containing key and value pairs for each original\n metadata element\n \"\"\"\n meta_xml = et.fromstring(omexml.encode('utf-8'))\n sa = '{http://www.openmicroscopy.org/Schemas/SA/2013-06}StructuredAnnotations/'\\\n '{http://www.openmicroscopy.org/Schemas/SA/2013-06}XMLAnnotation/'\\\n '{http://www.openmicroscopy.org/Schemas/SA/2013-06}Value/'\\\n '{http://www.openmicroscopy.org/Schemas/SA/2013-06}OriginalMetadata'\n\n return dict([(elem.find('{http://www.openmicroscopy.org/Schemas/SA/2013-06}Key').text,\n elem.find('{http://www.openmicroscopy.org/Schemas/SA/2013-06}Value').text)\n for elem in meta_xml.findall(sa)])\n\n\ndef get_namespaces(meta_xml_root):\n \"\"\"Extract OME and StructuredAnnotation namespaces from OME-XML file\n\n Parameters\n ----------\n meta_xml_root: Element\n Root ElementTree element\n\n Returns\n -------\n ns : dict\n Dictionary with the OME and SA namespaces\n \"\"\"\n ome_ns = meta_xml_root.tag[1:].split(\"}\", 1)[0]\n sa_ns = ome_ns.replace(\"OME\", \"SA\")\n return {'ome': ome_ns, 'sa': sa_ns}\n\n\ndef get_meta(input_file_path, output_path, **kwargs):\n \"\"\" Extract specific metadata typically used in bio-image analysis. Also\n outputs a preview image to the output directory.\n\n Parameters\n ----------\n input_file_path: str\n Input file path\n output_path: str\n\n Returns\n -------\n meta: [dict]\n List of dicts containing with keys and values for specific metadata\n \"\"\"\n pix_exc = set([\"id\", \"significantbits\", \"bigendian\", \"interleaved\"])\n channel_exc = set([\"color\", \"id\", \"color\", \"contrastmethod\", \"fluor\",\n \"ndfilter\", \"illuminationtype\", \"name\",\n \"pockelcellsetting\", \"acquisitionmode\"])\n input_fname, ext = os.path.splitext(os.path.basename(input_file_path))\n if ext[1:] not in bioformats.READABLE_FORMATS:\n logger.debug(\"Unsupported format: %s.%s\" % (input_fname, ext))\n return\n\n try:\n omexml = bioformats.get_omexml_metadata(input_file_path)\\\n .encode('utf-8')\n except javabridge.jutil.JavaException:\n logger.exception(\"Unable to read OME Metadata from: %s\",\n input_file_path)\n return\n\n\n meta_xml = et.fromstring(omexml)\n ome_ns = get_namespaces(meta_xml)\n meta = list()\n for i, img_meta in enumerate(meta_xml.findall('ome:Image', ome_ns)):\n smeta = dict()\n output_file_path = os.path.join(output_path,\n input_fname+\"_s%s.png\" % i)\n logger.debug(\"Generating series %s preview from image: %s\",\n i, input_file_path)\n img = previewimage.get_preview_image(input_file_path, omexml, series=i)\n logger.debug(\"Saving series %s preview from image: %s\",\n i, input_file_path)\n previewimage.save_image(img, output_file_path, overwrite=True)\n logger.debug(\"Extracting metadata for series %s preview from image: %s\",\n i, input_file_path)\n smeta['id'] = img_meta.attrib['ID']\n smeta['name'] = img_meta.attrib['Name']\n smeta['previewImage'] = output_file_path\n for pix_meta in img_meta.findall('ome:Pixels', ome_ns):\n for k, v in pix_meta.attrib.iteritems():\n if k.lower() not in pix_exc:\n smeta[k.lower()] = v\n\n for c, channel_meta in enumerate(pix_meta.findall('ome:Channel', ome_ns)):\n for kc, vc in channel_meta.attrib.iteritems():\n if kc.lower() not in channel_exc:\n if kc.lower() not in smeta:\n smeta[kc.lower()] = [\"Channel %s: %s\" % (c, vc)]\n else:\n smeta[kc.lower()].append(\"Channel %s: %s\" % (c, vc))\n\n meta.append(smeta)\n\n return meta\n\n\ndef get_ome_metadata(input_file_path, output_path, **kwargs):\n \"\"\" Extracts metadata from an input file and save it to a file at\n the specified output_path.\n Note: this is currently not used at this stage.\n\n Parameters\n ----------\n input_file_path: str\n Path to the input file\n\n \"\"\"\n input_fname, ext = os.path.splitext(os.path.basename(input_file_path))\n if ext[1:] not in bioformats.READABLE_FORMATS:\n raise Exception(\"Unsupported format: %s.%s\" % (input_fname, ext))\n\n meta_xml = bioformats.get_omexml_metadata(input_file_path)\n\n output_file_path = os.path.join(output_path, input_fname+\".xml\")\n with open(output_file_path, \"w\") as f:\n f.write(meta_xml.encode('utf-8'))\n\n return {\"ome\": output_file_path}\n","sub_path":"mytardisbf/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":5166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"500199081","text":"\r\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint\r\nfrom tensorflow.keras.layers import Dense, Activation\r\nfrom tensorflow.keras.layers import LSTM\r\nfrom tensorflow.keras.layers import Input\r\nfrom tensorflow.keras.models import Sequential, load_model, Model\r\nfrom tensorflow.keras import backend as K\r\nfrom tensorflow.keras.applications import VGG16\r\nfrom tensorflow.keras.applications import ResNet50\r\nimport cv2\r\nimport os\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport argparse\r\nimport time\r\nimport sys\r\nimport h5py\r\n\r\nimport download\r\n\r\nfrom random import shuffle\r\n\r\n\r\nimport tensorflow as tf\r\nprint(tf.__version__)\r\n\r\n\r\nimg_size = 224\r\nimg_size_touple = (img_size, img_size)\r\n\r\nnum_channels = 3\r\n\r\nimg_size_flat = img_size * img_size * num_channels\r\n\r\nnum_classes = 2\r\n\r\n_num_files_train = 1\r\n\r\n_images_per_file = 20\r\n\r\n_num_images_train = _num_files_train * _images_per_file\r\n\r\nvideo_exts = \".mp4\"\r\n\r\nin_dir = \"video\"\r\nin_dir_prueba = 'video'\r\n\r\n\r\ndef print_progress(count, max_count):\r\n\r\n pct_complete = count / max_count\r\n\r\n msg = \"\\r- Progress: {0:.1%}\".format(pct_complete)\r\n\r\n # Print it.\r\n sys.stdout.write(msg)\r\n sys.stdout.flush()\r\n\r\n\r\ndef get_frames(current_dir, file_name):\r\n in_file = os.path.join(current_dir, file_name)\r\n\r\n images = []\r\n\r\n vidcap = cv2.VideoCapture(in_file)\r\n\r\n success, image = vidcap.read()\r\n\r\n count = 0\r\n\r\n while count < _images_per_file:\r\n\r\n RGB_img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\r\n\r\n res = cv2.resize(RGB_img, dsize=(img_size, img_size),\r\n interpolation=cv2.INTER_CUBIC)\r\n\r\n images.append(res)\r\n\r\n success, image = vidcap.read()\r\n\r\n count += 1\r\n\r\n resul = np.array(images)\r\n\r\n resul = (resul / 255.).astype(np.float16)\r\n\r\n return resul\r\n\r\n\r\nimage_model = ResNet50(include_top=True, weights='imagenet')\r\nimage_model1 = VGG16(include_top=True, weights='imagenet')\r\nimage_model1.summary()\r\n\r\n\r\ntransfer_layer = image_model1.get_layer('fc2')\r\nimage_model1_transfer = Model(inputs=image_model1.input,\r\n outputs=transfer_layer.output)\r\ntransfer_values_size = K.int_shape(transfer_layer.output)[1]\r\nprint(\"La entrada de la red dimensiones:\",\r\n K.int_shape(image_model1.input)[1:3])\r\nprint(\"La salida de la red dimensiones: \", transfer_values_size)\r\n\r\n\r\ndef get_transfer_values(current_dir, file_name):\r\n\r\n shape = (_images_per_file,) + img_size_touple + (3,)\r\n\r\n image_batch = np.zeros(shape=shape, dtype=np.float16)\r\n\r\n image_batch = get_frames(current_dir, file_name)\r\n\r\n shape = (_images_per_file, transfer_values_size)\r\n transfer_values = np.zeros(shape=shape, dtype=np.float16)\r\n\r\n transfer_values = \\\r\n image_model1_transfer.predict(image_batch)\r\n\r\n return transfer_values\r\n\r\n\r\ndef proces_transfer(vid_names, in_dir, labels):\r\n count = 0\r\n\r\n tam = len(vid_names)\r\n\r\n shape = (_images_per_file,) + img_size_touple + (3,)\r\n\r\n while count < tam:\r\n video_name = vid_names[count]\r\n\r\n image_batch = np.zeros(shape=shape, dtype=np.float16)\r\n\r\n image_batch = get_frames(in_dir, video_name)\r\n\r\n shape = (_images_per_file, transfer_values_size)\r\n transfer_values = np.zeros(shape=shape, dtype=np.float16)\r\n\r\n transfer_values = \\\r\n image_model1_transfer.predict(image_batch)\r\n\r\n labels1 = labels[count]\r\n\r\n aux = np.ones([20, 2])\r\n\r\n labelss = labels1 * aux\r\n\r\n yield transfer_values, labelss\r\n\r\n count += 1\r\n\r\n\r\ndef make_files(n_files, names_training, in_dir_prueba, labels_training):\r\n gen = proces_transfer(names_training, in_dir_prueba, labels_training)\r\n numer = 1\r\n\r\n chunk = next(gen)\r\n row_count = chunk[0].shape[0]\r\n row_count2 = chunk[1].shape[0]\r\n with h5py.File('prueba.h5', 'w') as f:\r\n\r\n maxshape = (None,) + chunk[0].shape[1:]\r\n maxshape2 = (None,) + chunk[1].shape[1:]\r\n dset = f.create_dataset('data', shape=chunk[0].shape, maxshape=maxshape,\r\n chunks=chunk[0].shape, dtype=chunk[0].dtype)\r\n dset2 = f.create_dataset('labels', shape=chunk[1].shape, maxshape=maxshape2,\r\n chunks=chunk[1].shape, dtype=chunk[1].dtype)\r\n\r\n dset[:] = chunk[0]\r\n dset2[:] = chunk[1]\r\n for chunk in gen:\r\n if numer == n_files:\r\n break\r\n\r\n dset.resize(row_count + chunk[0].shape[0], axis=0)\r\n dset2.resize(row_count2 + chunk[1].shape[0], axis=0)\r\n\r\n dset[row_count:] = chunk[0]\r\n dset2[row_count:] = chunk[1]\r\n\r\n row_count += chunk[0].shape[0]\r\n row_count2 += chunk[1].shape[0]\r\n print_progress(numer, n_files)\r\n numer += 1\r\n\r\n\r\ndef make_files_validation(n_files, names_validation, in_dir_prueba, labels_validation):\r\n gen = proces_transfer(names_validation, in_dir_prueba, labels_validation)\r\n numer = 1\r\n\r\n chunk = next(gen)\r\n row_count = chunk[0].shape[0]\r\n row_count2 = chunk[1].shape[0]\r\n\r\n with h5py.File('pruebavalidation.h5', 'w') as f:\r\n\r\n maxshape = (None,) + chunk[0].shape[1:]\r\n maxshape2 = (None,) + chunk[1].shape[1:]\r\n dset = f.create_dataset('data', shape=chunk[0].shape, maxshape=maxshape,\r\n chunks=chunk[0].shape, dtype=chunk[0].dtype)\r\n dset2 = f.create_dataset('labels', shape=chunk[1].shape, maxshape=maxshape2,\r\n chunks=chunk[1].shape, dtype=chunk[1].dtype)\r\n\r\n dset[:] = chunk[0]\r\n dset2[:] = chunk[1]\r\n for chunk in gen:\r\n if numer == n_files:\r\n break\r\n\r\n dset.resize(row_count + chunk[0].shape[0], axis=0)\r\n dset2.resize(row_count2 + chunk[1].shape[0], axis=0)\r\n\r\n dset[row_count:] = chunk[0]\r\n dset2[row_count:] = chunk[1]\r\n\r\n row_count += chunk[0].shape[0]\r\n row_count2 += chunk[1].shape[0]\r\n print_progress(numer, n_files)\r\n numer += 1\r\n\r\n\r\ndef label_video_names(in_dir):\r\n names = []\r\n labels = []\r\n for current_dir, dir_names, file_names in os.walk(in_dir):\r\n for file_name in file_names:\r\n if file_name[0:2] == 'vi':\r\n labels.append([1, 0])\r\n names.append(file_name)\r\n elif file_name[0:2] == 'no':\r\n labels.append([0, 1])\r\n names.append(file_name)\r\n c = list(zip(names, labels))\r\n shuffle(c)\r\n names, labels = zip(*c)\r\n return names, labels\r\n\r\n\r\ndef process_alldata_training():\r\n joint_transfer = []\r\n frames_num = 20\r\n count = 0\r\n\r\n with h5py.File('prueba.h5', 'r') as f:\r\n\r\n X_batch = f['data'][:]\r\n y_batch = f['labels'][:]\r\n\r\n for i in range(int(len(X_batch) / frames_num)):\r\n inc = count + frames_num\r\n joint_transfer.append([X_batch[count:inc], y_batch[count]])\r\n count = inc\r\n\r\n data = []\r\n target = []\r\n\r\n for i in joint_transfer:\r\n data.append(i[0])\r\n target.append(np.array(i[1]))\r\n\r\n return data, target\r\n\r\n\r\ndef process_alldata_validation():\r\n joint_transfer = []\r\n frames_num = 20\r\n count = 0\r\n\r\n with h5py.File('pruebavalidation.h5', 'r') as f:\r\n\r\n X_batch = f['data'][:]\r\n y_batch = f['labels'][:]\r\n\r\n for i in range(int(len(X_batch) / frames_num)):\r\n inc = count + frames_num\r\n joint_transfer.append([X_batch[count:inc], y_batch[count]])\r\n count = inc\r\n\r\n data = []\r\n target = []\r\n\r\n for i in joint_transfer:\r\n data.append(i[0])\r\n target.append(np.array(i[1]))\r\n\r\n return data, target\r\n\r\n\r\ndef main():\r\n\r\n current_dir = os.path.dirname(os.path.abspath(\r\n __file__)) # absolute path of current directory\r\n\r\n current_dir = os.path.dirname(os.path.abspath(__file__))\r\n trained_model_path = os.path.join(current_dir, 'trained_net.h5')\r\n\r\n names, labels = label_video_names(in_dir_prueba)\r\n print(\"names\", names)\r\n\r\n validation_set = int(len(names))\r\n names_validation = names\r\n labels_validation = labels\r\n\r\n make_files_validation(validation_set, names_validation,\r\n in_dir_prueba, labels_validation)\r\n\r\n data_val, target_val = process_alldata_validation()\r\n\r\n model = load_model(trained_model_path)\r\n prediction = model.predict(np.array(data_val))\r\n print(\"\\n prediction \\n\", prediction)\r\n\r\n for idx in range(len(prediction)):\r\n print(\"Amount of Violence in %s is %f %%\" %\r\n (names[idx], prediction[idx, 0]*100))\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n main()\r\n","sub_path":"final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":8680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"119498841","text":"# coding: utf8\n\"\"\"\n weasyprint.document\n -------------------\n\n Entry point to the rendering process.\n\n :copyright: Copyright 2011-2012 Simon Sapin and contributors, see AUTHORS.\n :license: BSD, see LICENSE for details.\n\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport io\nimport sys\nimport math\nimport shutil\nimport functools\n\nimport cairo\n\nfrom .css import get_all_computed_styles\nfrom .formatting_structure.build import build_formatting_structure\nfrom .urls import FILESYSTEM_ENCODING\nfrom . import layout\nfrom . import draw\nfrom . import images\nfrom . import pdf\n\n\nclass Document(object):\n \"\"\"Abstract output document.\"\"\"\n def __init__(self, element_tree, enable_hinting, url_fetcher, media_type,\n user_stylesheets, ua_stylesheets):\n self.element_tree = element_tree #: lxml HtmlElement object\n self.enable_hinting = enable_hinting\n self.style_for = get_all_computed_styles(\n element_tree, media_type, url_fetcher,\n user_stylesheets, ua_stylesheets)\n self.get_image_from_uri = functools.partial(\n images.get_image_from_uri, {}, url_fetcher)\n\n def render_pages(self):\n \"\"\"Do the layout and return a list of page boxes.\"\"\"\n return list(layout.layout_document(\n self.enable_hinting, self.style_for, self.get_image_from_uri,\n build_formatting_structure(\n self.element_tree, self.style_for, self.get_image_from_uri)))\n\n def draw_page(self, page, context):\n \"\"\"Draw page on context at scale cairo device units per CSS pixel.\"\"\"\n return draw.draw_page(page, context,\n enable_hinting=self.enable_hinting,\n get_image_from_uri=self.get_image_from_uri)\n\n def get_png_surfaces(self, resolution=None):\n \"\"\"Yield (width, height, image_surface) tuples, one for each page.\"\"\"\n px_resolution = (resolution or 96) / 96\n for page in self.render_pages():\n width = int(math.ceil(page.margin_width() * px_resolution))\n height = int(math.ceil(page.margin_height() * px_resolution))\n surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)\n context = cairo.Context(surface)\n context.scale(px_resolution, px_resolution)\n self.draw_page(page, context)\n yield width, height, surface, page\n\n def get_png_pages(self, resolution=None, _with_pages=False):\n \"\"\"Yield (width, height, png_bytes) tuples, one for each page.\"\"\"\n for width, height, surface, page in self.get_png_surfaces(resolution):\n file_obj = io.BytesIO()\n surface.write_to_png(file_obj)\n if _with_pages:\n yield width, height, file_obj.getvalue(), page\n else:\n yield width, height, file_obj.getvalue()\n\n def write_png(self, target=None, resolution=None):\n \"\"\"Write a single PNG image.\"\"\"\n surfaces = list(self.get_png_surfaces(resolution))\n if len(surfaces) == 1:\n _, _, surface, _ = surfaces[0]\n else:\n total_height = sum(height for _, height, _, _ in surfaces)\n max_width = max(width for width, _, _, _ in surfaces)\n surface = cairo.ImageSurface(\n cairo.FORMAT_ARGB32, max_width, total_height)\n context = cairo.Context(surface)\n pos_y = 0\n for width, height, page_surface, _ in surfaces:\n pos_x = (max_width - width) // 2\n context.set_source_surface(page_surface, pos_x, pos_y)\n context.paint()\n pos_y += height\n\n if target is None:\n target = io.BytesIO()\n surface.write_to_png(target)\n return target.getvalue()\n else:\n if sys.version_info[0] < 3 and isinstance(target, unicode):\n # py2cairo 1.8 does not support unicode filenames.\n target = target.encode(FILESYSTEM_ENCODING)\n surface.write_to_png(target)\n\n def write_pdf(self, target=None):\n \"\"\"Write a single PNG image.\"\"\"\n # Use an in-memory buffer. We will need to seek for metadata\n # TODO: avoid this if target can seek? Benchmark first.\n file_obj = io.BytesIO()\n # We’ll change the surface size for each page\n surface = cairo.PDFSurface(file_obj, 1, 1)\n context = cairo.Context(surface)\n px_to_pt = pdf.PX_TO_PT\n context.scale(px_to_pt, px_to_pt)\n pages = self.render_pages()\n for page in pages:\n surface.set_size(page.margin_width() * px_to_pt,\n page.margin_height() * px_to_pt)\n self.draw_page(page, context)\n surface.show_page()\n surface.finish()\n\n pdf.write_pdf_metadata(pages, file_obj)\n\n if target is None:\n return file_obj.getvalue()\n else:\n file_obj.seek(0)\n if hasattr(target, 'write'):\n shutil.copyfileobj(file_obj, target)\n else:\n with open(target, 'wb') as fd:\n shutil.copyfileobj(file_obj, fd)\n","sub_path":"weasyprint/document.py","file_name":"document.py","file_ext":"py","file_size_in_byte":5193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"48092750","text":"from django.shortcuts import render\n# from django.http import HttpResponse\nfrom . import models\n\n# Create your views here.\ndef index(request):\n # ret = models.Article.objects.get(pk=2)\n ret = models.Article.objects.all()\n return render(request, 'blog/index.html', { 'articles': ret })\n\n# 文章详情\ndef article_page(request, article_id):\n ret = models.Article.objects.get(pk=article_id)\n return render(request, 'blog/article_page.html', { 'article': ret })\n\n# 文章详情编辑\ndef article_page_edit(request, article_id):\n # article_id = 0 则为新增,否则为编辑\n if str(article_id) == '0':\n return render(request, 'blog/article_page_edit.html')\n ret = models.Article.objects.get(pk=article_id)\n return render(request, 'blog/article_page_edit.html', { 'article': ret })\n \n\n# 文章编辑提交内容处理\ndef article_page_edit_action(request):\n # 通过article_id来判断新增还是编辑\n title = request.POST.get('title', '默认标题')\n content = request.POST.get('content', '默认内容')\n article_id = request.POST.get('article_id_hidden', '0')\n\n if str(article_id) == '0':\n # 写文章\n models.Article.objects.create(title=title, content=content)\n ret = models.Article.objects.all()\n return render(request, 'blog/index.html', { 'articles': ret })\n # 更新文章\n ret = models.Article.objects.get(pk=article_id)\n ret.title = title\n ret.content = content\n ret.save()\n return render(request, 'blog/article_page.html', { 'article': ret })\n # pass\n\n \n","sub_path":"jianghu_blog/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"241293008","text":"\"\"\"\nTasks class to run background tasks on a schedule while the server is running. \nTasks are to be run sequentially in a thread parallel to the server thread.\n\"\"\"\nimport threading # for parallel thread\nimport time # for sleeping\nrunning = True\nprint(\"Starting background tasks...\")\n\ndef task_start():\n print(\"Tasks are being re-run\")\n\ndef run_tasks():\n global running\n while(running):\n task_start()\n\n\n time.sleep(600)\n\ntask_thread = threading.Thread(target=run_tasks, args=(), kwargs={})\ntask_thread.setDaemon(True)\ntask_thread.start()","sub_path":"pneumovis/pages/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"601244966","text":"import requests,re\r\n\r\nkey_word=input(\"请输入关键词或完整的番号:\")\r\nif ' ' in key_word:\r\n key_word.replace(' ','%20')\r\nr=requests.get('http://pandilao.com/s/'+key_word)\r\ncer=re.compile(r'''(.*)\r\n\t\t\t.*\r\n\t\t\t
迅雷下载''',flags=0)\r\nresult=cer.findall(r.text)\r\nwith open(key_word+'.txt','w',encoding='utf-8') as f:\r\n for data in result:\r\n print('磁力链接:'+data[1]+'\\t视频大小:'+data[0]+'\\t视频名称:'+data[2])\r\n f.write('磁力链接:'+data[1]+'\\t视频大小:'+data[0]+'\\t视频名称:'+data[2]+'\\n')\r\n\r\n#cer_max=re.compile(r'''''')\r\n#max_page=cer_max.findall(r.text)\r\n#print('max page:',max_page)","sub_path":"search_movies.py","file_name":"search_movies.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"234221050","text":"import logging\nimport urllib2\nimport simplejson\nfrom carddirector.cd_api.constants import message_types\nfrom carddirector.cd_api.services import sign_dict_request_by_private_key\nfrom carddirector.cd_utils import date_utils\nfrom carddirector.cd_utils.string_utils import random_string\nfrom django.conf import settings\nfrom carddirector.cd_api.message_queue import MessageQueue\n\nlogger = logging.getLogger(__name__)\n\nSMOKE_TEST_MODE_CARD_ACCOUNT_BALANCE = 'card_account_balance'\nSMOKE_TEST_MODE_CARD_LOAD = 'card_load'\n\ndef get_smoke_test_context_data(context, client_id, client_code, card_id, private_key_name, smoke_test_mode):\n context['tps_server_txn_in_address'] = ping_url(settings.TPS_SERVER_TXN_IN_ADDRESS)\n context['tps_server_non_txn_in_address'] = ping_url(settings.TPS_SERVER_NON_TXN_IN_ADDRESS)\n context['ping_message_queue_result'] = ping_message_queue()\n context['ping_qgen'] = ping_url(settings.KYC_QGEN_WS_URL)\n context['ping_iid'] = ping_url(settings.KYC_IID_WS_URL)\n\n if SMOKE_TEST_MODE_CARD_ACCOUNT_BALANCE == smoke_test_mode:\n context = create_card_account_balance_request(context, client_id, client_code, card_id, private_key_name)\n elif SMOKE_TEST_MODE_CARD_LOAD == smoke_test_mode:\n context = create_card_load_request(context, client_id, client_code, card_id, private_key_name)\n\n return context\n\ndef ping_message_queue():\n try:\n with MessageQueue() as queue:\n queue.is_message_queue_ok()\n return True\n except Exception as e:\n logger.exception(\"Ping message queue failed: %s\" % e)\n return False \n\ndef ping_url(url):\n stream = None\n try:\n stream = urllib2.urlopen(url, timeout=60)\n stream.read()\n return True\n except Exception:\n logger.exception(\"Ping failed: %s\" % url)\n return False\n finally:\n if stream: stream.close()\n\n\ndef create_json(dict, private_key_name):\n sign_dict_request_by_private_key(dict, private_key_name)\n json = simplejson.dumps(dict)\n return json\n\n\ndef create_card_account_balance_request(context, client_id, client_code, card_id, private_key_name):\n dict = {'header':\n {'version': '1.0',\n 'messageId': random_string(),\n 'clientId': client_id,\n 'timestamp': date_utils.get_utcnow_with_isoformat(),\n 'messageType': message_types.CARD_ACCOUNT_BALANCE,\n 'signatureAlgorithm': 'SHA256'},\n 'cardAccountBalanceInfo':\n {'clientCode': client_code,\n 'cardId': card_id}\n }\n context['request_content'] = create_json(dict, private_key_name)\n return context\n\n\ndef create_card_load_request(context, client_id, client_code, card_id, private_key_name):\n dict = {'header':\n {'version': '1.0',\n 'messageId': random_string(),\n 'clientId': client_id,\n 'timestamp': date_utils.get_utcnow_with_isoformat(),\n 'messageType': message_types.CARD_LOAD,\n 'signatureAlgorithm': 'SHA256'},\n 'cardLoadInfo':\n {'clientCode': client_code,\n 'cardId': card_id,\n 'currency': 'USD',\n 'amountInCents': 'DUMMY'}\n }\n context['request_content'] = create_json(dict, private_key_name)\n return context\n\n#\n#\n#def create_card_unload_request(context):\n# dict = {'header':\n# {'version': '1.0',\n# 'messageId': random_string(),\n# 'clientId': 'TEST_CLIENT_T24',\n# 'timestamp': date_utils.get_utcnow_with_isoformat(),\n# 'messageType': message_types.CARD_UNLOAD,\n# 'signatureAlgorithm': 'SHA256'},\n# 'cardUnloadInfo':\n# {'clientCode': 'T24_CC',\n# 'cardId': '2861462153195637',\n# 'currency': 'USD',\n# 'amountInCents': '10000'}\n# }\n# context['card_unload_request'] = create_json(dict)\n# return context\n#\n#\n#def create_reseller_account_balance_request(context):\n# dict = {'header':\n# {'version': '1.0',\n# 'messageId': random_string(),\n# 'clientId': 'TEST_CLIENT_T24',\n# 'timestamp': date_utils.get_utcnow_with_isoformat(),\n# 'messageType': message_types.RESELLER_ACCOUNT_BALANCE,\n# 'signatureAlgorithm': 'SHA256'},\n# 'resellerAccountBalanceInfo':\n# {'clientCode': 'T24_CC'}\n# }\n# context['reseller_account_balance_request'] = create_json(dict)\n# return context\n","sub_path":"apps/carddirector/cd_main/smoke.py","file_name":"smoke.py","file_ext":"py","file_size_in_byte":4782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"58819603","text":"import pygame\n\nclass Personaje2(pygame.sprite.Sprite):\n def __init__(self, position):\n self.sheet = pygame.image.load('Personaje.png')\n self.sheet.set_clip(pygame.Rect(0, 0, 52, 76))\n self.image = self.sheet.subsurface(self.sheet.get_clip())\n self.rect = self.image.get_rect()\n self.rect.topleft = position\n self.frame = 0\n self.ImaIzq = {0: (0, 76, 52, 76), 1: (52, 76, 52, 76), 2: (156, 76, 52, 76)}\n self.ImaDer = {0: (0, 152, 52, 76), 1: (52, 152, 52, 76), 2: (156, 152, 52, 76)}\n self.ImaArri = {0: (0, 228, 52, 76), 1: (52, 228, 52, 76), 2: (156, 228, 52, 76)}\n self.ImaAba = {0: (0, 0, 52, 76), 1: (52, 0, 52, 76), 2: (156, 0, 52, 76)}\n\n def darCuadroImagen(self, frame_set):\n self.frame += 1\n if self.frame > (len(frame_set) - 1):\n self.frame = 0\n return frame_set[self.frame]\n\n def acortarIma(self, clipped_rect):\n if type(clipped_rect) is dict:\n self.sheet.set_clip(pygame.Rect(self.darCuadroImagen(clipped_rect)))\n else:\n self.sheet.set_clip(pygame.Rect(clipped_rect))\n return clipped_rect\n\n def actualizar(self, direction):\n if direction == 'izq':\n self.acortarIma(self.ImaIzq)\n self.rect.x -= 5\n if direction == 'der':\n self.acortarIma(self.ImaDer)\n self.rect.x += 5\n if direction == 'arri':\n self.acortarIma(self.ImaArri)\n self.rect.y -= 5\n if direction == 'aba':\n self.acortarIma(self.ImaAba)\n self.rect.y += 5\n\n if direction == 'EstaAlaIzq':\n self.acortarIma(self.ImaIzq[0])\n if direction == 'EstaAlaDer':\n self.acortarIma(self.ImaDer[0])\n if direction == 'EstaAArri':\n self.acortarIma(self.ImaArri[0])\n if direction == 'EstaAAba':\n self.acortarIma(self.ImaAba[0])\n\n self.image = self.sheet.subsurface(self.sheet.get_clip())\n\n def manejoDeEvento2(self, event):\n if event.type == pygame.QUIT:\n JuegoTerminado = True\n\n if event.type == pygame.KEYDOWN:\n\n if event.key == pygame.K_a:\n self.actualizar('izq')\n if event.key == pygame.K_d:\n self.actualizar('der')\n if event.key == pygame.K_w:\n self.actualizar('arri')\n if event.key == pygame.K_s:\n self.actualizar('aba')\n\n if event.type == pygame.KEYUP:\n\n if event.key == pygame.K_a:\n self.actualizar('EstaAlaIzq')\n if event.key == pygame.K_d:\n self.actualizar('EstaAlaDer')\n if event.key == pygame.K_w:\n self.actualizar('EstaAArri')\n if event.key == pygame.K_s:\n self.actualizar('EstaAAba')","sub_path":"proyecto/player2.py","file_name":"player2.py","file_ext":"py","file_size_in_byte":2845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"596226140","text":"import config\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn\nfrom torch.utils.data import Dataset, DataLoader\nimport preprocess_across_chiller\ninput_dim = config.input_dim\nhidden_size = config.hidden_size\nbatch_size = config.batch_size\ntrain_ratio = config.train_ratio\nlearningRate = config.learningRate\nepoch = config.epoch\n\n\nclass Net(torch.nn.Module):\n def __init__(self, n_feature, n_hidden):\n super(Net, self).__init__()\n self.hidden = torch.nn.Linear(n_feature, n_hidden, bias=1) # hidden layer\n self.predict = torch.nn.Linear(n_hidden, 1, bias=1) # output layer\n\n def forward(self, x):\n x = F.relu(self.hidden(x)) # activation function for hidden layer\n x = self.predict(x) # linear output\n return x\n\nclass TrainSet(Dataset):\n def __init__(self, datax, datay):\n self.data, self.label = datax, datay\n\n def __getitem__(self, index):\n return self.data[index], self.label[index]\n\n def __len__(self):\n return len(self.data)\n\n\n# we need COP of each chiller\n#COP 已经在之前的file中计算过\nimport pickle\n\ndatax,datay = preprocess_across_chiller.readdata()\n\n\nprint('data size is ', datax.shape, datay.shape)\n\n#######\n# trainset = TrainSet(datax[805:1453],datay[805:1453])\n# 2021年2月3日 10:00 AM to 2021年3月2日11:00 AM\n# trainset = TrainSet(datax[0:306],datay[0:306])\n# 2021年1月1日 00:00 AM to 2021年1月13日 16:00 PM\ntrainset = TrainSet(datax[3354:3528], datay[3354:3528])\n# 2021年5月20日 16:00:00 PM to 2021年5月27日 22:00PM\n########\n\n\ntrainloader = DataLoader(trainset, batch_size=batch_size, shuffle=False)\n\nSeq_model = Net(n_feature=input_dim, n_hidden=hidden_size) # define the network\noptimizer = torch.optim.SGD(Seq_model.parameters(), lr=learningRate)\nloss_func = nn.L1Loss()\n\nfor step in range(epoch):\n Loss_list = []\n prelist = []\n for x, y in trainloader:\n x = x.to(torch.float32)\n y = y.to(torch.float32)\n\n prediction = Seq_model(x) # input x and predict based on x\n for x in prediction:\n prelist.append(x.detach().numpy())\n # print(prediction,y)\n loss = loss_func(prediction, y) # must be (1. nn output, 2. target)\n Loss_list.append(loss.item())\n optimizer.zero_grad() # clear gradients for next train\n loss.backward() # backpropagation, compute gradients\n optimizer.step() # apply gradients\n\n print('Epoch:{}, Loss:{:.5f}'.format(step + 1, loss.item()))\n\n# x = np.linspace(0, len(prelist), len(prelist))\nx = np.linspace(0, len(Loss_list), len(Loss_list))\nplt.plot(x,Loss_list)\n# plt.plot(x, prelist)\n# plt.plot(x, trainset.label)\n# plt.legend(labels = ['prelist','label'])\nplt.show()\n\n#####\n# testset = TrainSet(datax[3354:3528], datay[3354:3528])\n# 2021年5月20日 16:00 PM to 2021年5月27日 22:00PM\n\ntestset = TrainSet(datax[4051:4362], datay[4051:4362])\n#2021年6月18日 16:00 PM to 2021年7月1日 16:00 PM\n\n# testset = TrainSet(datax[805:1453],datay[805:1453])\n# 2021年2月3日 10:00 AM to 2021年3月2日11:00 AM\n\n# testset = TrainSet(datax[0:306],datay[0:306])\n# 2021年1月1日 00:00 AM to 2021年1月13日 16:00 PM\n#######\n\ntestloader = DataLoader(testset, batch_size=batch_size, shuffle=False)\n\nloss_func = nn.L1Loss()\nLoss_list = []\nprelist = []\n\nfor x, y in testloader:\n x = x.to(torch.float32)\n y = y.to(torch.float32)\n\n prediction = Seq_model(x) # input x and predict based on x\n for x in prediction:\n prelist.append(x.detach().numpy())\n # print(prediction,y)\n loss = loss_func(prediction, y) # must be (1. nn output, 2. target)\n Loss_list.append(loss.item())\n print('Epoch:{}, Loss:{:.5f}'.format(1, np.mean(Loss_list)))\n\n# x = np.linspace(0, len(Loss_list), len(Loss_list))\n# plt.plot(x, Loss_list)\n# plt.show()\n\n# x = np.linspace(0, len(prelist), len(prelist))\n# plt.plot(x, prelist)\n# plt.plot(x, testset.label, 'r')\nl = np.linspace(0, len(Loss_list), len(Loss_list))\nplt.plot(l,Loss_list)\nplt.show()","sub_path":"jiaqi_huarun/retrain/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"67628851","text":"# This file is part of the GBI project.\n# Copyright (C) 2012 Omniscale GmbH & Co. KG \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\nimport sys\nimport os\nimport time\n\nimport socket\nimport requests\n\nimport logging\n\nlog = logging.getLogger(__name__)\n\n\ndef init_lib_paths():\n \"\"\"\n Set PATH to include locations of our GDAL/GEOS .dlls.\n\n Only supports win32 for now. On Linux/Unix it should find system libs\n otherwise set LD_LIBRARY_PATH.\n \"\"\"\n\n if sys.platform != \"win32\":\n return\n\n locations = []\n\n # for testing from ./app\n gdal_dev_location = os.path.join(\n os.path.dirname(__file__), \"..\", \"..\", \"packaging\", \"build\", \"gdal\", \"bin\"\n )\n geos_dev_location = os.path.join(\n os.path.dirname(__file__), \"..\", \"..\", \"packaging\", \"build\", \"geos\"\n )\n proj_dev_location = os.path.join(\n os.path.dirname(__file__), \"..\", \"..\", \"packaging\", \"build\", \"proj4\", \"lib\"\n )\n locations = [gdal_dev_location, geos_dev_location, proj_dev_location]\n os.environ[\"PROJ_LIB\"] = os.path.abspath(\n os.path.join(\n os.path.dirname(__file__), \"..\", \"..\", \"packaging\", \"build\", \"proj4\", \"data\"\n )\n )\n os.environ[\"GDAL_DATA\"] = os.path.abspath(\n os.path.join(\n os.path.dirname(__file__), \"..\", \"..\", \"packaging\", \"build\", \"gdal\", \"data\"\n )\n )\n\n if getattr(sys, \"frozen\", None):\n # running from pyinstaller .exe\n basedir = sys._MEIPASS\n\n # for testing the .exe from packaging/dist\n gdal_test_location = os.path.join(basedir, \"..\", \"..\", \"build\", \"gdal\", \"bin\")\n geos_test_location = os.path.join(basedir, \"..\", \"..\", \"build\", \"geos\")\n proj_test_location = os.path.join(basedir, \"..\", \"..\", \"build\", \"proj4\", \"lib\")\n os.environ[\"PROJ_LIB\"] = os.path.join(\n basedir, \"..\", \"..\", \"build\", \"proj4\", \"data\"\n )\n os.environ[\"GDAL_DATA\"] = os.path.join(\n basedir, \"..\", \"..\", \"build\", \"gdal\", \"data\"\n )\n\n # for deployed .exe inside the inno setup destination\n # ./osgeo/bin contains gdal and geos\n osgeo_deploy_location = os.path.join(basedir, \"..\", \"osgeo\", \"bin\")\n if not os.path.exists(os.environ[\"PROJ_LIB\"]):\n os.environ[\"PROJ_LIB\"] = os.path.join(basedir, \"..\", \"osgeo\", \"data\")\n if not os.path.exists(os.environ[\"GDAL_DATA\"]):\n os.environ[\"GDAL_DATA\"] = os.path.join(basedir, \"..\", \"osgeo\", \"data\")\n\n locations = [\n gdal_test_location,\n geos_test_location,\n proj_test_location,\n osgeo_deploy_location,\n ]\n\n path_found = False\n for loc in locations:\n if os.path.exists(loc):\n path_found = True\n os.environ[\"PATH\"] = os.path.abspath(loc) + \";\" + os.environ[\"PATH\"]\n log.info(\"GeoBox PATH environment: %s\", os.environ[\"PATH\"])\n assert path_found\n\n\ndef port_used(port):\n s = socket.socket()\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n try:\n s.bind((\"127.0.0.1\", port))\n except socket.error:\n return True\n finally:\n s.close()\n return False\n\n\ndef wait_for_http_server(host, port, max_wait=10):\n for _ in range(max_wait):\n try:\n if requests.get(\"http://%s:%d/\" % (host, port)):\n break\n except requests.exceptions.RequestException:\n time.sleep(1)\n\n\ndef join_threads(threads, max_wait_time=10):\n shutdown_start = time.time()\n max_wait_time = 10 # sec\n while threads and (time.time() - shutdown_start) < max_wait_time:\n # try to join all threads, but only for up to max_wait_time seconds\n try:\n for t in threads:\n t.join(0.2)\n if not t.is_alive():\n threads.remove(t)\n except KeyboardInterrupt:\n threads = []\n","sub_path":"gr/gbi-client/app/geobox/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"482292914","text":"import subprocess\n\nfrom mibuild.generic_programmer import GenericProgrammer\n\nclass USBBlaster(GenericProgrammer):\n\tneeds_bitreverse = False\n\n\tdef load_bitstream(self, bitstream_file, port=0):\n\t\tusb_port = \"[USB-\"+str(port)+\"]\"\n\t\tsubprocess.call([\"quartus_pgm\", \"-m\", \"jtag\", \"-c\", \"USB-Blaster\"+usb_port, \"-o\", \"p;\"+bitstream_file])\n","sub_path":"mibuild/altera/programmer.py","file_name":"programmer.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"475336571","text":"plaintext=input(\"Enter a plain word: \")\nkey_word=input(\"Enter a key word: \")\nplaintext_int=[ord(i) for i in plaintext]\nkey_int=[ord(i) for i in key_word]\nc=[]\nr=[]\nfor i in range(len(plaintext)):\n value = (plaintext_int[i] + key_int[i % len(key_word)]) % 97\n c.append(value+97)\nfor i in c:\n if i>122:\n i=i-26\n r.append(i)\n else:\n r.append(i)\nfor x in r:\n print(chr(x),end='')\n","sub_path":"lab3.py","file_name":"lab3.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"206675623","text":"import numpy as np\nfrom scipy.stats import norm\n\nfrom optimizers.scipy_opt import minimize\n\n\nclass POI(object):\n def __init__(self, kind, kappa, xi):\n self.kappa = kappa\n self.xi = xi\n self.kind = kind\n\n def acqf(self, x, regressor, y_max):\n \"\"\"\n acquisition function\n Parameters:\n ------------\n x: 2d-array, [sample_num, feature_dim]\n regressor: callable\n \"\"\"\n return self._poi(x, regressor, y_max, self.xi)\n \n\n @staticmethod\n def _poi(x, regressor, y_max, xi):\n \"\"\"\n poi acquisition function\n\n Parameters:\n ------------\n x: 2d-array\n y_max: 2d-array or 1d-array\n shape=(1,1) or (1,)\n \"\"\"\n\n mean, std = regressor.predict(x, return_std=True)\n assert std is not None, 'standard variance is None'\n std = std.reshape((-1,1))\n z = (mean -y_max -xi)/std\n return norm.cdf(z)\n\n\n def acq_max(self, regressor, y_max, bounds, random_state, n_warmup=100000, n_iter=250):\n #ward up eith random points\n x_tries = random_state.uniform(bounds[0], bounds[1], size=(n_warmup,bounds[0].shape[0]))\n acq_tries = self.acqf(x_tries, regressor, y_max=y_max)\n x_max = x_tries[np.argmax(acq_tries, axis=0)]\n acq_max = np.max(acq_tries, axis=0)\n\n #explore the parameter space more throughly\n x_seeds = random_state.uniform(bounds[0], bounds[1], size=(n_iter, bounds[0].shape[0]))\n for x_try in x_seeds:\n res = minimize(lambda x: -self.acqf(x.reshape((-1,1)), \n regressor=regressor,\n y_max=y_max),\n x_try,\n bounds=zip(bounds[0], bounds[1]),\n method='L-BFGS-B')\n\n if acq_max is None or -res.fun[0] >= acq_max:\n x_max = res.x\n acq_max = -res.fun[0]\n return np.clip(x_max, bounds[0], bounds[1])\n \n","sub_path":"acqfuncs/poi.py","file_name":"poi.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"240518259","text":"__author__ = 'cnleng'\n# -*-coding:Latin-1 -*\n\nfrom src.data.Data import *\nfrom src.data.NumericData import *\n\n# test de la fonction table\nscore = {\n \"joueur 1\": 5,\n \"joueur 2\": 35,\n \"joueur 3\": 20,\n}\n\ndata = NumericData(6, \"Numeric\", 9)\nprint(data.type)\n\n# Declaring a lambda function\n# f = lambda x, y: x + y\n","sub_path":"src/main/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"149174672","text":"import cv2 as cv\nimport numpy as np\nimport dlib\nimport os\n\n#cap = cv.VideoCapture(0)\n\nsezd = cv.imread(\"validation/sezd.png\")\nparking = cv.imread(\"validation/parking.jpg\")\nforvard = cv.imread(\"validation/forvard.png\")\nright = cv.imread(\"validation/right.jpg\")\nleft = cv.imread(\"validation/left.jpg\")\nsezd = cv.resize(sezd, (64, 64))\nforvard = cv.resize(forvard, (64, 64))\nright = cv.resize(right, (64, 64))\nleft = cv.resize (left, (64, 64))\nparking = cv.resize(parking, (64, 64))\nmask_sezd = cv.inRange(sezd, (10, 17, 20), (255, 255, 65))\nmask_forvard = cv.inRange(forvard, (10, 17, 20), (255, 255, 65))\nmask_right = cv.inRange(right, (10, 17, 20), (255, 255, 65))\nmask_left = cv.inRange(left, (10, 17, 20), (255, 255, 65))\nmask_parking = cv.inRange(parking, (10, 17, 20), (255, 255, 65))\nmask_sezd = cv.dilate(mask_sezd,None,iterations=1)\nmask_sezd = cv.erode(mask_sezd,None,iterations=1)\nmask_forvard = cv.dilate(mask_forvard,None,iterations=1)\nmask_forvard = cv.erode(mask_forvard,None,iterations=1)\nmask_right = cv.dilate(mask_right,None,iterations=1)\nmask_right = cv.erode(mask_right,None,iterations=1)\nmask_left = cv.dilate(mask_left,None,iterations=1)\nmask_left = cv.erode(mask_left,None,iterations=1)\nmask_parking = cv.dilate(mask_parking,None,iterations=1)\nmask_parking = cv.erode(mask_parking,None,iterations=1)\n\n\nwhile(True):\n cv.imshow(\"sezd\", sezd)\n cv.imshow(\"forvard\", forvard)\n cv.imshow(\"right\", right)\n cv.imshow(\"left\", left)\n cv.imshow(\"parking\", parking)\n cv.imshow(\"m_sezd\", mask_sezd)\n cv.imshow(\"m_forvard\", mask_forvard)\n cv.imshow(\"m_right\", mask_right)\n cv.imshow(\"m_left\", mask_left)\n cv.imshow(\"m_parking\", mask_parking)\n\n if cv.waitKey(1) == ord(\"q\"):\n break\n#cap.release()\ncv.destroyAllWindows()","sub_path":"znaki/znaki_test.py","file_name":"znaki_test.py","file_ext":"py","file_size_in_byte":1766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"624899841","text":"import numpy as np\nimport cv2\nimport os\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.utils.np_utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam\nfrom keras.layers import Dropout,Flatten\nfrom keras.layers.convolutional import Conv2D,MaxPooling2D\n\n###\npath = 'digits_dataset'\ntestRatio = 0.2\nvalidationRatio = 0.2\nimageDimensions = (32, 32, 3)\nbatchSize = 50\nepochs = 10\nstepsPerEpoch = 100\n###\nimages = []\nclassNumber = []\ndataList = [name for name in os.listdir(path) if os.path.isdir(os.path.join(path, name))] #os.listdir(path)\nclassesLenght = len(dataList)\n\n# Train application\n## Import the dataset of images to be trained\nprint(\"Importing dataset.\")\n### Iterate throught all data image folders\nfor folder in range (0, classesLenght):\n currentFilePath = path + \"/\" + str(folder)\n currentImgFolder = os.listdir(currentFilePath)\n\n ### Iterate throught all the images inside current folder\n for img in currentImgFolder:\n #if not os.path.isfile(img):\n currentImg = cv2.imread(currentFilePath + \"/\" + str(img))\n ### Reduce the size to be performance friendly\n currentImg = cv2.resize(currentImg, (imageDimensions[0], imageDimensions[1]))\n ### Store image and coresponding label\n images.append(currentImg)\n classNumber.append(folder)\n print(folder, end=\" \", flush=True)\n \nprint(\"\")\nprint(\"Imported: \", len(classNumber))\n\n## Convert images to numpy array\nimages = np.array(images)\nclassNumber = np.array(classNumber)\n\n## Split the data\n### This will shuffle the dateset evenly in order to train and test it right\n### testRation = 0.2 means: 80% training and 20% testing\n### X_train contains all the images\n### y_train contains all the labels for each image\nX_train, X_test, y_train, y_test = train_test_split(images, classNumber, test_size = testRatio)\n\n### split again for validation purposes\nX_train, X_validation, y_train, y_validation = train_test_split(X_train, y_train, test_size = validationRatio)\n\nnumOfSamples = []\nfor x in range(0, classesLenght):\n numOfSamples.append(len(np.where(y_train == x)[0]))\n\n# Create bar chart\n# plt.figure(figsize=(10, 5))\n# plt.bar(range(0, classesLenght), numOfSamples)\n# plt.title(\"Number of Images for each label\")\n# plt.xlabel(\"Label\")\n# plt.ylabel(\"Number of images\")\n# plt.show()\n\n# Preprocess image\ndef preProcessing(img):\n ### convert it to grayscale\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n ### distrube the light of the image equaly\n img = cv2.equalizeHist(img)\n ### normalize value from 0-255 to 0-1. Better for training process\n img = img/255\n\n return img\n\n### map every image in train, test and validation\nX_train = np.array(list(map(preProcessing, X_train)))\nX_test = np.array(list(map(preProcessing, X_test)))\nX_validation = np.array(list(map(preProcessing, X_validation)))\n\n### show image\n# img = X_train[30]\n# img = cv2.resize(img, (300, 300))\n# cv2.imshow(\"PreProcessed\", img)\n# cv2.waitKey(0)\n\n## Add depth to images\n### The first 3 params will remain the same\nX_train = X_train.reshape(X_train.shape[0], X_train.shape[1], X_train.shape[2], 1)\nX_test = X_test.reshape(X_test.shape[0], X_test.shape[1], X_test.shape[2], 1)\nX_validation = X_validation.reshape(X_validation.shape[0], X_validation.shape[1], X_validation.shape[2], 1)\n\n## Augment images (translation, zoom, rotaion, shift) - will make the dateset more generic\ndataGen = ImageDataGenerator(width_shift_range=0.1,\n height_shift_range=0.1,\n zoom_range=0.2,\n shear_range=0.1,\n rotation_range=10)\ndataGen.fit(X_train)\n\ny_train = to_categorical(y_train, classesLenght)\ny_test = to_categorical(y_test, classesLenght)\ny_validation = to_categorical(y_validation, classesLenght)\n\ndef myModel():\n numOfFilters = 60\n sizeOfFilter1 = (5, 5)\n sizeOfFilter2 = (3, 3)\n sizeOfPool = (2, 2)\n numOfNode = 500\n\n model = Sequential()\n model.add((Conv2D(numOfFilters,\n sizeOfFilter1,\n input_shape = (imageDimensions[0], imageDimensions[1],1),\n activation = 'relu')))\n model.add((Conv2D(numOfFilters, sizeOfFilter1, activation = 'relu')))\n model.add(MaxPooling2D(pool_size = sizeOfPool))\n\n model.add((Conv2D(numOfFilters / 2, sizeOfFilter2, activation = 'relu')))\n model.add((Conv2D(numOfFilters / 2, sizeOfFilter2, activation = 'relu')))\n model.add(MaxPooling2D(pool_size = sizeOfPool))\n model.add(Dropout(0.5)) #reduce orphaning\n\n model.add(Flatten())\n model.add(Dense(numOfNode, activation = 'relu'))\n model.add(Dropout(0.5))\n model.add(Dense(classesLenght, activation = 'softmax'))\n\n model.compile(Adam(lr = 0.001),\n loss = 'categorical_crossentropy',\n metrics = ['accuracy'])\n\n return model\n\n# Start the training\nmodel = myModel()\nhistory = model.fit(dataGen.flow(X_train, y_train, batch_size = batchSize),\n steps_per_epoch = stepsPerEpoch,\n epochs = epochs,\n validation_data = (X_validation, y_validation),\n shuffle = 1)\n\n### how the variation of loss and the variation of accuracy\nplt.figure(1)\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.legend(['training', 'validation'])\nplt.title('Loss')\nplt.xlabel('epoch')\n\nplt.figure(2)\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.legend(['training', 'validation'])\nplt.title('Accuracy')\nplt.xlabel('epoch')\n\n## uncomment in order to see the loss/accuracy graphs\n#plt.show()\n\nscore = model.evaluate(X_test, y_test, verbose = 0)\nprint('Test score: ', score[0])\nprint('Test accuracy: ', score[1])\n\nmodel.save(\"model_trained.h5\")","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":5997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"526774455","text":"#!/usr/bin/env python\nimport argparse\nimport re\nimport sys\n\ndef main(args):\n phone_dict = dict()\n with open(args.words_file, 'rt') as fin:\n for line in fin:\n line = line.replace(\"\\n\", \"\")\n try:\n phone, pid = line.split(None)\n except:\n sys.stderr.write(\"Invalid line in {0}: {1}\".format(args.words_file, line))\n continue\n phone_dict[pid] = phone\n\n with open(args.input_file, 'rt') as fin:\n for line in fin:\n line = line.replace(\"\\n\", \"\")\n tokens = line.split(None)\n out_tokens = [phone_dict[x] if x in phone_dict else x for x in tokens]\n print(' '.join(out_tokens))\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='This script converts the int ids in phone recognizer output to actual phonemes')\n parser.add_argument('--input', dest='input_file', action='store', required=True, help='Input file')\n parser.add_argument('--words', dest='words_file', action='store', required=True, help='Words file')\n args = parser.parse_args()\n sys.exit(main(args))\n","sub_path":"resource/tools/convertPhoneRecogTrans.py","file_name":"convertPhoneRecogTrans.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"430761029","text":"import airflow\nfrom airflow.operators.python_operator import PythonOperator\nfrom airflow.models import DAG\n\nimport time\nfrom pprint import pprint\n\nargs = {\"owner\": \"Boston Python\", \"start_date\": airflow.utils.dates.days_ago(2)}\n\ndag = DAG(dag_id=\"run_me_first\", default_args=args, schedule_interval=None)\n\n\ndef print_context(ds, **kwargs):\n pprint(\"First Airflow task is running with ds: {} and kwargs: {}\".format(ds, kwargs))\n\n\ndef print_iteration(loop_iteration):\n pprint(f\"I am the {loop_iteration}th task created!\")\n\n\nfirst_task = PythonOperator(\n task_id=\"print_context\", provide_context=True, python_callable=print_context, dag=dag\n)\n\nfor i in range(5):\n loop_task = PythonOperator(\n task_id=f\"created_in_loop_{i}\", python_callable=print_iteration, dag=dag, op_args=[i]\n )\n first_task >> loop_task\n","sub_path":"dags/run_me_first.py","file_name":"run_me_first.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"581605662","text":"import re\ntexto = \"Olá_mundo!_Eu_sou_Leonardo_Vasconcelos\"\n\nwhile True:\n search = input(\"Pesquisar: \")\n res = re.findall(search.lower(), texto.lower())\n print(\"\\nResultados:\")\n\n if len(res) == 0:\n print(\"Não foi encontrado nada\\n\")\n else:\n for i in res:\n print(i)\n print(\"Tamanho: \" +str(len(i)) + \"\\n\")","sub_path":"aula51/aula51.py","file_name":"aula51.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"557968182","text":"## Brian Blaylock\n## April 23, 2021\n\n\"\"\"\n==================================\nHerbie Extension: xarray accessors\n==================================\n\nExtend the xarray capabilities with a custom accessor.\nhttp://xarray.pydata.org/en/stable/internals.html#extending-xarray\n\nTo use the herbie xarray accessor, do this...\n\n.. code-block:: python\n\n H = Herbie('2021-01-01', model='hrrr')\n ds = H.xarray('TMP:2 m')\n ds.herbie.crs\n ds.herbie.plot\n\n\"\"\"\nimport warnings\n\nimport cartopy.crs as ccrs\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\nfrom paint.radar import cm_reflectivity\nfrom paint.radar2 import cm_reflectivity\nfrom paint.standard2 import cm_dpt, cm_pcp, cm_rh, cm_tmp, cm_wind\n\n# From Carpenter_Workshop:\n# https://github.com/blaylockbk/Carpenter_Workshop\n# TODO: update to the new cartopy_tools\nfrom toolbox.cartopy_tools_OLD import common_features, pc\n\n\n@xr.register_dataset_accessor(\"herbie\")\nclass HerbieAccessor:\n def __init__(self, xarray_obj):\n self._obj = xarray_obj\n self._center = None\n\n @property\n def center(self):\n \"\"\"Return the geographic center point of this dataset.\"\"\"\n if self._center is None:\n # we can use a cache on our accessor objects, because accessors\n # themselves are cached on instances that access them.\n lon = self._obj.latitude\n lat = self._obj.longitude\n self._center = (float(lon.mean()), float(lat.mean()))\n return self._center\n\n @property\n def crs(self):\n \"\"\"\n Cartopy coordinate reference system (crs) from a cfgrib Dataset.\n\n Projection information is from the grib2 message for each variable.\n\n Parameters\n ----------\n ds : xarray.Dataset\n An xarray.Dataset from a GRIB2 file opened by the cfgrib engine.\n \"\"\"\n\n ds = self._obj\n\n # Get projection from the attributes of HRRR xarray.Dataset\n # CF 1.8 map projection information for the HRRR model\n # http://cfconventions.org/Data/cf-conventions/cf-conventions-1.8/cf-conventions.html#_lambert_conformal\n\n # Projection info is in the variable attributes. The first variable will do.\n attrs = ds[list(ds)[0]].attrs\n\n if attrs[\"GRIB_gridType\"] == \"lambert\":\n lc_kwargs = dict(\n globe=ccrs.Globe(ellipse=\"sphere\"),\n central_latitude=attrs[\"GRIB_LaDInDegrees\"],\n central_longitude=attrs[\"GRIB_LoVInDegrees\"],\n standard_parallels=(\n attrs[\"GRIB_Latin1InDegrees\"],\n attrs[\"GRIB_Latin2InDegrees\"],\n ),\n )\n lc = ccrs.LambertConformal(**lc_kwargs)\n return lc\n elif attrs[\"GRIB_gridType\"] == \"polar_stereographic\":\n npc_kwargs = {}\n if ds.model == \"hrrrak\":\n # See https://rapidrefresh.noaa.gov/hrrr/ALASKA/static/\n npc_kwargs[\"central_longitude\"] = -135\n npc = ccrs.NorthPolarStereo(**npc_kwargs)\n return npc\n elif attrs[\"GRIB_gridType\"] == \"regular_ll\":\n pc_kwargs = {}\n if attrs[\"GRIB_longitudeOfFirstGridPointInDegrees\"] == 0:\n pc_kwargs[\"central_longitude\"] = 180\n pc = ccrs.PlateCarree(**pc_kwargs)\n return pc\n else:\n warnings.warn(\n f'GRIB_gridType [{attrs[\"GRIB_gridType\"]}] is not recognized.'\n )\n return None\n\n def plot(self, ax=None, common_features_kw={}, **kwargs):\n \"\"\"Plot data on a map.\"\"\"\n ds = self._obj\n\n _level_units = dict(\n adiabaticCondensation=\"adiabatic condensation\",\n atmosphere=\"atmosphere\",\n atmosphereSingleLayer=\"atmosphere single layer\",\n boundaryLayerCloudLayer=\"boundary layer cloud layer\",\n cloudBase=\"cloud base\",\n cloudCeiling=\"cloud ceiling\",\n cloudTop=\"cloud top\",\n depthBelowLand=\"m\",\n equilibrium=\"equilibrium\",\n heightAboveGround=\"m\",\n heightAboveGroundLayer=\"m\",\n highCloudLayer=\"high cloud layer\",\n highestTroposphericFreezing=\"highest tropospheric freezing\",\n isobaricInhPa=\"hPa\",\n isobaricLayer=\"hPa\",\n isothermZero=\"0 C\",\n isothermal=\"K\",\n level=\"m\",\n lowCloudLayer=\"low cloud layer\",\n meanSea=\"MSLP\",\n middleCloudLayer=\"middle cloud layer\",\n nominalTop=\"nominal top\",\n pressureFromGroundLayer=\"Pa\",\n sigma=\"sigma\",\n sigmaLayer=\"sigmaLayer\",\n surface=\"surface\",\n )\n\n for var in ds.data_vars:\n print(\"cfgrib variable:\", var)\n print(\"GRIB_cfName\", ds[var].GRIB_cfName)\n print(\"GRIB_cfVarName\", ds[var].GRIB_cfVarName)\n print(\"GRIB_name\", ds[var].GRIB_name)\n print(\"GRIB_units\", ds[var].GRIB_units)\n print(\"GRIB_typeOfLevel\", ds[var].GRIB_typeOfLevel)\n print()\n\n ds[var].attrs[\"units\"] = (\n ds[var]\n .attrs[\"units\"]\n .replace(\"**-1\", \"$^{-1}$\")\n .replace(\"**-2\", \"$^{-2}$\")\n )\n\n dpi = common_features_kw.pop(\"dpi\", 150)\n figsize = common_features_kw.pop(\"figsize\", [10, 5])\n fig, ax = plt.subplots(\n 1,\n 1,\n subplot_kw=dict(projection=ds.herbie.crs),\n dpi=dpi,\n figsize=figsize,\n )\n\n default = dict(\n scale=\"50m\", ax=ax, crs=ds.herbie.crs, STATES=True, BORDERS=True\n )\n common_features_kw = {**default, **common_features_kw}\n common_features(**common_features_kw)\n\n title = \"\"\n kwargs = {}\n cbar_kwargs = dict(pad=0.01)\n\n if ds[var].GRIB_cfVarName in [\"d2m\", \"dpt\"]:\n ds[var].attrs[\"GRIB_cfName\"] = \"dew_point_temperature\"\n\n ## Wind\n wind_pair = {\"u10\": \"v10\", \"u80\": \"v80\", \"u\": \"v\"}\n\n if ds[var].GRIB_cfName == \"air_temperature\":\n kwargs = {**cm_tmp().cmap_kwargs, **kwargs}\n cbar_kwargs = {**cm_tmp().cbar_kwargs, **cbar_kwargs}\n if ds[var].GRIB_units == \"K\":\n ds[var] -= 273.15\n ds[var].attrs[\"GRIB_units\"] = \"C\"\n ds[var].attrs[\"units\"] = \"C\"\n\n elif ds[var].GRIB_cfName == \"dew_point_temperature\":\n kwargs = {**cm_dpt().cmap_kwargs, **kwargs}\n cbar_kwargs = {**cm_dpt().cbar_kwargs, **cbar_kwargs}\n if ds[var].GRIB_units == \"K\":\n ds[var] -= 273.15\n ds[var].attrs[\"GRIB_units\"] = \"C\"\n ds[var].attrs[\"units\"] = \"C\"\n\n elif ds[var].GRIB_name == \"Total Precipitation\":\n title = \"-\".join(\n [f\"F{int(i):02d}\" for i in ds[var].GRIB_stepRange.split(\"-\")]\n )\n ds[var] = ds[var].where(ds[var] != 0)\n kwargs = {**cm_pcp().cmap_kwargs, **kwargs}\n cbar_kwargs = {**cm_pcp().cbar_kwargs, **cbar_kwargs}\n\n elif ds[var].GRIB_name == \"Maximum/Composite radar reflectivity\":\n ds[var] = ds[var].where(ds[var] >= 0)\n cbar_kwargs = {**cm_reflectivity().cbar_kwargs, **cbar_kwargs}\n kwargs = {**cm_reflectivity().cmap_kwargs, **kwargs}\n\n elif ds[var].GRIB_cfName == \"relative_humidity\":\n cbar_kwargs = {**cm_rh().cbar_kwargs, **cbar_kwargs}\n kwargs = {**cm_rh().cmap_kwargs, **kwargs}\n\n elif \"wind\" in ds[var].GRIB_cfName or \"wind\" in ds[var].GRIB_name:\n cbar_kwargs = {**cm_wind().cbar_kwargs, **cbar_kwargs}\n kwargs = {**cm_wind().cmap_kwargs, **kwargs}\n if ds[var].GRIB_cfName == \"eastward_wind\":\n cbar_kwargs[\"label\"] = \"U \" + cbar_kwargs[\"label\"]\n elif ds[var].GRIB_cfName == \"northward_wind\":\n cbar_kwargs[\"label\"] = \"V \" + cbar_kwargs[\"label\"]\n else:\n cbar_kwargs = {\n **dict(\n label=f\"{ds[var].GRIB_parameterName.strip().title()} ({ds[var].units})\"\n ),\n **cbar_kwargs,\n }\n\n p = ax.pcolormesh(\n ds.longitude, ds.latitude, ds[var], transform=pc, **kwargs\n )\n plt.colorbar(p, ax=ax, **cbar_kwargs)\n\n VALID = pd.to_datetime(ds.valid_time.data).strftime(\"%H:%M UTC %d %b %Y\")\n RUN = pd.to_datetime(ds.time.data).strftime(\"%H:%M UTC %d %b %Y\")\n FXX = f\"F{pd.to_timedelta(ds.step.data).total_seconds()/3600:02.0f}\"\n\n level_type = ds[var].GRIB_typeOfLevel\n if level_type in _level_units:\n level_units = _level_units[level_type]\n else:\n level_units = \"unknown\"\n\n if level_units.lower() in [\"surface\", \"atmosphere\"]:\n level = f\"{title} {level_units}\"\n else:\n level = f\"{ds[var][level_type].data:g} {level_units}\"\n\n ax.set_title(\n f\"Run: {RUN} {FXX}\",\n loc=\"left\",\n fontfamily=\"monospace\",\n fontsize=\"x-small\",\n )\n ax.set_title(\n f\"{ds.model.upper()} {level}\", loc=\"center\", fontweight=\"semibold\"\n )\n ax.set_title(\n f\"Valid: {VALID}\",\n loc=\"right\",\n fontfamily=\"monospace\",\n fontsize=\"x-small\",\n )\n\n # Set extent (could do this more efficiently by storing the data elsewhere)\n new = ds.herbie.crs.transform_points(\n pc, ds.longitude.data, ds.latitude.data\n )\n LONS = new[:, :, 0]\n LATS = new[:, :, 1]\n ax.set_extent(\n [LONS.min(), LONS.max(), LATS.min(), LATS.max()], crs=ds.herbie.crs\n )\n\n return ax\n","sub_path":"herbie/accessors.py","file_name":"accessors.py","file_ext":"py","file_size_in_byte":10243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"315032169","text":"import os.path as op\nimport numpy as np\nimport mne\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\n# Set up dirs needed for all visualizations\ntask1_dir = 'fixed_gaze/'\ntask2_dir = 'natural_reading/'\ndata_folder = '../control-experiment/results/preproc_EEG/fixed_gaze/'\nconditions = ['phase_rand', 'armenian', 'normal']\nsubjects = ['587631', '217720', '059694', '394107', '356349', '044846', '050120', '269257', '103183', '862169', '181585', '284297', '643438', '048298', '414822', '638838', '390744', '930517', '093925', '213103', '331536', '205515', '135230', '320268', '319897', '321319', '303786', '822816', '163753', '667207', '424174', '612370', '528213', '009833', '927179', '515155', '366394', '133288']\nprint('Number of participants: ', len(subjects))\nnoise_cov_files = ['noise-cov', 'reg_noise-cov']\nnoise_cov_types = ['with_non_reg_noise_cov', 'with_reg_noise_cov']\nconditions = ['phase_rand', 'armenian', 'normal']\ntask = 'fixed_gaze'\n\nfor subject in subjects:\n for condition in conditions:\n fig_whit, axs = plt.subplots(1,2,figsize = (18.0, 6.0), tight_layout=True)\n if task == 'fixed_gaze':\n evoked_dir = op.join(task1_dir, condition, 'evoked')\n title = 'Subject: ' + subject + '\\nTask: ' + task + '\\nCondition: '+ condition\n else:\n evoked_dir = op.join(task2_dir, 'evoked')\n title = 'Subject: ' + subject + '\\nNoise Cov Mat from: '+condition + '\\nTask: ' + task\n fig_whit.suptitle(title, x=0.5,y=0.99,weight='demibold')\n col = 0\n for noise_cov_type, noise_cov_file in zip(noise_cov_types, noise_cov_files):\n if task == 'fixed_gaze':\n evoked_file = op.join(evoked_dir, subject + '_' + condition + '-ave.fif')\n else:\n evoked_file = op.join(evoked_dir, subject + '-ave.fif')\n evoked = mne.read_evokeds(evoked_file, condition = 0, baseline=None, proj=False)\n cov_mat_file = op.join('noise_cov',condition, subject +'_'+ noise_cov_file + '.fif')\n print('\\n===============================================================================\\n')\n print(cov_mat_file)\n print('\\n===============================================================================\\n')\n noise_cov = mne.read_cov(cov_mat_file)\n fig1 = mne.viz.plot_evoked_white(evoked,noise_cov, show=False)\n fig1.suptitle(noise_cov_file, x = 0.2, y=0.99)\n if task=='fixed_gaze':\n img1 = 'noise_cov/plots/original_images/' + subject + '_FG_white_' + condition + '_' + noise_cov_file + '.png'\n else:\n img1 = 'noise_cov/plots/original_images/' + subject + '_NR_white_' + condition + '_' + noise_cov_file + '.png'\n fig1.savefig(img1, bbox_inches='tight')\n plt.close(fig1)\n img1 = mpimg.imread(img1)\n axs[col].imshow(img1)\n axs[col].set_axis_off()\n col += 1\n del fig1,img1\n\n # plt.show()\n if task=='fixed_gaze':\n file1 = 'noise_cov/plots/' + subject + '_FG_' + condition + '_white.png'\n else:\n file1 = 'noise_cov/plots/' + subject + '_NR_' + condition + '_white.png'\n fig_whit.savefig(file1, bbox_inches='tight')\n plt.close(fig_whit)\n del fig_whit,axs\n","sub_path":"scripts/examine_whitening.py","file_name":"examine_whitening.py","file_ext":"py","file_size_in_byte":3350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"164086880","text":"import sshtunnel\nimport pymongo\nfrom time import time, strftime, gmtime\nfrom os import path, scandir, environ\nfrom sys import argv\nfrom json import loads as decodeJSON\nargv = argv[1:]\n\n\n# FUNCIONES\ndef setEnv(chainText):\n for k, v in {\n 'timestamp': int(time())\n }.items():\n chainText = chainText.replace(f'@{k}', str(v))\n if chainText[:2] == '${' and chainText[-1] == '}':\n chainText = eval(chainText[2:-1])\n elif chainText[0] == '$' and chainText[1:] in environ.keys():\n chainText = environ[chainText[1:]]\n return chainText\n\n\ndef safeComplexity(obj):\n def recursiveKeys(obj, ret=[], prefix='', d='.'):\n if type(obj) == dict:\n for k, x in obj.items():\n if type(x) == dict:\n ret = [*ret, *recursiveKeys(x, ret=[], prefix=f'{prefix}{k}{d}')]\n else:\n ret.append(f'{prefix}{k}')\n return ret\n\n def fget(key, obj, d='.'):\n key, tmp = key.split(d), obj\n for k in key:\n if k in tmp:\n tmp = tmp[k]\n else:\n break\n return tmp\n return {k: fget(k, obj) for k in recursiveKeys(obj)}\n\n\ndef dictDeconstruction(x):\n def inWord(word, let, caseSensitive=False):\n ret = False\n for x in word:\n if (x.lower() == let.lower() if caseSensitive else x == let):\n ret = not ret\n break\n return ret\n ret = {}\n if type(x) == dict:\n for k, v in x.items():\n if inWord(k, '.'):\n tmp = last = ''\n for q in k.split('.'):\n tmp += f'[\\'{q}\\']'\n if eval(f'type(ret{last}) == dict and not \\'{q}\\' in ret{last}.keys()'):\n exec(f'r{tmp}=' + '{}', {'r': ret})\n last = tmp\n exec(f'ret{tmp} = v', {'ret': ret, 'v': v})\n else:\n ret[k] = v\n return ret\n\n\n# VALIDACION\nif len(argv) >= 1:\n fileConfName = f'./conf/{argv[0].lower()}.json'.replace('//', '/')\n if path.isfile(fileConfName):\n conf = decodeJSON(open(fileConfName, encoding='utf8').read())\n invalidValues = [z[0] for z in filter(lambda x: x[1] is None, conf.items())]\n entvars = {z[0]: z[1] if not z[1].isnumeric() else int(z[1]) for z in [x.split('=') for x in filter(lambda q: '=' in q, argv[1:])]}\n conf = {**conf, **entvars}\n conf = dictDeconstruction({k: v if type(v) != str else setEnv(v) for k, v in safeComplexity(conf).items()})\n if len(invalidValues) > 0:\n print(f'The follow params don\\'t be null: {\",\".join(invalidValues)}')\n exit()\n else:\n print(f'Profile {argv[0]} not found.')\nelse:\n print(f\"Profile name is required. Select profile: \\n{chr(10).join([f' - {path.basename(x.path)[:-5]}' for x in scandir('./conf')])}\")\n exit()\n\n# Asignaciones\nSSH_SERVER = conf['SSH_SERVER']\nSSH_PORT = conf['SSH_PORT']\nSSH_USERNAME = conf['SSH_USERNAME']\nSSH_CERT = conf['SSH_CERT']\nREMOTE_MONGO_USER = conf['REMOTE_MONGO_USER']\nREMOTE_MONGO_PASS = conf['REMOTE_MONGO_PASS']\nREMOTE_MONGO_DB = conf['REMOTE_MONGO_DB']\nREMOTE_MONGO_COLLECTION = conf['REMOTE_MONGO_COLLECTION']\nLOCAL_BIND_ADDRESS = conf['LOCAL_BIND_ADDRESS']\nLOCAL_BIND_PORT = conf['LOCAL_BIND_PORT']\nLOCAL_MONGO_USER = conf['LOCAL_MONGO_USER']\nLOCAL_MONGO_PASS = conf['LOCAL_MONGO_PASS']\nLOCAL_MONGO_DB = conf['LOCAL_MONGO_DB']\nLOCAL_MONGO_HOST = conf['LOCAL_MONGO_HOST']\nLOCAL_MONGO_PORT = conf['LOCAL_MONGO_PORT']\nMONGO_URI = f'mongodb://{REMOTE_MONGO_USER}:{REMOTE_MONGO_PASS}@{LOCAL_BIND_ADDRESS}:{LOCAL_BIND_PORT}'\ndb = pymongo.MongoClient(f'mongodb://{LOCAL_MONGO_USER}:{LOCAL_MONGO_PASS}@{LOCAL_MONGO_HOST}:{LOCAL_MONGO_PORT}/')[LOCAL_MONGO_DB]\n\n\ndef getData(collection_name, query={}):\n # define ssh tunnel\n server = sshtunnel.SSHTunnelForwarder(\n SSH_SERVER,\n ssh_username=SSH_USERNAME,\n ssh_pkey=SSH_CERT,\n ssh_port=SSH_PORT,\n remote_bind_address=(LOCAL_BIND_ADDRESS, LOCAL_BIND_PORT)\n )\n server.start()\n connection = pymongo.MongoClient(host=LOCAL_BIND_ADDRESS,\n port=server.local_bind_port,\n username=REMOTE_MONGO_USER,\n password=REMOTE_MONGO_PASS\n )\n db = connection[REMOTE_MONGO_DB]\n data = db[collection_name].find(query)\n return data\n\n\nerrorFileContent = []\ncounterIns, counterErr, total = 0, 0, 0\nfor entry in getData(REMOTE_MONGO_COLLECTION):\n entry['dateInput'] = int(time())\n try:\n db[REMOTE_MONGO_COLLECTION].insert_one(entry)\n counterIns += 1\n except Exception as e:\n errorFileContent.append(str(e))\n counterErr += 1\n total += 1\nGMT = -3 # TIMEZONE\ndate = gmtime(time()+(GMT*3600))\n# Crear archivos si no existen\nif not path.isfile('./logs/current_execution.log'):\n tmpFile = open('./logs/current_execution.log', 'w+')\n tmpFile.write(f\"{' FROM DATABASE PRODUCTION '.center(107,'/')}\\n{'Date'.ljust(40, ' ')}{'Collection'.ljust(17, ' ')}{'Total match'.ljust(17, ' ')}{'Inserted'.ljust(17, ' ')}{'No inserted'.ljust(17, ' ')}\\n\")\n tmpFile.close()\nif not path.isfile('./logs/current_errors.log'):\n tmpFile = open('./logs/current_errors.log', 'w+')\n tmpFile.close()\n# header = f\"{' FROM DATABASE PRODUCTION '.center(107,'/')}\\n{'Date'.ljust(40, ' ')}{'Collection'.ljust(17, ' ')}{'Total match'.ljust(17, ' ')}{'Inserted'.ljust(17, ' ')}{'Inserted'.ljust(17, ' ')}{'No inserted'.ljust(17, ' ')}\\n\"\nprint(f'{strftime(f\"%d-%m-%Y %H:%M:%S GMT{GMT}\", date)}[{int(time())}] {REMOTE_MONGO_COLLECTION.ljust(17, \" \")}{str(total).ljust(17, \" \")}{str(counterIns).ljust(17, \" \")}{str(counterErr).ljust(17, \" \")}')\ntmpFile = open('./logs/current_execution.log', 'a+')\ntmpFile.write(f'{strftime(f\"%d-%m-%Y %H:%M:%S GMT{GMT}\", date)}[{int(time())}] {REMOTE_MONGO_COLLECTION.ljust(17, \" \")}{str(total).ljust(17, \" \")}{str(counterIns).ljust(17, \" \")}{str(counterErr).ljust(17, \" \")}\\n')\ntmpFile.close()\ntmpFile = open('./logs/current_errors.log', 'a+')\nfor x in errorFileContent:\n tmpFile.write(f'{x}\\n')\ntmpFile.close()\n","sub_path":"clone.py","file_name":"clone.py","file_ext":"py","file_size_in_byte":6222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"634021218","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\nimport pytest\n\nfrom h import models\nfrom h.services.annotation_moderation import AnnotationModerationService\nfrom h.services.annotation_moderation import annotation_moderation_service_factory\n\n\nclass TestAnnotationModerationServiceHide(object):\n def test_it_creates_annotation_moderation(self, svc, factories, db_session):\n annotation = factories.Annotation()\n svc.hide(annotation)\n\n mod = db_session.query(models.AnnotationModeration) \\\n .filter_by(annotation=annotation) \\\n .first()\n\n assert mod is not None\n\n def test_it_skips_creating_moderation_when_already_exists(self, svc, factories, db_session):\n existing = factories.AnnotationModeration()\n\n svc.hide(existing.annotation)\n\n count = db_session.query(models.AnnotationModeration) \\\n .filter_by(annotation=existing.annotation) \\\n .count()\n\n assert count == 1\n\n @pytest.fixture\n def svc(self, db_session):\n return AnnotationModerationService(db_session)\n\n\nclass TestAnnotationNipsaServiceFactory(object):\n def test_it_returns_service(self, pyramid_request):\n svc = annotation_moderation_service_factory(None, pyramid_request)\n assert isinstance(svc, AnnotationModerationService)\n\n def test_it_provides_request_db_as_session(self, pyramid_request):\n svc = annotation_moderation_service_factory(None, pyramid_request)\n assert svc.session == pyramid_request.db\n","sub_path":"tests/h/services/annotation_moderation_test.py","file_name":"annotation_moderation_test.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"349076545","text":"\nimport os\nimport numpy as np\nimport scipy\nfrom astropy.io import fits\nfrom matplotlib import pyplot as plt\nfrom astropy.stats import sigma_clipped_stats\n\nfrom IPython import embed\n# set environment variables\nos.environ['CRDS_PATH'] = '/Users/joe/crds_cache/jwst_pub'\nos.environ['CRDS_SERVER_URL'] = 'https://jwst-crds-pub.stsci.edu'\nfrom matplotlib import pyplot as plt\nfrom astropy.io import fits\nfrom gwcs import wcstools\n\n\n## JWST imports\n# The calwebb_spec and spec3 pipelines\nfrom jwst.pipeline import Spec2Pipeline\nfrom jwst.pipeline import Spec3Pipeline\n# individual steps\nfrom jwst.assign_wcs import AssignWcsStep\nfrom jwst.background import BackgroundStep\nfrom jwst.imprint import ImprintStep\nfrom jwst.msaflagopen import MSAFlagOpenStep\nfrom jwst.extract_2d import Extract2dStep\nfrom jwst.srctype import SourceTypeStep\nfrom jwst.wavecorr import WavecorrStep\nfrom jwst.flatfield import FlatFieldStep\nfrom jwst.pathloss import PathLossStep\nfrom jwst.barshadow import BarShadowStep\nfrom jwst.photom import PhotomStep\nfrom jwst.resample import ResampleSpecStep\nfrom jwst.extract_1d import Extract1dStep\nfrom jwst import datamodels\nDO_NOT_USE = datamodels.dqflags.pixel['DO_NOT_USE']\n\n\n# PypeIt imports\nfrom jwst_utils import compute_diff, get_cuts, jwst_show_spec2, jwst_show_msa, jwst_proc, jwst_extract_subimgs\nfrom pypeit.display import display\nfrom pypeit import specobjs\nfrom pypeit import slittrace\nfrom pypeit.utils import inverse, fast_running_median\nfrom pypeit.core import findobj_skymask\nfrom pypeit.core import skysub, coadd\nfrom pypeit.core import procimg\nfrom pypeit.core import flat\n\nfrom pypeit.spectrographs.util import load_spectrograph\nfrom pypeit.images import pypeitimage\nfrom pypeit import calibrations\nfrom pypeit import find_objects\nfrom pypeit import extraction\nfrom pypeit import msgs\nfrom pypeit import spec2dobj\nfrom pypeit import coadd2d\nDO_NOT_USE = datamodels.dqflags.pixel['DO_NOT_USE']\n\n\n#detname = 'nrs1'\n#detector = 1 if 'nrs1' in detname else 2\n\ndisperser = 'G395M'\n#disperser = 'G235M'\n#disperser='PRISM_01133'\ndetectors = ['nrs1', 'nrs2']\n#disperser='PRISM_01117'\nscifiles = []\nfor detname in detectors:\n if 'PRISM_01133' in disperser:\n # PRISM data\n rawpath_level2 = '/Users/joe/jwst_redux/redux/NIRSPEC_PRISM/01133_COM_CLEAR_PRISM/calwebb/Raw'\n output_dir = '/Users/joe/jwst_redux/redux/NIRSPEC_PRISM/01133_COM_CLEAR_PRISM/calwebb/output'\n pypeit_output_dir = '/Users/joe/jwst_redux/redux/NIRSPEC_PRISM/01133_COM_CLEAR_PRISM/calwebb/pypeit'\n\n\n # NIRSPEC 3-point dither\n # dither center\n scifile1 = os.path.join(rawpath_level2, 'jw01133003001_0310x_00001_' + detname + '_rate.fits')\n scifile2 = os.path.join(rawpath_level2, 'jw01133003001_0310x_00002_' + detname + '_rate.fits')\n scifile3 = os.path.join(rawpath_level2, 'jw01133003001_0310x_00003_' + detname + '_rate.fits')\n\n # dither offset\n #scifile = os.path.join(rawpath_level2, 'jw01133003001_0310x_00003_' + detname + '_rate.fits')\n #bkgfile1 = os.path.join(rawpath_level2, 'jw01133003001_0310x_00001_' + detname + '_rate.fits')\n #bkgfile2 = os.path.join(rawpath_level2, 'jw01133003001_0310x_00002_' + detname + '_rate.fits')\n elif 'PRISM_01117' in disperser:\n # PRISM data\n rawpath_level2 = '//Users/joe/jwst_redux/Raw/NIRSPEC_PRISM/01117_COM_CLEAR_PRISM/level_12/01117'\n output_dir = '/Users/joe/jwst_redux/redux/NIRSPEC_PRISM/01117_COM_CLEAR_PRISM/calwebb/output'\n pypeit_output_dir = '/Users/joe/jwst_redux/redux/NIRSPEC_PRISM/01117_COM_CLEAR_PRISM/calwebb/pypeit'\n\n\n # NIRSPEC 3-point dither\n # dither center\n scifile1 = os.path.join(rawpath_level2, 'jw01117007001_03101_00002_' + detname + '_rate.fits')\n scifile2 = os.path.join(rawpath_level2, 'jw01117007001_03101_00003_' + detname + '_rate.fits')\n scifile3 = os.path.join(rawpath_level2, 'jw01117007001_03101_00004_' + detname + '_rate.fits')\n\n elif 'G395M' in disperser:\n # Use islit = 37 for nrs1\n # G395M data\n rawpath_level2 = '/Users/joe/jwst_redux/redux/NIRSPEC_ERO/02736_ERO_SMACS0723_G395MG235M/calwebb/Raw'\n output_dir = '/Users/joe/jwst_redux/redux/NIRSPEC_ERO/02736_ERO_SMACS0723_G395MG235M/calwebb/output'\n pypeit_output_dir = '/Users/joe/jwst_redux/redux/NIRSPEC_ERO/02736_ERO_SMACS0723_G395MG235M/calwebb/pypeit'\n\n # NIRSPEC 3-point dither\n scifile1 = os.path.join(rawpath_level2, 'jw02736007001_03103_00001_' + detname + '_rate.fits')\n scifile2 = os.path.join(rawpath_level2, 'jw02736007001_03103_00002_' + detname + '_rate.fits')\n scifile3 = os.path.join(rawpath_level2, 'jw02736007001_03103_00003_' + detname + '_rate.fits')\n elif 'G235M' in disperser:\n # Use islit = 38 for nrs1\n # G235M data\n rawpath_level2 = '/Users/joe/jwst_redux/Raw/NIRSPEC_ERO/02736_ERO_SMACS0723_G395MG235M/level_2/'\n output_dir = '/Users/joe/jwst_redux/redux/NIRSPEC_ERO/02736_ERO_SMACS0723_G395MG235M/calwebb/output'\n pypeit_output_dir = '/Users/joe/jwst_redux/redux/NIRSPEC_ERO/02736_ERO_SMACS0723_G395MG235M/calwebb/pypeit/'\n\n # NIRSPEC 3-point dither\n scifile1 = os.path.join(rawpath_level2, 'jw02736007001_03101_00002_' + detname + '_rate.fits')\n scifile2 = os.path.join(rawpath_level2, 'jw02736007001_03101_00003_' + detname + '_rate.fits')\n scifile3 = os.path.join(rawpath_level2, 'jw02736007001_03101_00004_' + detname + '_rate.fits')\n scifiles += [scifile1, scifile2, scifile3]\n\n# Make the new Science dir\n# TODO: This needs to be defined by the user\nscipath = os.path.join(pypeit_output_dir, 'Science')\nif not os.path.isdir(scipath):\n msgs.info('Creating directory for Science output: {0}'.format(scipath))\n os.makedirs(scipath)\n\n\n\n# TODO Should we flat field. The flat field and flat field error are wonky and probably nonsense\nparam_dict = {\n 'extract_2d': {'save_results': True},\n 'bkg_subtract': {'skip': True},\n 'imprint_subtract': {'save_results': True},\n 'msa_flagging': {'save_results': True},\n 'master_background_mos': {'skip': True},\n 'srctype': {'source_type':'EXTENDED'},\n# 'flat_field': {'skip': True},\n 'resample_spec': {'skip': True},\n 'extract_1d': {'skip': True},\n 'flat_field': {'save_interpolated_flat': True}, # Flats appear to be just nonsense. So skip for now.\n}\n\n\nbasenames = []\nfor sci in scifiles:\n basenames.append(os.path.basename(sci).replace('_rate.fits', ''))\n\n# Run the spec2 pipeline\nrunflag = False\nif runflag:\n for sci in scifiles:\n spec2 = Spec2Pipeline(steps=param_dict)\n spec2.save_results = True\n spec2.output_dir = output_dir\n result = spec2(sci)\n\n\n\n# Output file names\nintflat_output_files = []\ne2d_output_files =[]\ncal_output_files =[]\nfor ii, basename in enumerate(basenames):\n e2d_output_files.append(os.path.join(output_dir, basename + '_extract_2d.fits'))\n intflat_output_files.append(os.path.join(output_dir, basename + '_interpolatedflat.fits'))\n cal_output_files.append(os.path.join(output_dir, basename + '_cal.fits'))\n\n\ne2d_nrs1 = datamodels.open(e2d_output_files[0])\ne2d_nrs2 = datamodels.open(e2d_output_files[3])\n\nfinal_nrs1 = datamodels.open(cal_output_files[0])\nfinal_nrs2 = datamodels.open(cal_output_files[3])\n\nintflat_nrs1 = datamodels.open(intflat_output_files[0])\nintflat_nrs2 = datamodels.open(intflat_output_files[3])\n\nislit_1 = 37\nslit_names_1 = [slit.name for slit in e2d_nrs1.slits]\nslit_names_2 = [slit.name for slit in e2d_nrs2.slits]\nslit_name = slit_names_1[islit_1]\nislit_2 = np.where(np.array(slit_names_2) == slit_name)[0][0]\n\n\nslit_left_1, slit_righ_1, slit_left_orig_1, slit_righ_orig_1, spec_vals_orig_1, src_trace_ra_1, src_trace_dec_1, \\\nrate_1, rate_var_rnoise_1, rate_var_poisson_1, rate_var_tot_1, dq_1, ra_1, dec_1, waveimg_1, tilts_1, flatfield_1, pathloss_1, \\\nbarshadow_1, photom_conversion_1, final_1 = jwst_extract_subimgs(e2d_nrs1.slits[islit_1], final_nrs1.slits[islit_1], intflat_nrs1.slits[islit_1])\n\nslit_left_2, slit_righ_2, slit_left_orig_2, slit_righ_orig_2, spec_vals_orig_2, src_trace_ra_2, src_trace_dec_2, \\\nrate_2, rate_var_rnoise_2, rate_var_poisson_2, rate_var_tot_2, dq_2, ra_2, dec_2, waveimg_2, tilts_2, flatfield_2, pathloss_2, \\\nbarshadow_2, photom_conversion_2, final_2 = jwst_extract_subimgs(e2d_nrs2.slits[islit_2], final_nrs2.slits[islit_2], intflat_nrs2.slits[islit_2])\n\n\n# Find common slit to both\nnspec_1 = rate_1.shape[0]\nnspec_2 = rate_2.shape[0]\nmin_slit_ra_1 = np.zeros(nspec_1)\nmax_slit_ra_1 = np.zeros(nspec_1)\nmin_slit_ra_2 = np.zeros(nspec_2)\nmax_slit_ra_2 = np.zeros(nspec_2)\n\nfor ii in range(nspec_1):\n ra_seg = ra_1[ii, :]\n min_slit_ra_1[ii] = np.min(ra_seg[np.isfinite(ra_seg)])\n max_slit_ra_1[ii] = np.max(ra_seg[np.isfinite(ra_seg)])\n\nfor ii in range(nspec_2):\n ra_seg = ra_2[ii, :]\n min_slit_ra_2[ii] = np.min(ra_seg[np.isfinite(ra_seg)])\n max_slit_ra_2[ii] = np.max(ra_seg[np.isfinite(ra_seg)])\n\n\n\nsci_nrs1 = datamodels.open(scifiles[0])\nsci_nrs2 = datamodels.open(scifiles[3])\n\nnspec, nspat = sci_nrs1.data.shape\ngap = 180\nnspec_mosaic = 2*nspec + gap\n\nmosaic = np.zeros((nspec_mosaic, nspat))\nmosaic[0:nspec, :] = sci_nrs1.data.T\nmosaic[nspec+gap:, :] = sci_nrs2.data.T\n\ndisplay.show_image(mosaic, chname='Mosaic')\n\n\n","sub_path":"dev_algorithms/jwst/multidet_play.py","file_name":"multidet_play.py","file_ext":"py","file_size_in_byte":9309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"196735054","text":"# coding=utf-8\r\n#\r\n# The MIT License (MIT)\r\n#\r\n# Copyright (c) 2016-2019 yutiansut/QUANTAXIS\r\n#\r\n# Permission is hereby granted, free of charge, to any person obtaining a copy\r\n# of this software and associated documentation files (the \"Software\"), to deal\r\n# in the Software without restriction, including without limitation the rights\r\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n# copies of the Software, and to permit persons to whom the Software is\r\n# furnished to do so, subject to the following conditions:\r\n#\r\n# The above copyright notice and this permission notice shall be included in all\r\n# copies or substantial portions of the Software.\r\n#\r\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n# SOFTWARE.\r\n\r\nfrom QUANTAXIS.QAData.QADataStruct import QA_DataStruct_Stock_transaction\r\nfrom QUANTAXIS.QAFetch.QATdx import QA_fetch_get_stock_transaction, QA_fetch_get_future_transaction_realtime\r\nfrom QUANTAXIS.QAFetch.QAQuery import QA_fetch_stock_info\r\n\r\n\r\nclass QAAnalysis_Transaction():\r\n def __init__(self):\r\n self.data = None\r\n self.code = None\r\n self.stock_info = None\r\n\r\n def get_data(self, code, start, end):\r\n self.code = code\r\n try:\r\n self.data = QA_DataStruct_Stock_transaction(\r\n QA_fetch_get_stock_transaction(code, start, end))\r\n return self.data\r\n except Exception as e:\r\n raise e\r\n\r\n def get_stock_info(self, code):\r\n try:\r\n self.stock_info = QA_fetch_stock_info(code)\r\n except Exception as e:\r\n raise e\r\n\r\n def winner(self):\r\n pass\r\n","sub_path":"QUANTAXIS/QAAnalysis/QAAnalysis_tick.py","file_name":"QAAnalysis_tick.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"358229465","text":"\"\"\" A steady incompressible Navier-Stokes-Boussinesq simulation class \"\"\"\nimport firedrake as fe\nimport sapphire.simulation\n\n\ninner, dot, grad, div, sym = \\\n fe.inner, fe.dot, fe.grad, fe.div, fe.sym\n \ndef variational_form_residual(sim, solution):\n \n Gr = sim.grashof_number\n \n Pr = sim.prandtl_number\n \n ihat, jhat = sapphire.simulation.unit_vectors(sim.mesh)\n \n sim.gravity_direction = fe.Constant(-jhat)\n \n ghat = sim.gravity_direction\n \n p, u, T = fe.split(solution)\n \n psi_p, psi_u, psi_T = fe.TestFunctions(solution.function_space())\n \n mass = psi_p*div(u)\n \n momentum = dot(psi_u, grad(u)*u + Gr*T*ghat) \\\n - div(psi_u)*p + 2.*inner(sym(grad(psi_u)), sym(grad(u)))\n \n energy = psi_T*dot(u, grad(T)) + dot(grad(psi_T), 1./Pr*grad(T))\n \n dx = fe.dx(degree = sim.quadrature_degree)\n \n return (mass + momentum + energy)*dx\n \n \ndef strong_residual(sim, solution):\n \n Gr = sim.grashof_number\n \n Pr = sim.prandtl_number\n \n ghat = sim.gravity_direction\n \n p, u, T = solution\n \n r_p = div(u)\n \n r_u = grad(u)*u + grad(p) - 2.*div(sym(grad(u))) + Gr*T*ghat\n \n r_T = dot(u, grad(T)) - 1./Pr*div(grad(T))\n \n return r_p, r_u, r_T\n \n \ndef element(cell, degree):\n \n scalar = fe.FiniteElement(\"P\", cell, degree)\n \n vector = fe.VectorElement(\"P\", cell, degree + 1)\n \n return fe.MixedElement(scalar, vector, scalar)\n \n \nclass Simulation(sapphire.simulation.Simulation):\n \n def __init__(self, *args, mesh, element_degree, **kwargs):\n \n self.grashof_number = fe.Constant(1.)\n \n self.prandtl_number = fe.Constant(1.)\n \n super().__init__(*args,\n mesh = mesh,\n element = element(\n cell = mesh.ufl_cell(), degree = element_degree),\n variational_form_residual = variational_form_residual,\n time_dependent = False,\n **kwargs)\n ","sub_path":"sapphire/simulations/navier_stokes_boussinesq.py","file_name":"navier_stokes_boussinesq.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"224884535","text":"import Adafruit_BBIO.PWM as PWM\r\nimport lcm\r\nfrom rover_msgs import ServoCmd\r\n\r\n\r\n# Don't know if this is the same for the servo we're using\r\nSERVO_MAX_DC = 10.0\r\nSERVO_MIN_DC = 4.0\r\n\r\nammonia_blue = \"P9_14\"\r\namino_blue = \"P9_16\"\r\n\r\nammonia_white = \"P8_13\"\r\namino_white = \"P8_19\"\r\n\r\nammonia_yellow = \"P9_21\"\r\namino_yellow = \"P9_22\"\r\n\r\nlcm_ = lcm.LCM()\r\n\r\n\r\ndef angle_to_dc(degrees):\r\n percent = degrees / 120.0\r\n dc = SERVO_MIN_DC + (percent * (SERVO_MAX_DC - SERVO_MIN_DC))\r\n return dc\r\n\r\n\r\ndef run_servo(pin, degrees):\r\n dc = angle_to_dc(degrees)\r\n PWM.set_duty_cycle(pin, dc)\r\n\r\n\r\ndef servo_init(pin, degrees):\r\n dc = angle_to_dc(degrees)\r\n PWM.start(pin, dc, 50)\r\n\r\n\r\ndef servocmd_callback(channel, msg):\r\n servo = ServoCmd.decode(msg)\r\n\r\n # Blue callback\r\n if (servo.id == \"amino_blue\"):\r\n run_servo(amino_blue, servo.position)\r\n elif (servo.id == \"ammonia_blue\"):\r\n run_servo(ammonia_blue, servo.position)\r\n\r\n # White callback\r\n elif (servo.id == \"amino_white\"):\r\n run_servo(amino_white, servo.position)\r\n elif (servo.id == \"ammonia_white\"):\r\n run_servo(ammonia_white, servo.position)\r\n\r\n # Yellow callback\r\n elif (servo.id == \"amino_yellow\"):\r\n run_servo(amino_yellow, servo.position)\r\n elif (servo.id == \"ammonia_yellow\"):\r\n run_servo(ammonia_yellow, servo.position)\r\n\r\n\r\ndef main():\r\n\r\n servo_init(amino_blue, 0)\r\n servo_init(ammonia_blue, 0)\r\n\r\n servo_init(amino_white, 0)\r\n servo_init(ammonia_white, 0)\r\n\r\n servo_init(amino_yellow, 0)\r\n servo_init(ammonia_yellow, 0)\r\n # Might need a manual set to 0, not sure if init sets to angle 0 initially\r\n\r\n lcm_.subscribe(\"/servo_cmd\", servocmd_callback)\r\n\r\n while(1):\r\n lcm_.handle()\r\n","sub_path":"beaglebone/servo/src/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"567939222","text":"from math import sqrt\r\nfrom bot_code.conversions import output_formatter\r\nimport math\r\n\r\nUCONST_Pi = 3.1415926\r\nURotation180 = float(32768)\r\nURotationToRadians = UCONST_Pi / URotation180\r\n\r\n\r\ndef get_extra_features_from_array(array):\r\n car_loc = output_formatter.GAME_INFO_OFFSET + output_formatter.SCORE_INFO_OFFSET\r\n car_x = array[car_loc]\r\n car_y = array[car_loc + 1]\r\n car_z = array[car_loc + 2]\r\n car_rot_pitch = array[car_loc + 3]\r\n car_rot_yaw = array[car_loc + 4]\r\n\r\n ball_loc = car_loc + output_formatter.CAR_INFO_OFFSET\r\n ball_x = array[ball_loc]\r\n ball_y = array[ball_loc + 1]\r\n ball_z = array[ball_loc + 2]\r\n\r\n features = []\r\n features += generate_angles(car_x, car_y, car_z, ball_x, ball_y, ball_z, car_rot_pitch, car_rot_yaw)\r\n features.append(get_distance(car_x, car_y, car_z, ball_x, ball_y, ball_z))\r\n return features\r\n\r\n\r\ndef get_extra_features(game_tick_packet, self_index):\r\n car = game_tick_packet.gamecars[self_index]\r\n ball = game_tick_packet.gameball\r\n angles = generate_angles_loc(car, ball)\r\n distance = [get_distance_location(car.Location, ball.Location)]\r\n return angles + distance\r\n\r\n\r\ndef get_distance(x1, y1, z1, x2, y2, z2):\r\n # print(x1, y1, z1, x2, y2, z2)\r\n return sqrt((x1 - x2)**2 +\r\n (y1 - y2)**2 +\r\n (z1 - z2)**2)\r\n\r\n\r\ndef get_distance_location(location1, location2):\r\n return sqrt((location1.X - location2.X)**2 +\r\n (location1.Y - location2.Y)**2 +\r\n (location1.Z - location2.Z)**2)\r\n\r\n\r\ndef generate_angles(player_x, player_y, player_z, ball_x, ball_y, ball_z, pitch, yaw):\r\n\r\n # Nose vector x component\r\n player_rot1 = math.cos(pitch * URotationToRadians) * math.cos(yaw * URotationToRadians)\r\n # Nose vector y component\r\n player_rot4 = math.cos(pitch * URotationToRadians) * math.sin(yaw * URotationToRadians)\r\n # Nose vector z component\r\n # player_rot2 = math.sin(pitch * URotationToRadians)\r\n\r\n # Need to handle atan2(0,0) case, aka straight up or down, eventually\r\n player_front_direction_in_radians = math.atan2(player_rot1, player_rot4)\r\n relative_angle_to_ball_in_radians = math.atan2((ball_x - player_x), (ball_y - player_y))\r\n\r\n #player_front_direction_in_radians_XZ = math.atan2(player_rot1, player_rot2)\r\n #relative_angle_to_ball_in_radians_XZ = math.atan2((ball_x - player_x), (ball_z - player_z))\r\n\r\n return [player_front_direction_in_radians - relative_angle_to_ball_in_radians]\r\n\r\n\r\ndef generate_angles_loc(car, ball):\r\n return generate_angles(car.Location.X, car.Location.Y, car.Location.Z,\r\n ball.Location.X, ball.Location.Y, ball.Location.Z,\r\n float(car.Rotation.Pitch), float(car.Rotation.Yaw))\r\n","sub_path":"bot_code/modelHelpers/feature_creator.py","file_name":"feature_creator.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"312065841","text":"#!/usr/bin/env python3\n\nimport os, sys\nimport subprocess\nfrom string import Template\nfrom select import epoll, EPOLLIN\n\nTEMPLATE=\"\"\"\ncat(\"Starting\\\\n\")\ncat(\"Starting again\\\\n\")\nlibrary(dada2)\ncat(\"Dadaing\\\\n\")\nlibrary(notechoppe)\ncat(\"Never\\\\n\")\n\"\"\"\n\n\ndef read_with_timeout(fd, timeout__s):\n \"\"\"Reads from fd until there is no new data for at least timeout__s seconds.\n\n This only works on linux > 2.5.44.\n \"\"\"\n buf = []\n e = epoll()\n e.register(fd, EPOLLIN)\n while True:\n ret = e.poll(timeout__s)\n if not ret or ret[0][1] is not EPOLLIN:\n break\n buf.append(\n fd.read(1)\n )\n return ''.join(buf)\n\ndef runScript(script):\n \"\"\"\n Given a multiline Rscript (script), feed it to RScript via STDIN\n line by line and return error if one line fails\n \"\"\"\n p = subprocess.Popen([\"Rscript\", \"--vanilla\", \"-\"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n \n for line in script.split(\"\\n\"):\n stdout_data = p.communicate(input=line.encode())\n print(stdout_data)\n \n return 1\n \nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser(description='Run a template')\n parser.add_argument('--template', '-t', type=str, default=TEMPLATE)\n\n args = parser.parse_args()\n p = subprocess.Popen([\"Rscript\", \"--vanilla\", \"-\"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out, err = p.communicate(input=args.template.encode())\n print(out.decode())\n print(\"===\")\n print(err.decode())","sub_path":"lab/templateR.py","file_name":"templateR.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"575047217","text":"import time, random #these need to be imported so the program can use the time.sleep() and random.randint() functions (which are in the digest function)\n\ndef snail(): #this function creates the snail \n print(\"hello im George's snail! \\n\")\n alive = True #assigning alive boolean variable to true\n while alive == True: #while snail is alive the following code will loop (so forever)\n print(\"George's snail is hungry\") #snail starts hungry\n feed() #this will call the food function, the program will now execute the code in feed() before carrying on\n print(\"George's snail is full!\\n\") #snail has been fed\n digest() #this will call the digest function, wont go to next line until executing code in digest()\n #after calling the digest function the code will loop back to line 07\n \n\n#in summary this function pauses the execution of program between 5-10 seconds\ndef digest(): #this function is basically allows the snail to digest food inbetween eating by waiting for a random amount of seconds between 5-10\n print(\"George's snail is digesting food... \\n\")\n digestTime = random.randint(5,10) #variable digestTime will contain a random number between 5 and 10\n time.sleep(digestTime) # the program will pause execution for how many seconds the variable 'digestTime' contains\n \n\ndef feed():\n #try basicall means \"do the following indented code, if something bad happens (e.g. invalid data inputted like a string) go to 'except' to handle error\"\n try:\n food = int(input(\">enter 1 to feed lettuce or enter 2 to feed cabbage \\n\")) #in the command line enter a number (1 or 2)and the variable 'food' will be assingned that value\n if food == 1: #if you entered the number 1\n print(\"you fed George's snail lettuce\") #this will print\n elif food == 2: #if you entered the number 2\n print(\"you fed George's snail cabbage\") #this will print\n else: # if a number is entered thats not 1 or 2 this will print\n print(\"you entered an invalid number, he didn't like that... try again\")\n feed()#this will call the method again because you need to try again (its called recursion)\n \n except NameError:#this will run if you entered something that wasnt a number e.g a word/String\n print(\"George's snail doesn't understand what that means.. try again \\n\")\n feed()#this will call the method again becuase you need to try to feed the snail again\n\n#the following two lines make the program come to life by executing the function snail()\nif __name__ == '__main__':\n snail() \n \n \n","sub_path":"snail.py","file_name":"snail.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"311192138","text":"import queue\nimport time\nfrom multiprocessing import Process, Manager\nfrom typing import TYPE_CHECKING\n\nfrom .logger import Logger, DEBUG\nfrom .task import *\n\nif TYPE_CHECKING:\n from multiprocessing import Queue as Q\n\nlogger = Logger('Queue', DEBUG)\n\n\nclass Queue(Process):\n def __init__(self):\n super().__init__()\n self.manager = Manager()\n self.tasks: Dict[str] = self.manager.dict()\n self.queue: Q = self.manager.Queue()\n self.counter = self.manager.Value('i', 0)\n\n def wait_for(self, task: Task, timeout=0) -> TaskResult:\n task_id = task.task_id\n self.tasks[task_id] = None\n try:\n self.queue.put(serialize_task(task), timeout=5)\n logger.info(f\"[T][{task_id}] {task.name}\")\n except Exception as e:\n logger.error(e)\n raise e\n # Wait until task done\n start_ts = time.time()\n result = None\n while True:\n # logger.info(f\"[T][{task_id}] WAIT\")\n if timeout != 0 and time.time() - start_ts > timeout:\n raise TimeoutError()\n if self.tasks[task_id] is None:\n # Not done yet, keep trying fetch\n time.sleep(0.05)\n continue\n else:\n result = deserialize_task_result(self.tasks[task_id])\n del self.tasks[task_id]\n break\n logger.info(f\"[T][{task_id}] DONE\")\n return result\n\n def process(self, encoded_task: str):\n task = deserialize_task(encoded_task)\n logger.info(f\"[C][{task.task_id}] Consuming task {self.counter.get()}\")\n result = task.execute()\n self.tasks[task.task_id] = serialize_task_result(result)\n logger.info(f\"[C][{task.task_id}] Consumed [{'OK' if result.success else 'FAIL'}]\")\n self.counter.set(self.counter.get() + 1)\n\n def reset_queue(self):\n self.queue.close()\n for k in self.tasks.keys():\n self.tasks[k] = False\n self.queue: Q = self.manager.Queue()\n\n def run(self) -> None:\n logger.info(\"[!] Started task queue\")\n while True:\n try:\n encoded_task = self.queue.get(block=False)\n self.process(encoded_task)\n except queue.Empty:\n time.sleep(0.05)\n continue\n except Exception as e:\n logger.error(f'Queue error: {e}')\n self.reset_queue()\n time.sleep(1)\n","sub_path":"src/api/queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"111141159","text":"'''Wikipedia\nIn computer science, recursion is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem.\nMost programming languages support recursion by allowing a function to call itself from within it's own code.'''\n\n\nhouses = ['Eric\\'s house', 'Amy\\'s house', 'John\\'s house']\n\n'''ITERATIVE EXAMPLE'''\ndef deliver_presents_iteratively(arr):\n for house in arr:\n print('Delivery to', house)\n\n# deliver_presents_iteratively(houses)\n\n'''RECURSIVE EXAMPLE'''\n#each funtion call represents an elf doing his work\ndef deliver_presents_recursively(arr):\n #minimum wage elf doing his job\n if len(arr) == 1:\n house = arr[0]\n print('Delivering to', house)\n \n #manager elf, that divides and delegates his work\n else:\n mid = len(arr) // 2\n first_half = arr[:mid]\n second_half = arr[mid:]\n\n #divides\n deliver_presents_recursively(first_half)\n deliver_presents_recursively(second_half)\n\n# deliver_presents_recursively(houses)\n\n#A recursive function will continue to call itself and repeat its behavior until some \n#condition is met to return a result\n\n\n\n'''MAINTAINING STATE'''\n#By Passing the updated current state to each recursive call as an argument\ndef sum_recursive(current_num, accumulated_sum): #Sum of all nums up to 10 in this instance\n #base or end case\n if current_num == 11:\n return accumulated_sum\n \n #recursive case\n else:\n return sum_recursive(current_num + 1, accumulated_sum + current_num)\n\n# print(sum_recursive(1, 0))\n\n#Maintaining state by keeping args in global scope\n\n# current_number = 1\n# accumulated_sum = 0\n\n# def sum_recursive():\n# global current_number\n# global accumulated_sum\n# #base case\n# if current_number == 11:\n# return accumulated_sum\n# #Recursive case\n# else:\n# accumulated_sum = accumulated_sum + current_number\n# current_number = current_number + 1\n# return sum_recursive\n\n\ndef list_sum_recursive(input_list):\n #base case\n if input_list == []:\n return 0\n \n #recursive case\n # Decompose the original problem into simpler instances of the same problem\n # by making use of the fact that the input is a recursive data structure \n # and can be defined in terms if a smaller version of itself\n else:\n head = input_list[0]\n smaller_list = input_list[1:]\n return head + list_sum_recursive(smaller_list)\n\n\n# print(list_sum_recursive([1,2,3,4,5]))\n\n\ndef recursive_factorial(n):\n #Base Case: 1! == 1\n if n <= 1:\n return 1\n \n #Recursive case n! = n * (n-1)!\n else:\n return n * recursive_factorial(n-1)\n\nprint(recursive_factorial(4))\n'''We have to calculate recursive_factorial(4).\n\nThe function asks, is n == 1? No, n == 4 so let's return 4 * recursive_factorial(4 - 1),\nwhich is 4 * recursive_factorial(3).\n\nNow we have to calculate recursive_factorial(3).\n\nIs n == 1? No, n == 3 so let's return 4 * 3 * recursive_factorial(3 - 1),\nwhich is 4 * 3 * recursive_factorial(2).\n\nNow we have to calculate recursive_factorial(2).\n\nIs n == 1? No, n == 2 so let's return 4 * 3 * 2 * recursive_factorial(2 - 1),\nwhich is 4 * 3 * 3 * recursive_factorial(1).\n\nNow we have to calculate recursive_factorial(1).\n\nIs n == 1? Yes, n == 1, so let's return 4 * 3 * 2 * 1 which gives us 24 that is then returned one last time by\nthe original function call.'''\n\n\n","sub_path":"Terms/recursion.py","file_name":"recursion.py","file_ext":"py","file_size_in_byte":3460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"147679517","text":"import pandas as pd\nimport numpy as np\nimport cvxpy as cp\n\ndef load_wdbc():\n \n features_labels = ['radius_mean', \n 'texture_mean' , \n 'perimeter_mean', \n 'area_mean' , \n 'smoothness_mean', \n 'compactness_mean', \n 'concavity_mean' , \n 'concave points_mean', \n 'symmetry_mean' , \n 'fractal_dimension_mean', \n 'radius_se' , \n 'texture_se' , \n 'perimeter_se' , \n 'area_se' , \n 'smoothness_se' , \n 'compactness_se' ,\n 'concavity_se' ,\n 'concave points_se' , \n 'symmetry_se' ,\n 'fractal_dimension_se' ,\n 'radius_worst' ,\n 'texture_worst' ,\n 'perimeter_worst' ,\n 'area_worst' ,\n 'smoothness_worst' ,\n 'compactness_worst' ,\n 'concavity_worst' ,\n 'concave points_worst' ,\n 'symmetry_worst' ,\n 'fractal_dimension_worst' ]\n\n col_names = ['id', \n 'diagnosis', \n 'radius_mean', \n 'texture_mean' , \n 'perimeter_mean', \n 'area_mean' , \n 'smoothness_mean', \n 'compactness_mean', \n 'concavity_mean' , \n 'concave points_mean', \n 'symmetry_mean' , \n 'fractal_dimension_mean', \n 'radius_se' , \n 'texture_se' , \n 'perimeter_se' , \n 'area_se' , \n 'smoothness_se' , \n 'compactness_se' ,\n 'concavity_se' ,\n 'concave points_se' , \n 'symmetry_se' ,\n 'fractal_dimension_se' ,\n 'radius_worst' ,\n 'texture_worst' ,\n 'perimeter_worst' ,\n 'area_worst' ,\n 'smoothness_worst' ,\n 'compactness_worst' ,\n 'concavity_worst' ,\n 'concave points_worst' ,\n 'symmetry_worst' ,\n 'fractal_dimension_worst' ]\n \n \n dataset = pd.read_csv('datasets/UCI Breast Cancer Wisconsin/wdbc.data', names=col_names)\n \n Y_df = dataset['diagnosis']\n Y_all = pd.DataFrame(Y_df)\n\n # process and change classes from M, B to 1, -1, respectively\n Y_all[Y_df == 'M'] = 1\n Y_all[Y_df == 'B'] = -1\n y_num = pd.to_numeric(Y_all['diagnosis'], errors='coerce')\n\n # X: features vector , Y: labels\n Y = y_num.to_numpy()\n X = dataset.drop(columns=['id','diagnosis']).to_numpy()\n\n return X, Y, features_labels\n\ndef add_bias(X):\n n_samples, n_features = np.shape(X)\n return np.asarray(np.c_[X, np.ones(n_samples)])\n\n\ndef unscale(X,scaler):\n # only one instance\n return X*scaler.scale_ + scaler.mean_\n\n\ndef bisection_chance(instance, prediction_instance, prototype, SVM, FM_transform, mu=0, lam=0, p=0.5, acc = 0.00001):\n \n factor = lam*np.sqrt(2)*np.log(2*(1-p))\n ub = prototype\n lb = instance\n \n results = []\n \n while np.linalg.norm(ub-lb) > acc:\n \n bi = (ub+lb)/2\n pred = SVM.predict(FM_transform.transform(bi.reshape(1, -1)), noise=mu)\n sign = np.sign(prediction_instance*pred - factor*np.linalg.norm(FM_transform.transform(bi.reshape(1, -1)),ord=2,axis=1))\n \n if sign < 0:\n ub = bi.copy()\n else:\n lb = bi.copy()\n \n results.append(sign*np.linalg.norm((ub-lb).reshape(1, -1),axis=1))\n \n results_array = np.asarray(results).flatten()\n \n return bi, results_array\n\n\ndef counterfactual_explanation_linear(instance, F, b):\n # Define and solve the CVXPY problem.\n x = cp.Variable(F)\n t = cp.Variable(1)\n\n # We use cp.SOC(t, x) to create the SOC constraint ||x||_2 <= t.\n soc_constraints = [cp.SOC(t, x - np.asarray(instance).flatten()), b.T @ cp.hstack([x,1]) <= 0]\n\n prob = cp.Problem(cp.Minimize(t), soc_constraints)\n prob.solve()\n\n return x.value\n\n\ndef socp_opt(instance, F, b):\n # Define and solve the CVXPY problem.\n x = cp.Variable(F)\n t = cp.Variable(1)\n\n # We use cp.SOC(t, x) to create the SOC constraint ||x||_2 <= t.\n soc_constraints = [cp.SOC(t, x - np.asarray(instance).flatten()), cp.SOC(b.T @ cp.hstack([x,1]), cp.hstack([x,1]) )]\n\n prob = cp.Problem(cp.Minimize(t), soc_constraints)\n prob.solve()\n\n return x.value\n \n\n\n","sub_path":"utils/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":4742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"378643761","text":"\"\"\"\n@name: Modules/Housing/Lighting/_test/test_lighting_controllers.py\n@author: D. Brian Kimmel\n@contact: D.BrianKimmel@gmail.com\n@copyright: (c) 2014-2019 by D. Brian Kimmel\n@license: MIT License\n@note: Created on Feb 21, 2014\n@summary: This module is for testing local node data.\n\nPassed all 6 tests - DBK - 2019-07-20\n\"\"\"\n\n__updated__ = '2019-07-21'\n\n# Import system type stuff\nfrom twisted.trial import unittest\nimport xml.etree.ElementTree as ET\n\n# Import PyMh files and modules.\nfrom test.testing_mixin import SetupPyHouseObj\nfrom test.xml_data import XML_LONG\n\n# from Modules.Core.data_objects import ControllerInformation\nfrom Modules.Core.Utilities import config_tools\nfrom Modules.Core.Utilities.config_tools import Yaml as configYaml\nfrom Modules.Families.family import API as familyAPI\nfrom Modules.Housing.Lighting.lighting_controllers import \\\n Config as controllerConfig, \\\n CONFIG_FILE_NAME\n\nfrom Modules.Core.Utilities.debug_tools import PrettyFormatAny\n\n\n# Import PyMh files and modules.\nclass SetupMixin(object):\n\n def setUp(self, p_root):\n self.m_pyhouse_obj = SetupPyHouseObj().BuildPyHouseObj(p_root)\n self.m_yaml = SetupPyHouseObj().BuildYaml(None)\n #\n self.m_family = familyAPI(self.m_pyhouse_obj).LoadFamilyTesting()\n self.m_pyhouse_obj._Families = self.m_family\n self.m_filename = CONFIG_FILE_NAME\n self.m_yamlconf = configYaml(self.m_pyhouse_obj)\n\n\nclass A0(unittest.TestCase):\n\n def test_00_Print(self):\n _x = PrettyFormatAny.form('_test', 'title', 190) # so it is defined when printing is cleaned up.\n print('Id: test_lighting_controllers')\n\n\nclass A1_Setup(SetupMixin, unittest.TestCase):\n\n def setUp(self):\n SetupMixin.setUp(self, ET.fromstring(XML_LONG))\n\n def test_01_PyHouse(self):\n \"\"\" Be sure that the XML contains the right stuff.\n \"\"\"\n self.assertEqual(self.m_pyhouse_obj.House.Irrigation, {})\n\n\nclass C1_ConfigRead(SetupMixin, unittest.TestCase):\n \"\"\" This section tests the reading and writing of XML used by lighting_controllers.\n \"\"\"\n\n def setUp(self):\n SetupMixin.setUp(self, ET.fromstring(XML_LONG))\n # self.m_controllers = controllerXML().read_all_controllers_xml(self.m_pyhouse_obj)\n # self.m_working_controllers = self.m_pyhouse_obj.House.Lighting.Controllers\n\n def test_01_Build(self):\n \"\"\" The basic read info as set up\n \"\"\"\n # print(PrettyFormatAny.form(self.m_working_controllers, 'C1-01-A - WorkingControllers'))\n # print(PrettyFormatAny.form(self.m_pyhouse_obj.House, 'C1-01-B - House'))\n # print(PrettyFormatAny.form(self.m_pyhouse_obj.House.Lighting, 'C1-01-C - Lighting'))\n # print(PrettyFormatAny.form(self.m_pyhouse_obj.House.Lighting.Controllers, 'C1-01-C - Controllers'))\n self.assertEqual(self.m_pyhouse_obj.House.Lighting.Controllers, None)\n\n def test_02_ReadFile(self):\n \"\"\" Read the rooms.yaml config file\n \"\"\"\n l_node = config_tools.Yaml(self.m_pyhouse_obj).read_yaml(self.m_filename)\n l_yaml = l_node.Yaml\n l_yamlcontrollers = l_yaml['Controllers']\n # print(PrettyFormatAny.form(l_node, 'C1-02-A - Node'))\n # print('C1-02-B - Yaml {}'.format(l_yaml['Controllers']))\n # print(PrettyFormatAny.form(l_yamlcontrollers, 'C1-02-C - YamlRooms'))\n self.assertEqual(l_yamlcontrollers[0]['Name'], 'Plm-1')\n self.assertEqual(len(l_yamlcontrollers), 3)\n\n def test_03_Load(self):\n \"\"\" Read the rooms.yaml config file\n \"\"\"\n controllerConfig().load_yaml_config(self.m_pyhouse_obj)\n l_test = self.m_pyhouse_obj.House.Lighting.Controllers\n # print(PrettyFormatAny.form(l_test, 'C1-03-A - Controllers'))\n # print(PrettyFormatAny.form(l_test[0], 'C1-03-B - Controllers'))\n # print(PrettyFormatAny.form(l_test[0].Family, 'C1-03-C - Controllers'))\n self.assertEqual(l_test[0].Name, 'Plm-1')\n self.assertEqual(l_test[0].Comment, 'A comment')\n self.assertEqual(l_test[0].Family.Name, 'Insteon')\n\n\nclass C2_YamlWrite(SetupMixin, unittest.TestCase):\n \"\"\" This section tests the reading and writing of XML used by lighting_controllers.\n \"\"\"\n\n def setUp(self):\n SetupMixin.setUp(self, ET.fromstring(XML_LONG))\n # self.m_controllers = controllerXML().read_all_controllers_xml(self.m_pyhouse_obj)\n\n def test_01_CreateJson(self):\n \"\"\" Create a JSON object for Location.\n \"\"\"\n\n# ## END DBK\n","sub_path":"Project/src/Modules/House/Lighting/_test/test_controllers.py","file_name":"test_controllers.py","file_ext":"py","file_size_in_byte":4526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"49871607","text":"import pathlib\n\nfrom cryptography.fernet import Fernet\n\ndef DecryptFernet(): \n \"\"\"\n Read secret key for Fernet cipher. \n Call object Fernet. Decrypt encrypted text\n\n :return str:\n \"\"\"\n with open(str(pathlib.Path(__file__).parents[1]) + '\\\\Resource\\\\FirstOfAll.key', 'rb') as File: \n SecretKey = File.read()\n Cipher = Fernet(SecretKey)\n with open(str(pathlib.Path(__file__).parents[1]) + '\\\\Resource\\\\Something.key', 'rb') as f: \n return str(Cipher.decrypt(f.read()).decode())","sub_path":"Package/Source/CryptoKey.py","file_name":"CryptoKey.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"418554986","text":"\"\"\"\nCode adjusted from https://gist.github.com/f0k/f3190ebba6c53887d598d03119ca2066#file-wgan_mnist-py\n\n\"\"\"\n\nfrom __future__ import (absolute_import, print_function)\n\nimport numpy as np\n\nimport theano\nimport theano.tensor as T\nimport lasagne\n\n# ##################### Build the neural network model #######################\n# We create two models: The generator and the critic network.\n# The models are the same as in the Lasagne DCGAN example, except that the\n# discriminator is now a critic with linear output instead of sigmoid output.\ndef rmsprop(cost, params, learning_rate, momentum=0.5, rescale=5.):\n \n grads = T.grad(cost=cost, wrt=params)\n \n running_square_ = [theano.shared(np.zeros_like(p.get_value(),dtype=p.dtype), broadcastable=p.broadcastable)\n for p in params]\n running_avg_ = [theano.shared(np.zeros_like(p.get_value(),dtype=p.dtype), broadcastable=p.broadcastable)\n for p in params]\n memory_ = [theano.shared(np.zeros_like(p.get_value(),dtype=p.dtype), broadcastable=p.broadcastable)\n for p in params]\n \n grad_norm = T.sqrt(sum(map(lambda x: T.sqr(x).sum(), grads)))\n not_finite = T.or_(T.isnan(grad_norm), T.isinf(grad_norm))\n grad_norm = T.sqrt(grad_norm)\n scaling_num = rescale\n scaling_den = T.maximum(rescale, grad_norm)\n # Magic constants\n combination_coeff = 0.9\n minimum_grad = 1E-4\n updates = []\n for n, (param, grad) in enumerate(zip(params, grads)):\n grad = T.switch(not_finite, 0.1 * param,\n grad * (scaling_num / scaling_den))\n old_square = running_square_[n]\n new_square = combination_coeff * old_square + (\n 1. - combination_coeff) * T.sqr(grad)\n old_avg = running_avg_[n]\n new_avg = combination_coeff * old_avg + (\n 1. - combination_coeff) * grad\n rms_grad = T.sqrt(new_square - new_avg ** 2)\n rms_grad = T.maximum(rms_grad, minimum_grad)\n memory = memory_[n]\n update = momentum * memory - learning_rate * grad / rms_grad\n\n update2 = momentum * momentum * memory - (\n 1 + momentum) * learning_rate * grad / rms_grad\n \n updates.append((old_square, new_square))\n updates.append((old_avg, new_avg))\n updates.append((memory, update))\n updates.append((param, param + update2))\n return updates\n\ndef build_generator(input_var=None):\n from lasagne.layers import InputLayer, ReshapeLayer, DenseLayer\n try:\n from lasagne.layers import TransposedConv2DLayer as Deconv2DLayer\n except ImportError:\n raise ImportError(\"Your Lasagne is too old. Try the bleeding-edge \"\n \"version: http://lasagne.readthedocs.io/en/latest/\"\n \"user/installation.html#bleeding-edge-version\")\n try:\n from lasagne.layers.dnn import batch_norm_dnn as batch_norm\n except ImportError:\n from lasagne.layers import batch_norm\n from lasagne.nonlinearities import sigmoid\n # input: 100dim\n layer = InputLayer(shape=(None, 100), input_var=input_var)\n # fully-connected layer\n layer = batch_norm(DenseLayer(layer, 1024))\n # project and reshape\n layer = batch_norm(DenseLayer(layer, 128*7*7))\n layer = ReshapeLayer(layer, ([0], 128, 7, 7))\n # two fractional-stride convolutions\n layer = batch_norm(Deconv2DLayer(layer, 64, 5, stride=2, crop='same',\n output_size=14))\n layer = Deconv2DLayer(layer, 1, 5, stride=2, crop='same', output_size=28,\n nonlinearity=sigmoid)\n print (\"Generator output:\", layer.output_shape)\n return layer\n\ndef build_critic(input_var=None):\n from lasagne.layers import (InputLayer, Conv2DLayer, ReshapeLayer,\n DenseLayer)\n try:\n from lasagne.layers.dnn import batch_norm_dnn as batch_norm\n except ImportError:\n from lasagne.layers import batch_norm\n from lasagne.nonlinearities import LeakyRectify\n lrelu = LeakyRectify(0.2)\n # input: (None, 1, 28, 28)\n layer = InputLayer(shape=(None, 1, 28, 28), input_var=input_var)\n # two convolutions\n layer = batch_norm(Conv2DLayer(layer, 64, 5, stride=2, pad='same',\n nonlinearity=lrelu))\n layer = batch_norm(Conv2DLayer(layer, 128, 5, stride=2, pad='same',\n nonlinearity=lrelu))\n # fully-connected layer\n layer = batch_norm(DenseLayer(layer, 1024, nonlinearity=lrelu))\n # output layer (linear and without bias)\n layer = DenseLayer(layer, 1, nonlinearity=None, b=None)\n print (\"critic output:\", layer.output_shape)\n return layer\n \n\nnum_epochs=100\nepochsize=100\nbatchsize=64\ninitial_eta=5e-5\nclip=0.01\n \nclass WGAN(object):\n \n def __init__(self, config):\n \n self.verbose = config['verbose']\n self.rank = config['rank']\n self.size = config['size']\n \n self.name = 'Wasserstein_GAN'\n \n # data\n from theanompi.models.data.mnist import MNIST_data\n\n self.data = MNIST_data(self.verbose)\n self.data.batch_data(batchsize)\n \n self.batch_size=batchsize\n self.file_batch_size=batchsize\n self.n_subb=self.file_batch_size//self.batch_size\n \n # model\n self.build_model()\n \n self.params = self.critic_params #+self.generator_params\n \n # training related\n self.epoch=0\n self.n_epochs=num_epochs\n \n self.generator_updates = 0\n self.critic_scores = []\n self.generator_scores = []\n self.c_list=[]\n self.g_list=[]\n self.current_info=None\n \n self.init_view=False\n \n def build_model(self):\n \n rng=np.random.RandomState(1234)\n lasagne.random.set_rng(rng)\n \n # Prepare Theano variables for inputs and targets\n self.noise_var = T.matrix('noise')\n self.input_var = T.tensor4('inputs')\n \n # Create neural network model\n generator = build_generator(self.noise_var)\n critic = build_critic(self.input_var)\n \n # Create expression for passing real data through the critic\n self.real_out = lasagne.layers.get_output(critic)\n # Create expression for passing fake data through the critic\n self.fake_out = lasagne.layers.get_output(critic,\n lasagne.layers.get_output(generator))\n \n \n # Create update expressions for training\n self.generator_params = lasagne.layers.get_all_params(generator, trainable=True)\n self.critic_params = lasagne.layers.get_all_params(critic, trainable=True)\n self.generator = generator\n self.critic = critic\n \n def compile_iter_fns(self, *args, **kwargs):\n \n \n eta = theano.shared(lasagne.utils.floatX(initial_eta))\n self.eta=eta\n self.shared_lr=eta\n \n \n loss_critic = self.real_out.mean() - self.fake_out.mean()\n critic_updates = rmsprop(\n -1*loss_critic, self.critic_params, learning_rate=eta)\n \n loss_gen = -1*self.fake_out.mean()\n generator_updates = rmsprop(\n loss_gen, self.generator_params, learning_rate=eta)\n \n \n # Clip critic parameters in a limited range around zero (except biases)\n critic_clip_updates=[]\n for param in lasagne.layers.get_all_params(self.critic, trainable=True,\n regularizable=True):\n \n critic_clip_updates.append([param, T.clip(param, -clip, clip)])\n \n \n # Instantiate a symbolic noise generator to use for training\n from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams\n srng = RandomStreams(seed=np.random.randint(2147462579, size=6))\n noise = srng.uniform((batchsize, 100))\n\n # Compile functions performing a training step on a mini-batch (according\n # to the updates dictionary) and returning the corresponding score:\n print('Compiling...')\n \n import time\n \n start = time.time()\n \n self.generator_train_fn = theano.function([], loss_gen,\n givens={self.noise_var: noise},\n updates=generator_updates)\n self.critic_train_fn = theano.function([self.input_var],loss_critic,\n givens={self.noise_var: noise},\n updates=critic_updates)\n self.critic_clip_fn = theano.function([],updates=critic_clip_updates)\n\n # Compile another function generating some data\n self.gen_fn = theano.function([self.noise_var],\n lasagne.layers.get_output(self.generator,\n deterministic=True))\n \n self.val_fn = theano.function([self.input_var], \n outputs=[loss_critic, loss_gen],\n givens={self.noise_var: noise})\n \n if self.verbose: print ('Compile time: %.3f s' % (time.time()-start))\n \n def train_iter(self, count, recorder):\n \n batches_train = self.data.batches_train\n\n if (self.generator_updates < 5) or (self.generator_updates % 100 == 0):\n critic_runs = 50\n print('update critic 50 times')\n else:\n critic_runs = 2\n \n c_score_list = []\n recorder.start()\n for _ in range(critic_runs):\n batch = next(batches_train)\n inputs, targets = batch\n c_score = self.critic_train_fn(inputs)\n c_score_list.append(c_score)\n self.critic_clip_fn()\n \n count+=1\n \n \n self.critic_scores.extend(c_score_list)\n g_score = self.generator_train_fn()\n self.generator_scores.append(g_score)\n self.generator_updates += 1\n \n recorder.train_error(count, sum(c_score_list)/len(c_score_list), g_score)\n recorder.end('calc')\n \n return count\n \n def val_iter(self, count, recorder):\n \n batches_val = self.data.batches_val\n \n batch = next(batches_val)\n \n inputs, targets = batch\n \n c_score, g_score = self.val_fn(inputs)\n \n recorder.val_error(count, c_score, g_score, 0) # print loss_critic, loss_gen and a 0 instead of cost, error and error_top_5 \n \n def reset_iter(self, *args, **kwargs):\n pass\n \n def print_info(self, recorder):\n \n print('\\nEpoch %d' % self.epoch)\n g_=np.mean(self.generator_scores)\n c_=np.mean(self.critic_scores)\n self.g_list.extend([g_])\n self.c_list.extend([c_])\n print(\" generator score:\\t\\t{}\".format(g_))\n print(\" Wasserstein distance:\\t\\t{}\".format(c_))\n \n self.critic_scores[:] = []\n self.generator_scores[:] = []\n \n samples = self.gen_fn(lasagne.utils.floatX(np.random.rand(42, 100)))\n samples = samples.reshape(6, 7, 28, 28).transpose(0, 2, 1, 3).reshape(6*28, 7*28)\n \n if self.init_view == False:\n \n self.init_view = True\n self.save_flag=False\n recorder.plot_init(name='scores', save=self.save_flag) # if save=True then pause=False\n \n recorder.plot_init(name='sample', save=self.save_flag)\n \n recorder.plot(name='sample', image=samples, cmap='gray')\n recorder.plot(name='scores', lines=[self.c_list,self.g_list], lw=2, save=self.save_flag) # if pause=True then save=False\n \n \n def adjust_hyperp(self, epoch):\n\n # After half the epochs, we start decaying the learn rate towards zero\n if epoch >= num_epochs // 2:\n progress = float(epoch) / num_epochs\n self.eta.set_value(lasagne.utils.floatX(initial_eta*2*(1 - progress)))\n \n def cleanup(self):\n \n pass\n \n \n def save(self, path='./'):\n \n import os\n if not os.path.exists(path):\n print('Creating folder: %s' % path)\n os.makedirs(path)\n \n np.savez(path+'%d_wgan_mnist_gen.npz' % self.epoch, *lasagne.layers.get_all_param_values(self.generator))\n np.savez(path+'%d_wgan_mnist_crit.npz' % self.epoch, *lasagne.layers.get_all_param_values(self.critic))\n \n def load(self, path_gen, path_cri):\n \n with np.load(path_gen) as f:\n param_values = [f['arr_%d' % i] for i in range(len(f.files))]\n lasagne.layers.set_all_param_values(self.generator, param_values)\n \n with np.load(path_cri) as f:\n param_values = [f['arr_%d' % i] for i in range(len(f.files))]\n lasagne.layers.set_all_param_values(self.critic, param_values)\n \nif __name__ == '__main__':\n \n raise RuntimeError('to be tested using test_model.py:\\n$ python test_model.py lasagne_model_zoo.wgan WGAN')\n ","sub_path":"theanompi/models/lasagne_model_zoo/wgan.py","file_name":"wgan.py","file_ext":"py","file_size_in_byte":13467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"208754197","text":"\"\"\"\n少数派的文章,按喜好数排序\n\"\"\"\nimport requests\nimport arrow\nimport looter as lt\n\ndomain = 'https://sspai.com'\n\n\ndef crawl(url):\n items = requests.get(url, headers=lt.DEFAULT_HEADERS).json()['list']\n for item in items:\n data = {}\n data['title'] = item['title']\n data['released_at'] = arrow.get(item['released_at']).naive\n data['summary'] = item['summary']\n data['words_count'] = item['words_count']\n data['likes_count'] = item['likes_count']\n data['favorites_count'] = item['favorites_count']\n data['comments_count'] = item['comments_count']\n data['url'] = f\"{domain}/post/{item['id']}\"\n yield data\n\n\nif __name__ == '__main__':\n tasklist = [f'{domain}/api/v1/articles?offset={n * 10}&limit=10&type=recommend_to_home&sort=recommend_to_home_at&include_total=false' for n in range(1170)]\n total = lt.crawl_all(crawl, tasklist)\n lt.save(total, name='sspai.csv', sort_by='likes_count', order='desc')\n","sub_path":"examples/sspai.py","file_name":"sspai.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"547011384","text":"# The MIT License (MIT)\n#\n# Copyright (c) 2016 Fabian Wenzelmann \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 shall be included in all\n# copies or substantial portions of the 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\n\nfrom django.shortcuts import render, redirect, render_to_response\nfrom django.http import HttpResponse, HttpResponseNotFound\nfrom django.utils import timezone\nfrom formtools.wizard.views import SessionWizardView, CookieWizardView\nfrom django.utils.safestring import mark_safe\nfrom django.template import loader\nfrom django.utils.translation import get_language\n\nimport uuid\nimport datetime\nfrom collections import defaultdict\n\nfrom ordered_set import OrderedSet\n\nfrom .forms import PollFormGeneral, PollFormDates, PollFormText, PollFormTimes, PollFormCaptcha\nfrom .models import Poll, DateTimeOption, FreeTextOption, WholeDayOption, Answer, FirstAnswered\nfrom . import filters\nfrom .settings import get_foodle_setting\n\n# Create your views here.\n\n\ndef show_poll(request, poll_id):\n # get poll with the given id\n polls = Poll.objects.filter(poll_id=poll_id)\n if not polls:\n template = loader.get_template('foodle_polls/poll_not_found.html')\n context = {'poll_id': poll_id}\n return HttpResponseNotFound(template.render(context, request))\n # get the poll with the id, through the unique keywords it's secured that\n # there's only one\n poll = polls[0]\n context = {'poll': poll}\n if poll.freetext:\n return _show_freetext(request, poll, context)\n else:\n # first get all options\n\n # get all datetime options for this poll\n time_options = DateTimeOption.objects.filter(\n poll=poll).order_by('choice_time')\n time_options = [d.choice_time for d in time_options]\n # get all whole day options for that poll\n whole_day_options = WholeDayOption.objects.filter(\n poll=poll).order_by('choice_day')\n whole_day_options = [d.choice_day for d in whole_day_options]\n # now we have to merge the sorted lists\n sorted_dates, datetime_mappings = _merge_sorted_dates(\n time_options, whole_day_options)\n context['sorted_dates'] = sorted_dates\n context['datetime_mappings'] = datetime_mappings\n return render(request, 'foodle_polls/base_show_poll_date.html', context=context)\n\n\ndef _normalize_length(choice, required_len):\n if len(choice) < required_len:\n return choice + [0] * (required_len - len(choice))\n elif len(choice) > required_len:\n return choice[:required_len]\n else:\n # should never be reached, method usually only called when size does\n # not fit\n return choice\n\n\ndef _get_sorted_users(poll):\n users = FirstAnswered.objects.filter(poll=poll).order_by('time_posted')\n return OrderedSet([(user.user, user.user_id) for user in users])\n\n\ndef _show_freetext(request, poll, context):\n # first get the options\n options = FreeTextOption.objects.filter(poll=poll)\n context['options'] = options\n # get all answers\n # for this we create a dictionary that maps username -> list of answers\n answers_dict = defaultdict(list)\n for option in options:\n answers = Answer.objects.filter(option=option)\n for answer in answers:\n # add to the user's list\n answers_dict[answer.user].append(answer)\n # check if each user has been found with the right amount of answers\n # i.e. one for each option\n # hopefully this never happen\n for user, choice in list(answers_dict.items()):\n if len(choice) != len(options):\n # TODO do something more useful? display warning?\n print('Answer has wrong length!')\n answers_dict[user] = _normalize_length(choice, len(options))\n context['answers'] = answers_dict\n # check if poll is hidden\n if poll.hidden:\n return render(request, 'foodle_polls/show_locked_free.html', context=context)\n else:\n return render(request, 'foodle_polls/base_show_poll_free.html', context=context)\n\n\ndef _merge_sorted_dates(datetimes, dates):\n res = []\n date_dict = defaultdict(list)\n i, j = 0, 0\n while i < len(datetimes) and j < len(dates):\n nxt_datetime = datetimes[i]\n nxt_datetime_date = nxt_datetime.date()\n nxt_date = dates[j]\n\n # check which one is smaller, insert this one next\n if nxt_datetime_date < nxt_date:\n # insert nxt_datetime\n # but take care if this date is already present, we don't want\n # any duplicates\n if not res or res[-1] != nxt_datetime_date:\n res.append(nxt_datetime_date)\n date_dict[nxt_datetime_date].append(nxt_datetime)\n i += 1\n else:\n # insert nxt_date\n # again check for duplicates\n if not res or res[-1] != nxt_date:\n res.append(nxt_date)\n j += 1\n # append all remaining elements\n while i < len(datetimes):\n nxt_datetime = datetimes[i]\n nxt_datetime_date = nxt_datetime.date()\n\n # again to be sure check for duplicates\n if not res or res[-1] != nxt_datetime_date:\n res.append(nxt_datetime_date)\n date_dict[nxt_datetime_date].append(nxt_datetime)\n i += 1\n\n while j < len(dates):\n nxt_date = dates[j]\n # duplicates\n if not res or res[-1] != nxt_date:\n res.append(nxt_date)\n j += 1\n # the result values now contain the following:\n # res is a list of all sorted dates (without time!)\n # the list does not contain duplicates\n\n # date_dict contains all entries for datetimes, but not for whole day\n # options\n\n # in the case that there is a date that would appear as an whole day option\n # AND as a date in a DateTimeField that day would be considered as datetimes\n # however this should never happen and so should never cause any problem\n # at all\n return res, date_dict\n\n\ndef show_poll_admin(request, admin_id):\n if not Poll.objects.filter(admin_id=admin_id):\n template = loader.get_template(\n 'foodle_polls/admin_poll_not_found.html')\n context = {'admin_id': admin_id}\n return HttpResponseNotFound(template.render(context, request))\n return HttpResponse(admin_id)\n\n\ndef about(request):\n return render(request, 'foodle_polls/about.html')\n\nCREATE_FORMS = [\n PollFormGeneral,\n PollFormText,\n PollFormDates,\n PollFormTimes,\n PollFormCaptcha,\n]\n\nCREATE_TEMPLATES = {\n '0': 'foodle_polls/new_poll.html',\n '1': 'foodle_polls/new_poll_text.html',\n '2': 'foodle_polls/new_poll_dates.html',\n '3': 'foodle_polls/new_poll_times.html',\n '4': 'foodle_polls/create_captcha.html'\n}\n\n\ndef do_free(wizard):\n cleaned_data = wizard.get_cleaned_data_for_step('0') or {'freetext': False}\n return cleaned_data['freetext']\n\n\ndef do_date(wizard):\n return not do_free(wizard)\n\n\nclass NewPollWizard(SessionWizardView):\n form_list = CREATE_FORMS\n condition_dict = {\n '1': do_free,\n '2': do_date,\n '3': do_date,\n '4': lambda wizard: get_foodle_setting(\n 'captcha')}\n\n def get_template_names(self):\n return [CREATE_TEMPLATES[self.steps.current]]\n\n def done(self, form_list, **kwargs):\n forms = list(form_list)\n general_data = forms[0].cleaned_data\n poll = forms[0].save(commit=False)\n poll.pub_date = timezone.now()\n # TODO catch exceptions that can occur in the gen_..._id methods\n poll.poll_id = Poll.gen_poll_id()\n poll.admin_id = Poll.gen_admin_id()\n poll.save()\n # TODO save_m2m()?\n if (general_data['freetext']):\n freetext_data = forms[1].cleaned_data['choices']\n for choice in freetext_data:\n option = FreeTextOption(poll=poll, choice_text=choice)\n option.save()\n else:\n time_data = forms[2].cleaned_data\n for timed, d in time_data['times']:\n if timed:\n option = DateTimeOption(poll=poll, choice_time=d)\n option.save()\n else:\n # initialize with some random hours and minutes\n option = WholeDayOption(poll=poll, choice_day=d)\n option.save()\n return render_to_response('foodle_polls/success.html',\n {'poll_id': poll.poll_id, 'admin_id': poll.admin_id})\n\n def get_selected_dates(self):\n cleaned_data = self.get_cleaned_data_for_step('2') or {'dates': []}\n return str([d.isoformat() for d in cleaned_data['dates']])\n\n def get_context_data(self, form, **kwargs):\n context = super(\n NewPollWizard,\n self).get_context_data(\n form=form,\n **kwargs)\n context.update({'language': get_language()})\n if self.steps.current == '3':\n context.update({'selected_dates': self.get_selected_dates()})\n return context\n","sub_path":"foodle/foodle_polls/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"502494031","text":"import cv2\nimport numpy as np\nimport scipy.ndimage\nimport desc\n\nfrom color import color, print_images\nfrom harris import findCorners\nfrom minMax import findKeyPoints\n\nRESIZE_COEFF = np.sqrt(2)\n\n\ndef makeDiff(img1, img2):\n return cv2.absdiff(img1, img2)\n\n\ndef getDiffOctaves(octaves):\n res = [[[] for j in range(len(octaves[i]) - 1)] for i in range(len(octaves))]\n for i, blurs in enumerate(octaves):\n for j, _ in enumerate(blurs):\n if (j == (len(blurs) - 1)):\n continue\n tmpImage = makeDiff(blurs[j], blurs[j + 1])\n res[i][j] = tmpImage\n return res\n\n\ndef cleanKp(kps, octaves):\n for i in range(len(kps)):\n for j in range(0, len(kps[i])):\n kpList = kps[i][j]\n kps[i][j] = findCorners(octaves[i][0], kpList, printCorner=False)\n\n\ndef flattenKps(kps):\n res = []\n for i in range(len(kps)):\n for j in range(0, len(kps[i])):\n for kp in kps[i][j]:\n tmp = kp\n tmp[0] = int(tmp[0] * RESIZE_COEFF ** i)\n tmp[1] = int(tmp[1] * RESIZE_COEFF ** i)\n res.append(tmp)\n return res\n\n\ndef doSift(img):\n print('Start building octaves')\n octaves = getOctaves(img)\n for i, o in enumerate(octaves):\n if i < 2:\n continue\n print_images(o, name=str(i) + 'th Octave ', resize=False)\n print('Start diff of octaves')\n diffOctaves = getDiffOctaves(octaves)\n for i, o in enumerate(diffOctaves):\n if i < 2:\n continue\n print_images(o, name=str(i) + 'th Octave DoG ', resize=False)\n print('Start find key points')\n kps = findKeyPoints(diffOctaves)\n print('Remove non-pertinent key-points')\n cleanKp(kps, octaves)\n flatKps = flattenKps(kps)\n print('Build descriptor for key-points')\n descriptors = getDescriptors(octaves, flatKps)\n return descriptors, flatKps\n\n\ndef getDescriptors(octaves, flatKps):\n return desc.descriptor().create_descriptors(flatKps, octaves[0][0])\n\n\ndef getOctaves(img, nbOctaves=4, nbBlur=5, sig=1.6):\n res = [[[] for j in range(nbBlur)] for i in range(nbOctaves)]\n tmpImg = img.copy()\n for x in range(nbOctaves):\n for y in range(nbBlur):\n pass\n res[x][y] = scipy.ndimage.filters.gaussian_filter(tmpImg, sig ** (y + 1))\n tmpImg = cv2.resize(tmpImg, dsize=(0, 0), fx=1 / RESIZE_COEFF, fy=1 / RESIZE_COEFF)\n return res\n","sub_path":"src/mySift.py","file_name":"mySift.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"434375194","text":"#coding:utf-8\nfrom .apicore import ApiCore\nimport time\n#from user import ApiUser\n\nclass ApiGame(ApiCore):\n u\"\"\"获取比赛信息\n \"\"\"\n def __repr__(self):\n return self.__str__()\n def __str__(self):\n s = u\"\"\n try:\n s = s.encode(\"utf-8\").decode(\"utf-8\")\n except UnicodeEncodeError:\n pass\n else:\n s = s.encode(\"utf-8\")\n return s\n\n def calcultime(self,time):\n \"\"\"用来计算比赛的持续时间,升级时间和一血时间\n\n \"\"\"\n h = time/3600\n m = time%3600/60\n s = time%60\n H=\"\"\n M=\"\"\n S=\"\"\n if h == 0:\n H = \"00:\"\n else:\n H = str(h)+\":\"\n if m == 0:\n M = \"00:\"\n else:\n M = str(m)+\":\"\n if s == 0:\n S = \"00\"\n else:\n S = str(s)\n\n return H+M+S\n\n def __init__(self,id):\n u\"\"\"一场比赛\n 主要的信息有:\n winner -- 胜方\n start_time -- 开始时间\n duration -- 持续时间\n match_seq_num -- 比赛记录号\n cluster -- 主机集群号\n first_blood_time -- 一血时间\n lobby_type -- 对战类型\n human_players -- 非机器人玩家数\n leagueid -- 联赛id(0标示不是联赛)\n positive_votes -- 给赞数\n negative_votes -- 竖中指数\n game_mode 比赛模式(all pick之类)\n engine -- 游戏引擎\n players -- 玩家信息:\n |\n |--key:id---|\n |-playerinfo:对应的ApiUser对象\n |-hero:所选英雄\n |-item_0..item_5:6格装备信息\n |-kills:击杀数\n |-deaths:死亡数\n |-assists:助攻数\n |-leaver_status:离开状态,不明,估计是是否离线\n |-gold:游戏结束时的余钱\n |-last_hits:正补\n |-denies:反补\n |-gold_per_min:每分钟收入\n |-xp_per_min:每分钟经验\n |-gold_spent:一共花费金币\n |-hero_damage:对英雄造成的伤害量\n |-tower_damage:对塔造成的伤害量\n |-hero_healing:对英雄治疗量\n |-level:最终等级\n |-ability_upgrades:每级升级时间和选择的技能\n\n tower_status -- 塔信息(需换成2进制)\n |\n |-┌─┬─┬─┬─┬─────────────────────── Not used.\n │ │ │ │ │ ┌───────────────────── Ancient Top\n │ │ │ │ │ │ ┌─────────────────── Ancient Bottom\n │ │ │ │ │ │ │ ┌───────────────── Bottom Tier 3\n │ │ │ │ │ │ │ │ ┌─────────────── Bottom Tier 2\n │ │ │ │ │ │ │ │ │ ┌───────────── Bottom Tier 1\n │ │ │ │ │ │ │ │ │ │ ┌─────────── Middle Tier 3\n │ │ │ │ │ │ │ │ │ │ │ ┌───────── Middle Tier 2\n │ │ │ │ │ │ │ │ │ │ │ │ ┌─────── Middle Tier 1\n │ │ │ │ │ │ │ │ │ │ │ │ │ ┌───── Top Tier 3\n │ │ │ │ │ │ │ │ │ │ │ │ │ │ ┌─── Top Tier 2\n │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ┌─ Top Tier 1\n │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │\n 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n barracks_status -- 兵营信息(需换成2进制)\n |\n |- ┌─┬───────────── Not used.\n │ │ ┌─────────── Bottom Ranged\n │ │ │ ┌───────── Bottom Melee\n │ │ │ │ ┌─────── Middle Ranged\n │ │ │ │ │ ┌───── Middle Melee\n │ │ │ │ │ │ ┌─── Top Ranged\n │ │ │ │ │ │ │ ┌─ Top Melee\n │ │ │ │ │ │ │ │\n 0 0 0 0 0 0 0 0\n\n \"\"\"\n #ApiCore.init()\n ApiCore.__init__(self)\n ApiGame.init()\n self.id = id\n kws=\"&match_id=\"+str(self.id)\n url = ApiCore.URL.format(INTERFACES=ApiCore.FUNCTION[\"getmatchinfo\"][0],\n METHOD=ApiCore.FUNCTION[\"getmatchinfo\"][1],\n VERSION=ApiCore.FUNCTION[\"getmatchinfo\"][2],\n API_KEY=ApiCore.API_KEY,\n KWS=kws\n )\n info=ApiCore.submit(url)['result']\n self.players = info[\"players\"]\n self.winner= u\"夜魇\" if info[\"radiant_win\"]==False else u\"天辉\"\n self.start_time=time.ctime(info[\"start_time\"])\n self.duration=self.calcultime(info[\"duration\"])\n self.match_seq_num = info[\"match_seq_num\"]\n self.cluster = info[\"cluster\"]\n self.first_blood_time = self.calcultime(info[\"first_blood_time\"])\n self.lobby_type = info[\"lobby_type\"]\n self.human_players = info[\"human_players\"]\n self.leagueid = info[\"leagueid\"]\n self.positive_votes = info[\"positive_votes\"]\n self.negative_votes = info[\"negative_votes\"]\n self.engine = info[\"engine\"]\n\n mode = {0:\"Unknown\",\n 1:\"All Pick\",\n 2:\"Captains Mode\",\n 3:\"Random Draft\",\n 4:\"Single Draft\",\n 5:\"All Random\",\n 6:\"?? INTRO/DEATH ??\",\n 7:\"The Diretide\",\n 8:\"Reverse Captains Mode\",\n 9:\"Greeviling\",\n 10:\"Tutorial\",\n 11:\"Mid Only\",\n 12:\"Least Played\",\n 13:\"New Player Pool\",\n 14:\"Compendium Matchmaking\",\n 15:\"Custom\",\n 16:\"Captains Draft\",\n 17:\"Balanced Draft\",\n 18:\"Ability Draft\",\n 19:\"?? Event ??\",\n 20:\"All Random Death Match\",\n 21:\"1vs1 Solo Mid\",\n 22:\"Ranked All Pick\"\n }\n self.game_mode=mode[info[\"game_mode\"]]\n self.tower_status_radiant=info[\"tower_status_radiant\"]\n self.tower_status_dire=info[\"tower_status_dire\"]\n self.barracks_status_radiant=info[\"barracks_status_radiant\"]\n self.barracks_status_dire=info[\"barracks_status_dire\"]\n","sub_path":"dota2analysis/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":7424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"283463440","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api\n\nclass atabla(models.Model):\n _name = 'jessenia.atabla'\n\n name = fields.Char(string=\"Nombre\")\n age = fields.Integer(string=\"Edad\")\n promedio = fields.Float(string=\"Promedio\")\n tablab = fields.Many2one('jessenia.btabla',string=\"tabla B\")\n\nclass btabla(models.Model):\n _name='jessenia.btabla'\n\n name = fields.Char(string=\"Provincia\")\n province = fields.Selection([('a','Ambato'),('b','Baños'),('c','Pelileo')],'Ciudades')\n\n# @api.depends('value')\n# def _value_pc(self):\n# self.value2 = float(self.value) / 100\n","sub_path":"jessenia/models/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"465019536","text":"#PROJECT ONE\n\nfilename = \"accessLog.txt\" #for demonstration I put my access log in a txt file\nfile = open(filename, \"r\")\nfor line in file:\n if \"blank.php\" in line:\n request = line.split(\",\")\n for line in request:\n x = line\n data = x[78:len(x)]\n print(x)\n print(\"DATA=\"+data)\n \n","sub_path":"SecurityIIproject1.py","file_name":"SecurityIIproject1.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"345364749","text":"#!/usr/bin/env python\n\nimport csv\nimport json\nimport re\nimport urllib.request\n\nfrom pathlib import Path\n\nfrom common import load_from_file, tostring\n\nSKILLS = [\n ('Acrobatics', 'acrobatics'),\n ('Animal Handling', 'animal-handling'),\n ('Arcana', 'arcana'),\n ('Athletics', 'athletics'),\n ('Deception', 'deception'),\n ('History', 'history'),\n ('Insight', 'insight'),\n ('Intimidation', 'intimidation'),\n ('Investigation', 'investigation'),\n ('Medicine', 'medicine'),\n ('Nature', 'nature'),\n ('Perception', 'perception'),\n ('Performance', 'performance'),\n ('Persuasion', 'persuasion'),\n ('Religion', 'religion'),\n ('Sleight of Hand', 'sleight-of-hand'),\n ('Stealth', 'stealth'),\n ('Survival', 'survival'),\n]\n\nprinted = [\n 'cult fanatic',\n 'cultist',\n 'guard',\n 'ogrillon (half-ogre)',\n 'outland veteran',\n 'scholar',\n 'scout',\n 'skeleton'\n 'sprite',\n 'thug',\n 'warlock initiate of the fiend',\n 'wolf',\n 'zombie',\n 'gnoll', 'gnoll pack lord', 'harpy', 'commoner',\n 'faskar the fallen', 'tomi norelon',\n # smaller font\n 'gnoll flesh gnawer', 'gnoll hunter', 'gnoll witherling', 'ghoul',\n 'shadow', 'shadow (wolf)',\n 'hyena', 'ghast', 'scarecrow', 'cockatrice',\n 'green hag', 'ghost',\n 'warlock of the archfey', 'master thief', 'scoundrel', 'pixie', 'imp', 'rat', 'spider', 'raven'\n 'bandit', 'dire wolf', 'druid', 'giant spider', 'swarm of bats', 'swarm of ravens', \"will-o'-wisp\",\n 'needle blight', 'twig blight', 'vine blight', 'werewolf',\n 'assassin', 'beserker', 'bandit captain', 'strahd zombie', 'revenant', 'vampire spawn',\n 'gladiator', 'veteran', 'spy', 'wereraven',\n 'night hag',\n 'dretch', 'nightmare',\n 'owl',\n 'imp',\n 'quasit',\n 'young blue dragon',\n]\n\nTO_PRINT = [\n 'magician',\n 'bat',\n 'redcap',\n 'ogre zombie',\n]\n\ndef include(row):\n \"\"\"\n Use this function to filter the items processed.\n \"\"\"\n name = row['name'].lower()\n if name in TO_PRINT:\n return True\n return False\n # return True\n\ndef get_tags(row):\n tags = [row['size'], row['type']]\n if row.get('legendary_actions'):\n tags.append('legendary')\n if row.get('subtype'):\n tags.append(row['subtype'])\n return tags\n\n\ndef cr_stats(row):\n cr_span = '{}, CR: {}'\n cr = row['challenge_rating']\n if 'xp' in row:\n xp = row['xp']\n else:\n xp = {\n 0: '10', 14: '11500',\n 0.125: '25', 15: '13000',\n 0.25: '50', 16: '15000',\n 0.5: '100', 17: '18000',\n 1: '200', 18: '20000',\n 2: '450', 19: '22000',\n 3: '700', 20: '25000',\n 4: '1100', 21: '33000',\n 5: '1800', 22: '41000',\n 6: '2300', 23: '50000',\n 7: '2900', 24: '62000',\n 8: '3900', 25: '75000',\n 9: '5000', 26: '90000',\n 10: '5900', 27: '105000',\n 11: '7200', 28: '120000',\n 12: '8400', 29: '135000',\n 13: '10000', 30: '155000',\n }[cr]\n if cr == 0.125:\n cr = '1/8'\n if cr == 0.25:\n cr = '1/4'\n if cr == 0.5:\n cr = '1/2'\n\n alignment = row['alignment']\n if alignment.lower() != \"any alignment\":\n alignment = re.sub(r'\\s*alignment\\s*', ' ', alignment, re.I).strip()\n\n return cr_span.format(alignment, cr)\n\n\ndef stats(row):\n _, colour = get_icon_and_colour(row)\n div_style = 'style=\"width:33%;float:left\"'\n stat_style = 'style=\"color:{};font-size:180%\"'.format(colour)\n template = '
{title}
{value}

{description}
'\n\n armour = row.get('armor', '') or row.get('armour')\n hit_dice = row['hit_dice']\n speeds = [re.sub(r'\\s*ft\\.?', '', x).strip() for x in row['speed'].split(',')]\n speed = 'NA'\n extra_speeds = ''\n if speeds:\n speed = speeds[0]\n if len(speeds) > 1:\n extra_speeds = ', '.join(speeds[1:])\n\n if not (hit_dice == '' and armour == '' and extra_speeds == ''):\n hit_dice = hit_dice or ' '\n armour = armour or ' '\n extra_speeds = extra_speeds or ' '\n\n ac_div = template.format(div_style=div_style,\n title='Armour Class',\n stat_style=stat_style,\n value=row['armor_class'],\n description=armour)\n\n hp_div = template.format(div_style=div_style,\n title='Hit Points',\n stat_style=stat_style,\n value=row['hit_points'],\n description=hit_dice)\n\n cr_div = template.format(div_style=div_style,\n title='Speed',\n stat_style=stat_style,\n value=speed,\n description=extra_speeds)\n\n return 'text |
{}{}{}
'.format(ac_div, hp_div, cr_div)\n\n\ndef dnd_stats(row):\n return 'dndstats | {} | {} | {} | {} | {} | {}'.format(row['strength'],\n row['dexterity'],\n row['constitution'],\n row['intelligence'],\n row['wisdom'],\n row['charisma'])\n\n\ndef attributes(row):\n lines = []\n\n # Saving throws\n saving = []\n for key in ('strength', 'dexterity', 'constitution', 'intelligence', 'wisdom', 'charisma'):\n if key + '_save' in row:\n name = key[0].upper() + key[1:]\n value = row[key + '_save']\n saving.append('{} +{}'.format(name, value))\n if saving:\n lines.append('property | Saves | ' + ', '.join(saving))\n\n # Skills\n skills = []\n for name, key in SKILLS:\n if key in row:\n skills.append('{} +{}'.format(name, row[key]))\n if skills:\n lines.append('property | Skills | ' + ', '.join(skills))\n\n # Others\n for name, key in [\n ('Damage vulnerabilities', 'damage_vulnerabilities'),\n ('Damage resistances', 'damage_resistances'),\n ('Damage immunities', 'damage_immunities'),\n ('Condition immunities', 'condition_immunities'),\n ('Senses', 'senses'),\n ('Languages', 'languages'),\n ]:\n if row.get(key):\n lines.append('property | {} | {}'.format(name, row[key]))\n\n if len(lines) > 0:\n lines.append('rule')\n return lines\n\n\ndef description(row):\n if 'description' in row:\n return [\n # 'fill | 2',\n 'rule',\n 'text | {}'.format(row['description']),\n ]\n return []\n\n\ndef abilities(row):\n lines = []\n for key, title in [\n ('special_abilities', ''),\n ('actions', 'Actions'),\n ('reactions', 'Reactions'),\n ('legendary_actions', 'Legendary Actions'),\n ]:\n if key in row:\n if title:\n lines.append('section | ' + title)\n for x in row[key]:\n lines.append('property | {} | {}'.format(x['name'], tostring(x['desc'])))\n\n return lines\n\n\ndef get_icon_and_colour(row):\n icon, colour = {\n 'aberration': ('suckered-tentacle', 'rebeccapurple'),\n 'beast': ('lion', 'saddlebrown'),\n 'celestial': ('angel-outfit', 'darkgoldenrod'),\n 'construct': ('robot-golem', 'slategray'),\n 'dragon': ('dragon-head', 'darkred'),\n 'elemental': ('unfriendly-fire', 'teal'),\n 'fey': ('unicorn', 'olive'),\n 'fiend': ('imp', 'orangered'),\n 'giant': ('giant', 'steelblue'),\n 'humanoid': ('person', 'indianred'),\n 'monstrosity': ('hydra', 'darkmagenta'),\n 'ooze': ('slime ', 'darkslategray'),\n 'plant': ('carnivorous-plant', 'darkgreen'),\n 'swarm of Tiny beasts': ('hydra-shot', 'darksalmon'),\n 'undead': ('shambling-zombie', 'black'),\n }.get(row['type'], (None, None))\n\n if row.get('icon'):\n icon = row['icon']\n else:\n print(\"Using default icon for {}\".format(row['name']))\n\n if icon is None:\n print(\"Can't find icon or colour for '{}'\".format(row['type']))\n return 'imp-laugh', 'red'\n\n return icon, colour\n\n\ndef convert(row):\n title = row['name']\n tags = get_tags(row)\n\n classification = '{size} {type}'.format(**row)\n if row.get('subtype') not in (None, \"\", \"any race\"):\n classification += ' ({})'.format(row['subtype'])\n\n classification += cr_stats(row)\n\n caption = ''\n if row.get('picture'):\n caption = classification\n contents = []\n else:\n contents = ['subtitle | {}'.format(classification), 'rule']\n\n contents += [\n stats(row),\n 'rule',\n dnd_stats(row),\n 'rule',\n ] + attributes(row) + abilities(row) + [\n 'fill | 2'\n ] + description(row)\n\n icon, colour = get_icon_and_colour(row)\n data = {\n 'count': 1,\n 'color': colour,\n 'title': title,\n 'icon': icon,\n 'picture': row.get('picture', ''),\n 'picture_flex_ratio': row.get('picture_flex_ratio') or row.get('picture_ratio'),\n 'caption': caption,\n 'contents': contents,\n 'tags': tags,\n }\n if row.get('title_size'):\n data['title_size'] = row['title_size']\n return data\n\n\ndef write_json(data, outfile):\n # data = sorted(data, key=lambda x: x['name'])\n with open(outfile, 'w') as fh:\n json.dump(data, fh, indent=2)\n\n\ndef main(folder, outfile):\n data = []\n for infile in Path(folder).iterdir():\n print(infile)\n for row in load_from_file(infile):\n if include(row):\n data.append(convert(row))\n\n write_json(data, outfile)\n\n\nif __name__ == '__main__':\n main('sources/monsters', 'monsters.json')\n","sub_path":"convert_monsters.py","file_name":"convert_monsters.py","file_ext":"py","file_size_in_byte":10359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"48283500","text":"#!/usr/bin/python\n# Copyright (c) 2021 Wind River Systems, Inc.\n#\n# SPDX-License-Identifier: Apache-2.0\n#\n# This script will remove snmp related data (icommunity and\n# itrapdest) in dcorch database according to the host based\n# SNMP removal in preparation for upgrade from release 20.06.\n#\n\n\nimport psycopg2\nimport sys\nfrom controllerconfig.common import log\nfrom psycopg2.extras import RealDictCursor\n\nLOG = log.get_logger(__name__)\n\n\ndef main():\n action = None\n from_release = None\n to_release = None\n arg = 1\n while arg < len(sys.argv):\n if arg == 1:\n from_release = sys.argv[arg]\n elif arg == 2:\n to_release = sys.argv[arg]\n elif arg == 3:\n action = sys.argv[arg]\n else:\n print (\"Invalid option %s.\" % sys.argv[arg])\n return 1\n arg += 1\n\n log.configure()\n\n LOG.debug(\"%s invoked with from_release = %s to_release = %s action = %s\"\n % (sys.argv[0], from_release, to_release, action))\n\n if from_release == \"20.06\" and action == \"migrate\":\n try:\n if is_system_controller():\n LOG.info(\"Performing dcorch snmp data removal...\")\n remove_snmp_record()\n except Exception as ex:\n LOG.exception(ex)\n print(ex)\n return 1\n\n\ndef is_system_controller():\n with open('/etc/platform/platform.conf', 'r') as f:\n lines = f.readlines()\n\n for line in lines:\n if line.strip() == 'distributed_cloud_role=systemcontroller':\n return True\n\n return False\n\n\ndef remove_snmp_in_orch_request(cur, job_id):\n # Check if the record exists in orch_request\n cur.execute(\"select * from orch_request where orch_job_id = '%d'\" %\n job_id)\n orch_request = cur.fetchall()\n if orch_request:\n cur.execute(\"delete from orch_request where orch_job_id = '%d'\" %\n job_id)\n LOG.info(\"icommunity/itrapdest is removed in orch_request.\")\n else:\n LOG.info(\"There is no icommunity/itrapdest in orch_request.\")\n\n\ndef remove_snmp_in_orch_job(cur, master_id):\n # Check if the record exists in orch_job\n cur.execute(\"select * from orch_job where source_resource_id = '%s'\" %\n master_id)\n orch_job = cur.fetchall()\n if orch_job:\n for orch_job_record in orch_job:\n remove_id = orch_job_record['id']\n remove_snmp_in_orch_request(cur, remove_id)\n cur.execute(\"delete from orch_job where id = %d\" % (remove_id))\n LOG.info(\"icommunity is removed in orch_job.\")\n else:\n LOG.info(\"There is no icommunity/itrapdest in orch_job.\")\n\n\ndef remove_snmp_in_subcloud_resource(cur, master_id):\n # Check if the record exists in subcloud_resource\n cur.execute(\"select * from subcloud_resource \"\n \"where subcloud_resource_id = '%s'\" % (master_id))\n resource_subcloud = cur.fetchall()\n if resource_subcloud:\n cur.execute(\"delete from subcloud_resource \"\n \"where subcloud_resource_id = '%s'\" % (master_id))\n LOG.info(\"icommunity is removed in subcloud_resource.\")\n else:\n LOG.info(\"There is no icommunity/itrapdest in subcloud_resource.\")\n\n\ndef remove_snmp_record():\n conn = psycopg2.connect(\"dbname='dcorch' user='postgres'\")\n with conn:\n with conn.cursor(cursor_factory=RealDictCursor) as cur:\n # Check if any icommunity or itrapdest record exists\n cur.execute(\"select * from resource where resource_type in \"\n \"('icommunity','itrapdest')\")\n resource_records = cur.fetchall()\n if not resource_records:\n LOG.info(\"Nothing to do - \"\n \"there is no icommunity/itrapdest in resource.\")\n return\n for data_resource in resource_records:\n master_id = data_resource['master_id']\n remove_snmp_in_subcloud_resource(cur, master_id)\n remove_snmp_in_orch_job(cur, master_id)\n cur.execute(\"delete from resource \"\n \"where master_id = '%s'\" % (master_id))\n LOG.info(\"icommunity/itrapdest is removed from resource.\")\n LOG.info(\"snmp community and trapdest data removal completed.\")\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"controllerconfig/controllerconfig/upgrade-scripts/96-delete-snmp-records.py","file_name":"96-delete-snmp-records.py","file_ext":"py","file_size_in_byte":4368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"305695788","text":"import copy\nimport logging\n\nfrom . import exceptions\nfrom . import utils\n\n\ndefaults = {\n 'access_token_name': 'access_token',\n 'algorithm': 'HS256',\n 'authorization_header': 'authorization',\n 'authorization_header_prefix': 'Bearer',\n 'authorization_header_refresh_prefix': 'Refresh',\n 'claim_aud': None,\n 'claim_iat': False,\n 'claim_iss': None,\n 'claim_nbf': False,\n 'claim_nbf_delta': 0,\n 'cookie_domain': '',\n 'cookie_httponly': True,\n 'cookie_refresh_token_name': 'refresh_token',\n 'cookie_set': False,\n 'cookie_strict': True,\n 'cookie_access_token_name': 'access_token',\n 'debug': False,\n 'expiration_delta': 60 * 5 * 6,\n 'leeway': 60 * 3,\n 'refresh_token_enabled': False,\n 'refresh_token_name': 'refresh_token',\n 'path_to_authenticate': '/',\n 'path_to_retrieve_user': '/me',\n 'path_to_verify': '/verify',\n 'path_to_refresh': '/refresh',\n 'private_key': None,\n 'scopes_enabled': False,\n 'scopes_name': 'scopes',\n 'secret': 'This is a big secret. Shhhhh',\n 'strict_slashes': False,\n 'url_prefix': '/auth',\n 'user_id': 'user_id',\n 'verify_exp': True,\n}\n\naliases = {\n 'cookie_token_name': 'cookie_access_token_name',\n 'public_key': 'secret',\n}\n\nlogger = logging.getLogger(__name__)\nconfig = None\n\n\nclass Configuration:\n def __init__(self, app_config, **kwargs):\n presets = self.extract_presets(app_config)\n self.kwargs = self._merge_aliases(kwargs)\n self.defaults = copy.deepcopy(defaults)\n self.defaults.update(self._merge_aliases(presets))\n self.defaults.update(self.kwargs)\n\n list(map(self.__map_config, self.defaults.items()))\n self._validate_secret()\n self._validate_keys()\n self._load_keys()\n\n def __map_config(self, config_item):\n key, value = config_item\n if (not hasattr(self, key) or key in self.kwargs):\n setter_name = 'set_{}'.format(key)\n if hasattr(self, setter_name):\n value = getattr(self, setter_name)()\n setattr(self, key, value)\n\n def __iter__(self):\n return ((x, getattr(self, x)) for x in self.defaults.keys()) # noqa\n\n def __repr__(self):\n return str(dict(iter(self))) # noqa\n\n def _validate_secret(self):\n logger.debug('validating provided secret')\n if self.secret is None or (\n isinstance(self.secret, str) and self.secret.strip() == ''):\n raise exceptions.InvalidConfiguration(\n 'the SANIC_JWT_SECRET parameter cannot be None nor an empty '\n 'string')\n\n def _validate_keys(self):\n logger.debug('validating keys (if needed)')\n if utils.algorithm_is_asymmetric(self.algorithm) and (\n self.private_key is None or (\n isinstance(self.private_key, str) and\n self.private_key.strip() == ''\n )\n ):\n raise exceptions.RequiredKeysNotFound\n\n def _load_keys(self):\n logger.debug('loading secret and/or keys (if needed)')\n try:\n self.secret = utils.load_file_or_str(self.secret)\n if utils.algorithm_is_asymmetric(self.algorithm):\n self.private_key = utils.load_file_or_str(self.private_key)\n except exceptions.ProvidedPathNotFound as exc:\n if utils.algorithm_is_asymmetric(self.algorithm):\n raise exceptions.RequiredKeysNotFound\n raise exc\n\n @staticmethod\n def _merge_aliases(config):\n popped = {}\n for k in aliases.keys():\n if k in config:\n popped[aliases[k]] = config.pop(k)\n config.update(popped)\n return config\n\n @staticmethod\n def extract_presets(app_config):\n \"\"\"\n Pull the application's configurations for Sanic JWT\n \"\"\"\n return {\n x.lower()[10:]: app_config.get(x)\n for x in filter(lambda x: x.startswith('SANIC_JWT'), app_config)\n }\n","sub_path":"sanic_jwt/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":3994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"37555347","text":"import json\r\n\r\nfrom ..core import *\r\nfrom ..vparsers import *\r\nfrom ..utils import *\r\n\r\n\r\nclass TreeDevParser(SingleSourceMixin, SingleRequestLoaderMixin, BaseParser):\r\n middlewares = [ DecodeMiddleware(), BeautifulSoupMiddleware() ]\r\n \r\n url = \"http://treedevelopment.com/\"\r\n method = \"GET\"\r\n parsers = {\r\n \"int\": IntParser(), \"area\": AreaParser(), \"price\": PriceParser(),\r\n \"status\": StatusParser(), \"rooms\": RoomsParser()\r\n }\r\n td_with_data = 10\r\n \r\n @attributeerror_wrapper(return_value=[])\r\n def find_records(self, soup):\r\n records = soup.find(\"table\", {\"class\": \"table-apartments\"})\\\r\n .find(\"tbody\").find_all(\"tr\")\r\n return [ self.extract_data(record) for record in records ]\r\n \r\n @tryexcept_wrapper((AttributeError, IndexError), return_value=None)\r\n def extract_data(self, record):\r\n data = record.find_all(\"td\")[self.td_with_data].find(\"a\")\\\r\n .get(\"data-json\", \"{}\")\r\n return json.loads(data)\r\n \r\n def parse_record(self, data):\r\n return {\r\n \"number\": data.get(\"numer_oferty\", None),\r\n \"building\": data.get(\"budynek\", None),\r\n \"floor\": self.parsers[\"int\"](data.get(\"pietro\", None)),\r\n \"area\": self.parsers[\"area\"](data.get(\"powierzchnia\", None)),\r\n \"rooms\": self.parsers[\"rooms\"](data.get(\"pokoje\", None)),\r\n \"balcony\": self.parsers[\"area\"](data.get(\"balkon\", None)),\r\n \"garden\": self.parsers[\"area\"](data.get(\"ogrodek\", None)),\r\n \"terrace\": self.parsers[\"area\"](data.get(\"taras\", None)),\r\n \"price\": self.parsers[\"price\"](data.get(\"cena\", None)),\r\n \"price_m2\": self.parsers[\"price\"](data.get(\"cena_m2\", None)),\r\n \"status\": self.parsers[\"status\"](data.get(\"status\", None)),\r\n \"entrance\": data.get(\"klatka\", None)\r\n }\r\n \r\n def modify_record(self, record, data):\r\n record[\"fid\"] = record[\"number\"]\r\n record[\"plan\"] = self.create_plan_url(record)\r\n return record\r\n\r\n def create_plan_url(self, record):\r\n return None\r\n","sub_path":"parsers/treedev/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"204397436","text":"import unittest\nfrom unittest.mock import Mock, patch\n\nfrom ga.population_generator import PopGenerator\nfrom ms_rcpsp.scheduler import Scheduler\nfrom ms_rcpsp.skill import Skill\n\n\nclass TestPopulationGenerator(unittest.TestCase):\n\n def setUp(self):\n s = [Skill('s1', 4),\n Skill('s2', 2),\n Skill('s3', 5),\n Skill('s3', 2)]\n self.resources = [Mock(skills=[s[1], s[2]]),\n Mock(skills=[s[0]]),\n Mock(skills=[s[3]])]\n self.tasks = [Mock(id=1, required_skill=s[1]),\n Mock(id=2, required_skill=s[3]),\n Mock(id=3, required_skill=s[0]),\n Mock(id=4, required_skill=s[2]),\n Mock(id=5, required_skill=s[0])]\n self.individual = Scheduler(list(self.tasks),\n list(self.resources))\n\n def test__random_population__good_pop_length(self):\n with patch('ga.population_generator.'\n 'PopGenerator._rand_individual'):\n pop_size = 15\n rand_pop = PopGenerator.generate_rand(15, Mock(), Mock())\n self.assertEqual(len(rand_pop), pop_size)\n\n def test__random_population__10_individuals(self):\n individual = PopGenerator._rand_individual(\n resources=self.resources,\n tasks=self.tasks)\n for task, resource in zip(individual.tasks,\n individual.resources):\n self.assertTrue(Scheduler.can_do_task(task, resource))\n self.assertEqual(task.resource_id, resource.id)\n","sub_path":"zad_01/tests/ga/test_population_generator.py","file_name":"test_population_generator.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"597343857","text":"import sqlite3\n\n# get personal data from user\n# firstName = input(\"Enter your first name: \")\n# lastName = input(\"Enter your last name: \")\n# age = int(input(\"Enter your age: \"))\n# personData = (firstName, lastName, age)\n\n# execute insert statement for supplied person data\nwith sqlite3.connect(\"test_database.db\") as connection:\n c = connection.cursor()\n # c.execute(\"INSERT INTO People VALUES(?,?,?)\", personData)\n # c.execute(\"UPDATE People SET age=? WHERE firstName=? AND lastName=?\", (45, 'Luigi', 'Vercotti'))\n # connection.commit()\n\n# select all first and last names from people over age 30\n# query fetched all results into a list\n# c.execute(\"SELECT firstName, lastName FROM People WHERE Age > 30\")\n# for row in c.fetchall():\n # print (row)\n# loop through returned list to parse the results\n c.execute(\"SELECT firstName, lastName FROM People WHERE Age > 30\")\n while True:\n row = c.fetchone()\n if row is None:\n break\n print (row)\nconnection.close()\n","sub_path":"SQLite_Assignment_p213.py","file_name":"SQLite_Assignment_p213.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"77456397","text":"\"\"\"\nTesting For Paper-I\n\"\"\"\n# import all the required Libraries\n\n## We have the set path before this\nsys.path.append('../CommonLibrariesDissertation')\npath_store = '../FinalDistSamples/'\n\n## We have to now import our libraries\nfrom Data_import import *\nfrom Library_Paper_two import *\n\n## Extract samples from the data\ndef extract_samples(X, y, p):\n index_1= [i for i,v in enumerate(y) if v == p]\n N = X[index_1,:];\n return N\n\n## Bootstrap sample for the data\ndef subsample(dataset, ratio=1.0):\n\tsample = list()\n\tn_sample = round(len(dataset) * ratio)\n\twhile len(sample) < n_sample:\n\t\tindex = randrange(len(dataset))\n\t\tsample.append(dataset[index])\n\treturn sample\n\n\n## Distance iteration to extract and save samples\ndef distance_Iteration():\n ## Class wise distance evaluation\n from Library_Paper_one import traditional_MTS\n\n # # Loop to evaluate distance value for all the classes.\n for p in tqdm(xrange(1,C+1)):\n N = extract_samples(X, y, p)\n np.savetxt( (\"../\"+'C'+str(p)+dataset_type+'.csv'), np.array(N), delimiter =',')\n scaler = preprocessing.StandardScaler().fit(N)\n N_transform = scaler.transform(N)\n\n Ref, Tree = initialize_calculation(T = None, Data = N_transform, gsize = 3, par_train = 0)\n Data = []\n\n np.savetxt( (\"../\"+'C_dimred'+str(p)+dataset_type+'.csv'), np.array(Ref), delimiter =',')\n\n for i in tqdm(xrange(T_iterations)):\n T = np.array(subsample(N_transform, ratio=0.06))\n T_dim, Tree = initialize_calculation(T = Tree, Data = T, gsize = 3, par_train = 1)\n\n Tmp = traditional_MTS(Ref, T_dim, par=0)\n Data.append(Tmp.mean())\n\n np.savetxt( (\"../\"+'R'+str(p)+dataset_type+'.csv'), np.reshape(np.array(Data), [-1,]), delimiter =',')\n\n\n## First Let us import our two data-sets=\nX, y = DataImport(num=11)\ndataset_type = 'rolling'\nC = 4\nT_iterations = 10000\ndistance_Iteration()\n","sub_path":"paper_1_distance_sample_gathering.py","file_name":"paper_1_distance_sample_gathering.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"185015705","text":"from custom_layers import base_embed_lstm_net, base_embed_cnn_lstm_net, base_multi_channel_net, base_attention_lstm\nimport keras\n\n\ndef mr_base_model(dataset, vocabulary_size, maxlen, method=\"base_multi_channel_net\", ):\n if method == \"base_multi_channel_net\":\n model = base_multi_channel_net(vocabulary_size, time_steps=maxlen)\n elif method == \"base_attention_lstm\":\n model = base_attention_lstm(vocabulary_size, time_steps=maxlen)\n elif method == \"base_embed_cnn_lstm_net\":\n model = base_embed_cnn_lstm_net(vocabulary_size)\n else:\n model = base_embed_lstm_net(vocabulary_size)\n\n model.compile(optimizer='rmsprop',\n loss='binary_crossentropy',\n metrics=['acc'])\n callbacks = [\n keras.callbacks.EarlyStopping(\n monitor='val_loss',\n patience=5,\n mode='auto'\n )\n ]\n model.summary()\n history = model.fit(dataset.x_train, dataset.y_train,\n epochs=20,\n batch_size=128,\n validation_data=(dataset.x_val, dataset.y_val),\n callbacks=callbacks,\n verbose=2)\n return model, history\n\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"184703325","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tur Jan 12 09:44:14 2018\n\n@author: Diogo\n\"\"\"\n\nfrom Bio import SeqIO\nimport fileinput\nfrom shutil import copyfile\nimport os\n\nclass _generic_genbank_file(object):\n \"\"\"\n This class treat the genbank files in general. Just load the data based on the file location\n \"\"\"\n\n def __init__(self, path_file):\n \"\"\"\n Constructor of the class genbank top class, the data are loaded into data_gen_bank variable. The classe only manipulate the data with the bioPython\n\n :param path_file: Complete path with file name\n\n :type path_file: string - required\n \"\"\"\n self.path_file = path_file\n self.data_gen_bank = None\n\n def read_write_gen_bank(self):\n \"\"\"\n This method create a backup and update the file path with this one correcting the ACCESSION number\n \"\"\"\n count_id = 0\n new_file_name = self.path_file + '.bak'\n copyfile(self.path_file, new_file_name)\n lines_file = []\n\n with open(self.path_file) as file:\n for line in file:\n if line.find('ACCESSION unknown') != -1:\n line = line.replace('ACCESSION unknown', 'ACCESSION unknown' + str(count_id))\n count_id += 1\n lines_file.append(line)\n\n with open(new_file_name, 'w') as file:\n for value_line in lines_file:\n file.write(value_line)\n\n# GARY\n #with open(new_file_name) as file_to_write:\n # with open(self.path_file) as file:\n # for line in file:\n # if line.find('ACCESSION unknown') != -1:\n # line = line.replace('ACCESSION unknown', 'ACCESSION unknown' + str(count_id))\n # count_id += 1\n # file_to_write.write(line)\n\n\n# END of magic GARY\n\n \n\n\n self.path_file = new_file_name\n\n\n\n\n def read_gen_bank(self):\n \"\"\"\n method use to load the data into its dict_fasta_data. If the ACCESSION number is \"unknow\", the method correct this for the extraction of the data into dictionaries calling the read_write_gen_bank method\". This last method is called when it is impossible to parse the genBank file.\n\n :excep ValueError: When it isn't possible to load the data into the dictionnary because of the double keys\n \"\"\"\n try:\n self.data_gen_bank = SeqIO.to_dict(SeqIO.parse(self.path_file, \"genbank\"))\n except ValueError:\n print (\"Test the substitution of the file: {0}\".format(self.path_file))\n\n self.read_write_gen_bank()\n self.data_gen_bank = SeqIO.to_dict(SeqIO.parse(self.path_file, \"genbank\"))\n\n print(\"end of the substitution\")\n\n def __str__(self):\n \"\"\"\n Overwrite of the str method\n \"\"\"\n message = \"File name: {0}, number of sequences {1:d}\".format(self.path_file, len(self.data_gen_bank))\n return message\n","sub_path":"files_treatment_new/generic_gen_bank_files.py","file_name":"generic_gen_bank_files.py","file_ext":"py","file_size_in_byte":2991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"374704953","text":"# -*- encoding: utf-8 -*-\nimport sys\nr_input = sys.stdin.readline\n\nN = int(r_input()) # 학생의 수\nstudents = [] # 학생들의 번호\n\nfor i in range(N):\n students.append(r_input().rstrip())\n\nlength = len(students[0])\n\nfor i in range(1, length+1):\n stack = []\n flag = 1\n\n for j in students:\n tmp = j[length - i:]\n if tmp in stack:\n flag = 0\n break\n stack.append(tmp)\n\n if flag:\n print(i)\n break\n","sub_path":"Algorithm/Baekjoon/01235 학생 번호/1235.py","file_name":"1235.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"425775341","text":"\"\"\"\nWrite a Python program to capitalize first and last letters of each word of a given string.\n\"\"\"\nstr1 = \"CodedLadies Innovate is a python oriented group.\"\nprint(str1.title())\nstr1 = result = str1.title()\nresult = \"\"\nfor word in str1.split():\n result += word[:-1] + word[-1].upper() + \" \"\nprint(result[:-1])","sub_path":"Aniyom Ebenezer/Phase 2/STRINGS/Day_34_Challenge_Solution/Question 10 Solution.py","file_name":"Question 10 Solution.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"415882959","text":"\"\"\"!\n@package DataAnalysis\n\nContains methods, functions, and classes to support data analysis, manipulation\nand I/O.\n\n\\sa Stats\n\\sa DataIO\n\\sa DataManipuation\n\\sa Math\n\\sa Histograms\n\"\"\"\n\n__all__ = [\"Stats\", \"DataIO\", \"DataManipulation\", \"Math\", \"Histograms\"]\n","sub_path":"src/DataAnalysis/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"27518590","text":"\"\"\" ==================================================================\nScript Name: tpDebugging.py\nby Tomas Poveda - 27/12/16\n______________________________________________________________________\nUtility methods related to write/read json files\n______________________________________________________________________\n===================================================================\"\"\"\n\nimport json\nimport maya.cmds as cmds\nimport os\n\ndef writeToFile(data, filename):\n if '.json' not in filename:\n filename += '.json'\n\n with open(filename, 'w') as jsonFile:\n json.dump(data, jsonFile, indent=2)\n\n return filename\n\ndef readFile(filename):\n if os.stat(filename).st_size == 0:\n return None\n else:\n try:\n with open(filename, 'r') as jsonFile:\n return json.load(jsonFile)\n except:\n print('Could not read {0}'.format(filename))\n return None","sub_path":"tpJson.py","file_name":"tpJson.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"122704548","text":"#!/usr/bin/python\nimport rospy\nimport dialogflow_v2 as dialogflow\nfrom std_msgs.msg import String\n\nfrom std_msgs.msg import ColorRGBA\nfrom naoqi_bridge_msgs.msg import FadeRGB\n\nfrom gtts import gTTS\nimport os\n\n\nRECOGNIZED_INTENT = '/recognized_intent'\nSPEAK_TOPIC = '/speech'\nLED_TOPIC = '/fade_rgb'\n\n\nspeech = rospy.Publisher(SPEAK_TOPIC, String, queue_size=10)\n\ndef detect_intent_texts(project_id, session_id, texts, language_code):\n \"\"\"Returns the result of detect intent with texts as inputs.\n\n Using the same `session_id` between requests allows continuation\n of the conversaion.\"\"\"\n\n print(\"TEXT: \", texts)\n \n session_client = dialogflow.SessionsClient()\n\n session = session_client.session_path(project_id, session_id)\n print('Session path: {}\\n'.format(session))\n\n for text in texts:\n text_input = dialogflow.types.TextInput(\n text=text, language_code=language_code)\n\n query_input = dialogflow.types.QueryInput(text=text_input)\n\n response = session_client.detect_intent(\n session=session, query_input=query_input)\n\n print('Query text: {}'.format(response.query_result.query_text))\n print('Detected intent: {} (confidence: {})\\n'.format(\n response.query_result.intent.display_name,\n response.query_result.intent_detection_confidence))\n print('Fulfillment text: {}\\n'.format(\n response.query_result.fulfillment_text))\n\n speech.publish(response.query_result.fulfillment_text)\n # fp = \"/tmp/tmp.mp3\"\n # tts = gTTS(text=response.query_result.fulfillment_text, lang='en')\n # tts.save(fp)\n # os.system(\"play \" + fp)\n\n\nclass Intent():\n\n def __init__(self):\n rospy.init_node('intent', anonymous=True)\n rospy.Subscriber(RECOGNIZED_INTENT, String, self.callback) \n\n def callback(self, msg):\n\n if msg.data:\n texts = [msg.data]\n detect_intent_texts('pepper-39819', 'abc', texts, 'en')\n\n led_msg = FadeRGB()\n color = ColorRGBA()\n color.r = 0\n color.g = 0\n color.b = 0\n color.a = 0\n d = rospy.Duration.from_sec(0)\n led_msg = FadeRGB()\n led_msg.led_name = 'FaceLeds'\n led_msg.color = color\n led_msg.fade_duration = d\n led.publish(led_msg)\n\n led_msg = FadeRGB()\n led_msg.led_name = 'EarLeds'\n led_msg.color = color\n led_msg.fade_duration = d\n led.publish(led_msg)\n\n\nif __name__ == '__main__':\n led = rospy.Publisher(LED_TOPIC, FadeRGB, queue_size=10)\n i = Intent()\n rospy.spin()","sub_path":"dialogflow/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"491403932","text":"from __future__ import division\n\nfrom django import template\nfrom django.template import Library\nfrom django.conf import settings\n\nfrom savoy.core.media.models import *\n\nregister = Library()\n\n\nclass GetPhotosWithTagNode(template.Node):\n def __init__(self, type, num, varname):\n self.tag, self.num, self.varname = type, num, varname\n\n def render(self, context):\n from tagging.models import Tag, TaggedItem\n try:\n tag = Tag.objects.get(name=self.tag)\n context[self.varname] = TaggedItem.objects.get_by_model(Photo, tag).order_by('-date_published')[:self.num]\n except:\n pass\n return ''\n\n@register.tag\ndef get_photos_with_tag(parser, token):\n \"\"\"\n Retrieves a given number of photos that have related FlickrPhoto objects sorted by date_published.\n\n Syntax::\n\n {% get_photos_with_tag [tag] [num] as [varname] %}\n\n Example::\n\n {% get_photos_with_tag screenshot 5 as screenshot_list %}\n\n \"\"\"\n bits = token.contents.split()\n if len(bits) != 5:\n raise template.TemplateSyntaxError(\"'%s' tag takes four arguments\" % bits[0])\n #if bits[1] != 'attend' or 'watch' or 'all':\n # raise template.TemplateSyntaxError(\"first argument to '%s' tag must be 'attend', 'watch', or 'all'.\" % bits[0])\n if bits[3] != 'as':\n raise template.TemplateSyntaxError(\"third argument to '%s' tag must be 'as'\" % bits[0])\n return GetPhotosWithTagNode(bits[1], bits[2], bits[4])\n\n\nclass GetLatestFlickrPhotosNode(template.Node):\n def __init__(self, type, num, varname):\n self.type, self.num, self.varname = type, num, varname\n\n def render(self, context):\n if self.type == 'personal':\n context[self.varname] = Photo.objects.filter(flickrphoto__isnull=False, flickrphoto__owner__nsid=settings.FLICKR_USERID).order_by('-date_published')[:self.num]\n elif self.type == 'favorites':\n context[self.varname] = Photo.objects.filter(flickrphoto__isnull=False).exclude(flickrphoto__owner__nsid=settings.FLICKR_USERID).order_by('-date_published')[:self.num]\n else:\n context[self.varname] = Photo.objects.filter(flickrphoto__isnull=False).order_by('-date_published')[:self.num]\n return ''\n\n@register.tag\ndef get_latest_flickr_photos(parser, token):\n \"\"\"\n Retrieves a given number of photos that have related FlickrPhoto objects sorted by date_published.\n\n Syntax::\n\n {% get_latest_flickr_photos [type(favorites|personal|all)] [num] as [varname] %}\n\n Example::\n\n {% get_latest_flickr_photos personal 5 as latest_photos %}\n\n \"\"\"\n bits = token.contents.split()\n if len(bits) != 5:\n raise template.TemplateSyntaxError(\"'%s' tag takes four arguments\" % bits[0])\n #if bits[1] != 'attend' or 'watch' or 'all':\n # raise template.TemplateSyntaxError(\"first argument to '%s' tag must be 'attend', 'watch', or 'all'.\" % bits[0])\n if bits[3] != 'as':\n raise template.TemplateSyntaxError(\"third argument to '%s' tag must be 'as'\" % bits[0])\n return GetLatestFlickrPhotosNode(bits[1], bits[2], bits[4])\n\n\n@register.filter\ndef convert_for_width(value, new_size):\n percentage = new_size/500\n return value * percentage\n \n \n@register.simple_tag\ndef convert_note_size(note, value, new_width):\n \"\"\"\n When displaying photos at a different size than Flickr does on its photo pages,\n you must convert notes to the size you're displaying at. Given a note, a value (of w, h, x, or y),\n and the width of your scaled version, this template tag will return the converted value.\n \n Example usage:\n
\n \"\"\"\n photo = note.flickr_photo.photo\n try:\n scale_percentage = new_width / photo.image_width\n except:\n return ''\n\n if photo.is_horizontal():\n percentage = new_width / 500 \n elif photo.is_vertical():\n aspect_ratio = photo.image_height / photo.image_width\n new_height = new_width * aspect_ratio\n percentage = new_height / 500\n\n if value == 'h':\n return note.h * percentage\n if value == 'w':\n return note.w * percentage\n if value == 'y':\n return note.y * percentage\n if value == 'x':\n return note.x * percentage","sub_path":"virtualenvs/ninetyseven/src/savoy/core/media/templatetags/photos.py","file_name":"photos.py","file_ext":"py","file_size_in_byte":4330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"536185799","text":"\n# coding: utf-8\n\n# In[ ]:\n\n\n#csvファイルを読み込み、「出处」で集計する。\n#集計結果���ソートして、csvファイルに書き出す。\n\nimport pandas as pd\n\nDIRNAME = '/Users/maryzhu/ggdrive/python/data/'\nFILENAME = 'sentence77719r.csv'\ndf = pd.read_csv(DIRNAME + FILENAME)\ndfcount = pd.DataFrame(df.groupby('出处').count())\ndfcountst = dfcount.sort_values(by=[\"中文\"], ascending=True).loc[:,['中文', '日文', '英文']]\n\ndfcount.sort_values(by=[\"中文\"], ascending=True).to_csv(DIRNAME +'sencountall.csv')\ndfcountst.to_csv(DIRNAME +'sencount.csv')\n\n","sub_path":"sentenceplay.py","file_name":"sentenceplay.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"3327168","text":"#-*- coding: utf-8 -*-\n\n\"\"\"systemanalysis URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/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. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import include, url\nfrom django.conf.urls.i18n import i18n_patterns\nfrom django.contrib import admin\n\nfrom core.views import (\n KeyErrorView, IndexView,\n LoginView, LogoutView, RegisterView,\n ControlConfirmationKeyView\n)\n\nadmin.autodiscover()\n\n\nurlpatterns = i18n_patterns('',\n\n # Admin Panel\n url(r'^admin/', include(admin.site.urls)),\n\n # General\n url(r'^$', view=IndexView.as_view(), name=\"index\"),\n\n # Account\n url(r'^login/$', view=LoginView.as_view(), name=\"login\"),\n url(r'^logout/$',view=LogoutView.as_view(), name=\"logout\" ),\n url(r'^register/$', view=RegisterView.as_view(), name=\"register\"),\n url(r'^confirmation/(?P\\w+)/$', view=ControlConfirmationKeyView.as_view(), name=\"confirmation\"),\n\n # User\n url(r'^user/', include('user.urls', namespace='user')),\n)\n","sub_path":"bugsnews/apps/core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"509944229","text":"import glob\nimport requests\nimport re\nimport os\nimport time\nimport json\n##########################################################################################################################\ndef renameFiles():\n\tprint(final)\n\tos.rename(filename, rename)\n##########################################################################################################################\ndef finalUUID():\n\tglobal final\n\tglobal rename\n\tfinaluuid = \"%s-%s-%s-%s-%s\" % (first8, second4, third4, fourth4, fifth12)\n\trename = \"%s.yml\" % (finaluuid)\n\tfinal = \"eUUID - %s.yml Processed\" % (finaluuid)\n\trenameFiles()\n##########################################################################################################################\ndef slashInput():\n\tglobal first8\n\tglobal second4\n\tglobal third4\n\tglobal fourth4\n\tglobal fifth12\n\tf4 = open('uuidmappings2', 'w+')\n\tf4.seek(0, 0)\n\tf4.write(UUIDHere)\n\tf4.seek(0, 0)\n\tfirst8 = f4.read(8)\n\tf4.seek(8, 0)\n\tsecond4 = f4.read(4)\n\tf4.seek(12, 0)\n\tthird4 = f4.read(4)\n\tf4.seek(16, 0)\n\tfourth4 = f4.read(4)\n\tf4.seek(20, 0)\n\tfifth12 = f4.read(12)\n\tf4.close()\n\tfinalUUID()\n##########################################################################################################################\ndef findUUID():\n\tprint(usernamemessage)\n\tlink = \"https://api.mojang.com/users/profiles/minecraft/%s\" % newusername\n\tf2 = requests.get(link)\n\tjson_string = json.dumps(f2.json())\n\tnewJsonData = json.loads(json_string)\n\tglobal UUIDHere\n\ttry:\n\t\tUUIDHere = newJsonData['id']\n\t\tprint(UUIDHere)\n\texcept KeyError:\n\t\tprint(\"One UUID skipped due to username change\")\n\tslashInput()\n##########################################################################################################################\ndef startup():\n\tglobal filename\n\tfor filename in glob.glob('*.yml'):\n\t\tf = open(filename, 'r')\n\t\tfor line in f:\n\t\t\tif \"lastAccountName\" in line:\n\t\t\t\tusernamenl = line\n\t\t\t\tusername = usernamenl.replace('\\n','')\n\t\tf.close()\n\t\tglobal newusername\n\t\tnewusername = username.replace('lastAccountName: ', '')\n\t\tglobal usernamemessage\n\t\tusernamemessage = \"eUUID - %s being processed.\" % newusername\n\t\ttime.sleep(1.2)\n\t\tfindUUID()\n##########################################################################################################################\ndef message():\n\tglobal complete\n\tmessage = \"Essentials Playerfiles Converter\"\n\tmessage2 = \"eUUID - Converts both Offline to Online UUID\"\n\tmessage3 = \"eUUID - Script Made by WhiteFlamesMC and Soledge\"\n\tprint(message)\n\tprint(message2)\n\tprint(message3)\n\tcomplete = 'Finished with Playerdata UUID conversion.'\n\tstartup()\n##########################################################################################################################\ndef deleteGarbage():\n\tif os.path.exists('uuidmappings'):\n\t\tos.remove('uuidmappings')\n\tif os.path.exists('uuidmappings2'):\n\t\tos.remove('uuidmappings2')\n\telse:\n\t\tprint(\"No UUIDs were processed\")\n##########################################################################################################################\nmessage()\ndeleteGarbage()\nprint(complete)","sub_path":"EssentialsUUID.py","file_name":"EssentialsUUID.py","file_ext":"py","file_size_in_byte":3058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"509376219","text":"import numpy as np\nimport pandas as pd\n\nfrom .NrcProcess import NrcProcess\nclass TextClassifier(NrcProcess):\n IS_DEBUG = False\n\n def __init__(self):\n super().__init__()\n\n def classify(self, text):\n score = {}\n for word in text:\n if self.IS_DEBUG: print(\"word: \", word)\n _score = self.getNrcScore(word)\n score = self.sumScore(_score, score)\n if self.IS_DEBUG: print(\"score: \", score)\n if self.IS_DEBUG: print(\"------------------------------------\")\n\n return score","sub_path":"libs/TextClassifier.py","file_name":"TextClassifier.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"570640985","text":"# load code / config\nimport os,sys;\nsys.path.append(os.path.join((lambda r,f:f[0:f.index(r)+len(r)])('code',os.path.abspath(__file__)),'config'));\nimport config\nconfig.epimodel()\nconfig.numpy()\nconfig.plot()\n# external module\nimport re\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom copy import deepcopy\n# epi-model modules\nimport utils\nimport modelutils\nfrom space import Space,Array\nfrom elements import Color\n# relative imports\nimport system\nimport sensitivity\n\nnames = ['S','I','T']\n# names = ['S','infected']\nlights = [0.6,0.0,0.3]\nout = 'X'\nn = 1\n\ndef make_pie(sim,select,phi):\n plt.figure(figsize=(2,2))\n selectors = [\n sim.model.select[name].union(sim.model.select[select])\n for name in names\n ]\n SIR = np.array([\n modelutils.taccum(sim.outputs[out],**selector).islice(t=sim.t[-1])\n for selector in selectors\n ])\n SIR = SIR / SIR.sum()\n colors = [selector.color.lighten(light) for selector,light in zip(selectors,lights)]\n labels = [sim.model.select[name].label for name in names]\n reorder = lambda x: [x[0],x[2],x[1]]\n # reorder = lambda x: [x[0],x[1]]\n plt.pie(reorder(SIR), colors=reorder(colors), startangle=90, counterclock=True )\n plt.tight_layout(pad=-1.8)\n figdir = os.path.join(config.path['figs'],'flows','phi={}'.format(phi))\n utils.makedir(figdir)\n if config.save:\n plt.savefig(os.path.join(figdir,'{}-{}.pdf'.format('flow',select,phi)),transparent=True)\n else:\n plt.show()\n plt.close()\n make_legend(labels,colors)\n\ndef make_legend(labels,colors):\n plt.figure(figsize=(4.5,0.5))\n # plt.figure(figsize=(1.5,1))\n for color in colors:\n plt.fill([np.nan]*3,[np.nan]*3,color=color)\n # plt.legend(['$\\\\mathcal{S}$','$\\\\mathcal{I}$','$\\\\mathcal{R}$'],loc='center',ncol=3)\n plt.legend(labels,loc='center',mode='expand',ncol=3 )\n plt.gca().set_axis_off()\n if config.save:\n plt.savefig(os.path.join(config.path['figs'],'flows','flows-legend.pdf'))\n else:\n plt.show()\n plt.close()\n\ndef make_tikz(label,phi):\n tikzdir = os.path.join(config.path['tikz'],'flows');\n phistr = 'phi={}'.format(phi)\n flowdir = os.path.join(config.path['figs'],'flows')\n # What is this 3x escape mess?\n configstr = \\\n '\\\\\\\\graphicspath{{'+os.path.join(flowdir,phistr)+'/}}'+\\\n '\\\\\\\\\\\\\\\\newcommand{\\\\\\\\\\\\\\\\turnover}{'+str(4*np.minimum(1,phi**(1/3)))+'}'\n os.system('cd {} && echo {} > config.tex && pdflatex flows.tex >/dev/null && cp flows.pdf {}/{}'.format(\n tikzdir, configstr, flowdir, 'flows-{}.pdf'.format(label) ))\n\ndef make_figs():\n phis = list(sensitivity.iter_phi())\n for label,phi in [\n ('low', phis[n]),\n ('med', phis[int((config.N-1)/2)]),\n ('high', phis[config.N-n-1]),\n ('extreme',10),\n ]:\n specs = system.get_specs()\n model = system.get_model()\n sim = sensitivity.get_sim(phi,0.1)\n sim.init_outputs(system.get_outputs(\n spaces = sim.model.spaces,\n select = sim.model.select,\n t = sim.t,\n names = [out]\n ))\n if label == 'extreme':\n sim.update_params(dict(ibeta=0.038))\n sim.solve()\n for name in ['high','low']:\n make_pie(sim,name,phi)\n make_tikz(label,phi)\n","sub_path":"code/main/flows.py","file_name":"flows.py","file_ext":"py","file_size_in_byte":3125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"427978628","text":"\n\n#calss header\nclass _ANTENNA():\n\tdef __init__(self,): \n\t\tself.name = \"ANTENNA\"\n\t\tself.definitions = [u'either of a pair of long, thin organs that are found on the heads of insects and crustaceans (= animals with hard outer shells) and are used to feel with', u'the natural ability to notice things and understand their importance: ', u'an aerial noun ']\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/_antenna.py","file_name":"_antenna.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"358441680","text":"princess = {\n \"banana\": 4,\n \"apple\": 2,\n \"orange\": 1.5,\n \"pear\": 3\n}\nstock = {\n \"banana\": 6,\n \"apple\": 0,\n \"orange\": 32,\n \"pear\": 15,\n}\nfor keys, values in stock.items():\n print(keys, values, sep = ': ')\n print('price', princess[keys], sep = ': ')\ntotal = 0\nfor keys, values in princess.items():\n price = values * stock[keys]\n total = total + price\nprint(total)\n","sub_path":"Session04/Homework/exercise2.py","file_name":"exercise2.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"24428590","text":"'''\nThis module is an sklearn compatible pipeline for machine learning\ntime series data and sequences using a sliding window segmentation\n'''\n# Author: David Burns\n# License: BSD\n\nfrom .transform import SegmentX\nfrom .util import check_ts_data\n\nimport numpy as np\nfrom sklearn.base import BaseEstimator\n\nfrom sklearn.utils.validation import check_is_fitted\n\nclass SegPipe(BaseEstimator):\n '''\n The pipeline supports learning multi-variate time series with or without relational contextual variables (see introduction).\n\n The purpose of this pipeline is to assemble the segmentation, feature extraction (optional), feature processing (optional), and final estimator steps into a single pipeline that can be cross validated together setting different parameters.\n\n The pipeline is applied in 2 steps, when methods ``fit``, ``transform``, ``predict``, or ``score`` is called\n\n Step 1: sliding window segmentation performed by the ``segmenter`` object.\n\n Step 2: ``est`` estimator pipeline (or estimator) called\n\n The time series data (X) is input to the pipeline as a numpy object array, length n_series. The first column holds the time series data, and second column (optional) can hold relational contextual variables. Each element of the time series data is array-like with shape [n_samples, n_time_variables]. n_samples can be different for each element (series). Each element of the contextual variable data is array-like with shape [n_context_variables]. The ``util`` module has functions to help create the necessary data structure.\n\n The target y can be like a contextual variable, with one value per time series, in which case ``SegmentX`` should be used as the segmenter. Or if the target variable y is itself a time series, than ``SegmentXY`` should be used.\n\n The API for setting parameters for the segmenter and ``est`` pipelines are similar to sklearn but slightly different. It is compatible with sklearn parameter optimization tools (eg GridSearchCV). See the set_params method, and examples for details.\n\n Parameters\n ----------\n est : sklearn estimator or pipeline or None\n | for feature processing (optional) and applying the final estimator\n | if None, only segmentation and expansion is done\n segmenter : object\n Segmentation transformer to convert time series data to segmented time series data\n shuffle : bool, optional\n shuffle the segments before fitting the ``est`` pipeline (recommended)\n scorer : callable, optional\n scorer callable made with sklearn.metrics.make_scorer, can only return 1 score\n\n\n Attributes\n ----------\n N_train : number of training segments - available after calling fit method\n N_test : number of testing segments - available after calling predict, or score methods\n\n Examples\n --------\n\n >>> from seglearn.transform import FeatureRep\n >>> from seglearn.feature_functions import mean, var, std, skew\n >>> from seglearn.pipe import SegPipe\n >>> from seglearn.datasets import load_watch\n >>> from sklearn.pipeline import Pipeline\n >>> from sklearn.ensemble import RandomForestClassifier\n >>> data = load_watch()\n >>> X = data['X']\n >>> y = data['y']\n >>> fts = {'mean': mean, 'var': var, 'std': std, 'skew': skew}\n >>> est = Pipeline([('ftr', FeatureRep(features = fts)),('rf',RandomForestClassifier())])\n >>> pipe = SegPipe(est)\n >>> pipe.fit(X, y)\n >>> print(pipe.score(X, y))\n\n '''\n def __init__(self, est, segmenter = SegmentX(), shuffle = True, scorer = None):\n self.est = est\n self.segmenter = segmenter\n self.shuffle = shuffle\n self.scorer = scorer\n\n def fit(self, X, y, **fit_params):\n '''\n Fit the data.\n Applies fit to ``feed`` pipeline, segment expansion, and fit on ``est`` pipeline.\n\n Parameters\n ----------\n X : array-like, shape [n_series, ...]\n Time series data and (optionally) contextual data created as per ``make_ts_data``\n y : array-like shape [n_series]\n target vector\n fit_params : optional parameters\n passed to ``est`` pipe fit method\n\n Returns\n -------\n self : object\n Return self\n\n '''\n self._reset()\n check_ts_data(X, y)\n self.segmenter.fit(X, y, **fit_params)\n X, y, _ = self.segmenter.transform(X, y)\n\n self.N_train = len(y)\n\n if self.shuffle is True:\n X, y = self._shuffle(X, y)\n\n fitres = self.est.fit(X, y, **fit_params)\n\n # for keras scikit learn api\n if hasattr(fitres,'history'):\n self.history = fitres\n\n return self\n\n def transform(self, X, y = None):\n '''\n Applies transform to ``est`` pipeline.\n If the target vector y is supplied, the segmentation expansion will be performed on it and returned.\n\n Parameters\n ----------\n X : array-like, shape [n_series, ...]\n Time series data and (optionally) contextual data created as per ``make_ts_data``\n y : array-like shape [n_series], optional\n target vector\n\n Returns\n -------\n X : array-like, shape [n_segments, ]\n transformed feature data\n y : array-like, shape [n_segments]\n expanded target vector\n '''\n check_is_fitted(self, 'N_train')\n check_ts_data(X, y)\n X, y, _ = self.segmenter.transform(X, y)\n X = self.est.transform(X)\n return X, y\n\n\n def fit_transform(self, X, y, **fit_params):\n '''\n Applies fit and transform methods to the full pipeline sequentially\n\n Parameters\n ----------\n X : array-like, shape [n_series, ...]\n Time series data and (optionally) contextual data created as per ``make_ts_data``\n y : array-like shape [n_series], optional\n target vector\n\n Returns\n -------\n X : array-like, shape [n_segments, ]\n transformed feature data\n y : array-like, shape [n_segments]\n expanded target vector\n '''\n self.fit(X,y, **fit_params)\n return self.transform(X,y)\n\n\n\n def predict(self, X, y):\n '''\n Applies transform to ``feed`` pipeline, segment expansion, and predict on ``est`` pipeline.\n\n Parameters\n ----------\n X : array-like, shape [n_series, ...]\n Time series data and (optionally) contextual data created as per ``make_ts_data``\n y : array-like shape [n_series], optional\n target vector\n\n Returns\n -------\n y : array like shape [n_segments]\n expanded target vector\n yp : array like shape [n_segments]\n predicted (expanded) target vector\n\n '''\n check_is_fitted(self, 'N_train')\n check_ts_data(X, y)\n X, y, _ = self.segmenter.transform(X, y)\n yp = self.est.predict(X)\n self.N_test = len(y)\n return y, yp\n\n\n def score(self, X, y, sample_weight = None):\n '''\n Applies transform and score with the final estimator or scorer function if set as init parameter\n\n Parameters\n ----------\n X : array-like, shape [n_series, ...]\n Time series data and (optionally) contextual data created as per ``make_ts_data``\n y : array-like shape [n_series], optional\n target vector\n sample_weight : array-like shape [n_series], default = None\n If not none, this is expanded from a by-series to a by-segment representation and passed as a ``sample_weight`` keyword argument to the ``score`` method of the ``est`` pipeline.\n\n Returns\n -------\n score : float\n '''\n check_is_fitted(self, 'N_train')\n check_ts_data(X, y)\n X, y, sample_weight = self.segmenter.transform(X, y, sample_weight)\n\n score_params = {}\n if sample_weight is not None:\n score_params['sample_weight'] = sample_weight\n\n self.N_test = len(y)\n\n if self.scorer is None:\n return self.est.score(X, y, **score_params)\n else:\n return self.scorer(self.est, X, y, **score_params)\n\n\n def set_params(self, **params):\n '''\n Set the parameters of of the pipeline.\n\n Parameters\n ----------\n params : dict\n | parameter keys for the ``feed`` pipeline are preceeded by ``f$``\n | parameter keys for the ``est`` pipeline are preceded by ``e$``\n | parameter keys can be set to the value of another parameter using the key for that parameter as a value\n\n Returns\n -------\n self : object\n Returns self\n\n '''\n keys = list(params.keys())\n for key in params:\n if params[key] in keys:\n params[key] = params[params[key]]\n\n seg_params = {key[2:]:params[key] for key in params if 's$' in key}\n est_params = {key:params[key] for key in params if 's$' not in key}\n self.segmenter.set_params(**seg_params)\n self.est.set_params(**est_params)\n return self\n\n # def get_params(self, deep=True):\n # not yet implemented\n # feed_params = self.feed.get_params()\n # feed_params = {'f$'+key:feed_params[key] for key in feed_params}\n #\n # est_params = self.est.get_params()\n # est_params = {'e$' + key: est_params[key] for key in est_params}\n #\n # return dict(list(feed_params.items()) + list(est_params.items()))\n\n\n def _reset(self):\n ''' Resets internal data-dependent state of the transformer. __init__ parameters not touched. '''\n if hasattr(self,'N_train'):\n del self.N_train\n if hasattr(self, 'N_test'):\n del self.N_test\n\n def _shuffle(self, X, y):\n ''' shuffles X and y '''\n ind = np.arange(len(y), dtype=np.int)\n np.random.shuffle(ind)\n X = X[ind]\n y = y[ind]\n return X, y\n\n\n","sub_path":"seglearn/pipe.py","file_name":"pipe.py","file_ext":"py","file_size_in_byte":10015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"439618920","text":"import logging\nfrom app.utils.datetime import string_to_date, string_to_datetime\nfrom flask import request\nfrom flask_restful import Resource\nfrom app.models.pet import Pet\nfrom app.models.pet_record import DelPetRecordSchema, PetRecord, PetRecordSchema, RecordQuerySchema\nfrom app.utils.decorators import confirm_account, confirm_device\nfrom app import db\nimport datetime\nfrom sqlalchemy.exc import IntegrityError\n\n# make instances of schemas\npet_record_schema = PetRecordSchema()\npet_records_schema = PetRecordSchema(many=True)\ndeleted_record_schema = DelPetRecordSchema()\nrecord_query_schema = RecordQuerySchema()\n\nclass PetRecordApi(Resource):\n @confirm_device\n def post(self, pet_id: int):\n \"\"\"\n Post new pet record by Ppcam(device)\n TEST by form-data, not raw JSON\n\n :Param pet_id: pet id of the record\n \"\"\"\n logging.debug(request.form)\n\n # find user by pet_id\n selected_pet = Pet.query.filter_by(id = pet_id).first()\n # check 404\n if selected_pet is None:\n return {\n \"msg\" : \"Pet not found\"\n }, 404\n # make new record object\n new_record = PetRecord(\n timestamp = request.form['timestamp'],\n result = request.form['result'],\n pet_id = pet_id,\n user_id = selected_pet.user_id\n )\n # Upload record image file\n image_uuid = new_record.upload_record_image(request.files['image'])\n if image_uuid:\n new_record.image_uuid = image_uuid\n else:\n return {\n \"msg\" : \"Fail to upload record image.\"\n }, 500\n # persistancy\n try:\n db.session.add(new_record)\n db.session.commit()\n except IntegrityError as e:\n new_record.delete_record_image()\n db.session.rollback()\n logging.error(f'POST: {e}')\n return {\n \"msg\" : \"IntegrityError on post new pet_record, check primary keys\"\n }, 409\n # update stat tables\n PetRecord.update_stats(new_record.pet_id, new_record.user_id, new_record.timestamp, string_to_datetime(request.form['timestamp']))\n return pet_record_schema.dump(new_record)\n\n @confirm_account\n def get(self, pet_id):\n # validate query string by ma\n errors = record_query_schema.validate(request.args)\n if errors:\n return {\n \"msg\" : \"error in get method - query schema validation\"\n }, 400\n # get timestamp in query string\n timestamp = request.args.get(\"timestamp\")\n # get record by timestamp\n selected_record = PetRecord.query.filter_by(timestamp = timestamp, pet_id = pet_id).first()\n if(selected_record is None):\n return {\n \"msg\" : \"Pet record not found\"\n }, 404\n else:\n return pet_record_schema.dump(selected_record)\n\n\n @confirm_account\n def put(self, pet_id):\n # validate query string by ma\n errors = record_query_schema.validate(request.args)\n if errors:\n return {\n \"status\" : \"fail\",\n \"msg\" : \"error in put method - query schema validation\"\n }, 400\n # get old datetime in query string\n old_datetime = request.args.get(\"timestamp\")\n # querying record\n selected_record = PetRecord.query.filter_by(timestamp = old_datetime, pet_id = pet_id).first()\n if(selected_record is None):\n return {\n \"msg\" : \"Pet record not found\"\n }, 404\n # update selected-record\n try:\n selected_record.timestamp = request.json['timestamp']\n selected_record.result = request.json['result']\n selected_record.last_modified_date = datetime.datetime.now()\n db.session.commit()\n except IntegrityError as e:\n db.session.rollback()\n return {\n \"msg\" : \"IntegrityError in put pet_record\"\n }, 409\n # update stat tables\n PetRecord.update_stats(selected_record.pet_id, selected_record.user_id, selected_record.timestamp, string_to_datetime(old_datetime))\n return pet_record_schema.dump(selected_record)\n\n @confirm_account\n def delete(self, pet_id):\n # validate query string by ma\n errors = record_query_schema.validate(request.args)\n if errors:\n return {\n \"msg\" : \"error in delete method - query schema validation\"\n }, 400\n # get timestamp in query string\n old_datetime = request.args.get(\"timestamp\")\n selected_record = PetRecord.query.filter_by(timestamp = old_datetime, pet_id = pet_id).first()\n # check 404\n if(selected_record is None):\n return {\n \"msg\" : \"Pet record not found\"\n }, 404\n deleted_pet_id = pet_id\n deleted_user_id = selected_record.user_id\n try:\n db.session.delete(selected_record)\n db.session.commit()\n # delete record image in S3\n selected_record.delete_record_image()\n except IntegrityError as e:\n db.session.rollback()\n return {\n \"msg\" : \"IntegrityError of deleting pet record\"\n }, 409\n # update stat tables\n PetRecord.update_stats(deleted_pet_id, deleted_user_id, string_to_datetime(old_datetime), string_to_datetime(old_datetime))\n return {\n \"msg\" : \"successfully delete selected record\"\n }, 200\n\nclass PetRecordsApi(Resource):\n @confirm_account\n def get(self, pet_id):\n '''\n /pet//records\n Get all records at the date\n :Query param: timestamp: str\n '''\n # validate query string by ma\n errors = record_query_schema.validate(request.args)\n if errors:\n return {\n \"msg\" : \"error in get method - query schema validation\"\n }, 400\n # get timestamp in query string\n date = string_to_date(request.args.get(\"timestamp\"))\n min_timestamp = datetime.datetime.combine(date, datetime.time.min)\n max_timestamp = datetime.datetime.combine(date, datetime.time.max)\n # get all records in that date\n selected_records = PetRecord.query.filter_by(pet_id = pet_id).\\\n filter(PetRecord.timestamp <= max_timestamp).\\\n filter(PetRecord.timestamp >= min_timestamp).\\\n all()\n if len(selected_records) == 0:\n return {\n \"msg\" : \"Pet records not found\"\n }, 404\n else:\n return pet_records_schema.dump(selected_records), 200","sub_path":"app/resources/pet_record.py","file_name":"pet_record.py","file_ext":"py","file_size_in_byte":6769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"14115900","text":"# file i/o demo --generating\n\nimport turtle\n\ntheWindow = turtle.Screen()\ntheWindow.bgcolor(\"black\")\n\nisra = turtle.Turtle()\nisra.color(\"skyblue\")\nisra.pensize(4)\n\ntheFile = open(\"drawing.dat\", \"w\")\n\ndef headTo(x, y):\n x = int(x)\n y = int(y)\n isra.goto(x, y)\n coordinates = str(x) + \" \" + str(y) + \"\\n\"\n theFile.write(coordinates)\n\ndef pickUp():\n isra.penup()\n theFile.write(\"UP\\n\")\n\ndef putDown():\n isra.pendown()\n theFile.write(\"DOWN\\n\")\n\ndef endDrawing():\n theFile.close()\n theWindow.bye()\n\ntheWindow.onkey(pickUp, \"u\")\ntheWindow.onkey(putDown, \"d\")\ntheWindow.onkey(endDrawing, \"q\")\ntheWindow.onclick(headTo)\ntheWindow.listen()\n\ntheWindow.mainloop()","sub_path":"generateMysteryDrawings.py","file_name":"generateMysteryDrawings.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"197223903","text":"#\n# Copyright (C) 2016 The Android Open Source Project\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\n\"\"\"Tests for util.py\"\"\"\n\n\nimport unittest\n\nfrom core import util\nfrom test import stubs\n\n\nclass UtilTest(unittest.TestCase):\n \"\"\"Tests for the Util functions.\"\"\"\n\n def setUp(self):\n self.stub_os = stubs.StubOs()\n self.stub_open = stubs.StubOpen(self.stub_os)\n\n util.os = self.stub_os\n util.open = self.stub_open.open\n\n def test_bdk_path(self):\n # We use startswith since it might also be .pyc if unit tests have been\n # previously run.\n self.assertTrue(__file__.startswith(\n util.GetBDKPath('cli', 'lib', 'core', 'util_unittest.py')))\n\n def test_bdk_version(self):\n self.stub_open.files[util.GetBDKPath('VERSION')] = (\n stubs.StubFile('123.45'))\n self.stub_os.path.should_exist = [util.GetBDKPath('VERSION')]\n self.assertEqual(util.GetBDKVersion(), '123.45')\n\n def test_get_product_dir(self):\n self.stub_os.cwd = '/long/way/down/to/the/bottom/turtle/'\n self.stub_os.path.should_exist = [\n self.stub_os.path.join('/long', util.ANDROID_PRODUCTS_MK),\n self.stub_os.path.join('/long/way/down/to/top',\n util.ANDROID_PRODUCTS_MK),\n self.stub_os.path.join('/long/way', util.ANDROID_PRODUCTS_MK)]\n # Make sure we find the closest in our direct path.\n self.assertEqual(util.GetProductDir(), '/long/way')\n\n def test_get_no_product_dir(self):\n self.stub_os.cwd = '/long/way/down/to/the/bottom/turtle/'\n self.stub_os.path.should_exist = [\n self.stub_os.path.join('/other', util.ANDROID_PRODUCTS_MK)]\n self.assertEqual(util.GetProductDir(), None)\n\n def test_get_project_spec(self):\n self.stub_os.cwd = '/long/way/down/to/the/bottom/turtle/'\n self.stub_os.path.should_exist = [\n self.stub_os.path.join('/long', util.PROJECT_SPEC_FILENAME),\n self.stub_os.path.join('/long/way/down/to/top',\n util.PROJECT_SPEC_FILENAME),\n self.stub_os.path.join('/long/way', util.PROJECT_SPEC_FILENAME)]\n # Make sure we find the closest in our direct path.\n self.assertEqual(util.FindProjectSpec(),\n self.stub_os.path.join('/long/way',\n util.PROJECT_SPEC_FILENAME))\n\n def test_get_no_project_spec(self):\n self.stub_os.cwd = '/long/way/down/to/the/bottom/turtle/'\n self.stub_os.path.should_exist = [\n self.stub_os.path.join('/other', util.PROJECT_SPEC_FILENAME)]\n self.assertEqual(util.FindProjectSpec(), None)\n\n def test_get_host(self):\n self.stub_os.SetUname(('Linux', 'host_name.website.com',\n '99.99-awesome', 'stuff', 'x86_64'))\n self.assertEqual(util.GetHostArch(), 'linux-x86')\n\n def test_get_bad_host(self):\n self.stub_os.SetUname(('OSX', 'host_name.website.com', '99.99-awesome',\n 'stuff', 'x86_64'))\n with self.assertRaises(util.HostUnsupportedArchError):\n util.GetHostArch()\n","sub_path":"cli/lib/core/util_unittest.py","file_name":"util_unittest.py","file_ext":"py","file_size_in_byte":3704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"204957736","text":"from userKov.pyGeneralRoutines.generalRoutines import *\nimport sys\nfrom numpy import *\nimport os\n\nif __name__==\"__main__\":\n if (len(sys.argv)==1):\n filename= raw_input('give a filename')\n else:\n filename=sys.argv[1]\n \n stTh=loadCol(filename,0)[0]\n stTh=stTh[1:] #remove substrate\n if (len(stTh)!=int(len(stTh)/2)*2):\n stTh.append(0)\n stTh=array(stTh)\n #crea dati su due colonne e li scrive su file\n stTh=reshape(stTh,(-1,2))\n outfile=\"_2col\".join(os.path.splitext(filename))\n of=open (outfile,'w')\n for l in stTh:\n of.write(\"%s\\t%s\\n\"%tuple(l))\n #print l\n of.close()","sub_path":"pyPPM/thExtract.py","file_name":"thExtract.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"541041623","text":"import os\nfrom inspect import Parameter\nfrom inspect import Signature\nfrom argparse import ArgumentParser\n\n\ndef randkey(n=32, printit=True):\n s = os.urandom(n).hex()\n if printit:\n print(s)\n return s\n\n\ndef argparse_for_func(func, subparser=None, suppress=False) -> ArgumentParser:\n if subparser:\n parser = subparser.add_parser(func.__name__, help=f'help for {func.__name__}')\n else:\n parser = ArgumentParser()\n added_pshorts = []\n sig = Signature.from_callable(func)\n\n for param in sig.parameters.values():\n\n if param.kind in [Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD]:\n if not suppress:\n raise NotImplementedError('cannot build argparse for var arg defs')\n\n elif param.default == Parameter.empty:\n parser.add_argument(param.name)\n\n elif param.kind in [Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY]:\n pname = f'--{param.name.replace(\"_\", \"-\")}'\n pshort = f'-{param.name[0]}'\n cli_names = (pname,) if pshort in added_pshorts else (pshort, pname)\n added_pshorts.append(pshort)\n\n if param.default is None or type(param.default) == list:\n parser.add_argument(\n *cli_names, nargs='+', default=param.default)\n\n elif type(param.default) in [int, float, str]:\n parser.add_argument(\n *cli_names, type=type(param.default), default=param.default)\n\n elif type(param.default) == bool:\n parser.add_argument(\n *cli_names, action='store_true', default=param.default)\n\n return parser\n","sub_path":"tkpy/tkpy/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"134637175","text":"# -*- coding:utf-8 -*-\n# 给定一个 $m \\times n$的实数矩阵,通过改变一整列或一整行的数字的符号,使得所有行和列之和非负\n\nimport numpy as np\n\ndef nonPos_mat(matX):\n matX_o = matX.copy()\n sumation = np.sum(matX)\n print(sumation)\n m, n = matX.shape\n\n while True:\n for i in range(m):\n if not isSum_nonPos(matX[i, :]):\n flip_vec(matX[i, :])\n print('Fliping row: ', i)\n print('Sum of row: ', i, 'is ', np.sum(matX[i, :]))\n\n for j in range(n):\n if not isSum_nonPos(matX[:, j]):\n flip_vec(matX[:, j])\n print('Fliping col: ', j)\n print('Sum of co;: ', j, 'is ', np.sum(matX[:, j]))\n\n if np.sum(matX) > sumation:\n sumation = np.sum(matX)\n print(sumation)\n else:\n print('Finished')\n print(matX)\n break\n\ndef flip_vec(vec):\n # 翻转一整行或一整列\n for i in range(len(vec)):\n vec[i] = -vec[i]\n\ndef isSum_nonPos(vec):\n # 判断一整行或一整列之和是否非负\n return np.sum(vec) >= 0\n\n\nif __name__ == '__main__':\n matX = np.ceil(np.random.rand(10,10)*10 - 5)\n print(matX)\n nonPos_mat(matX)\n\n","sub_path":"puzzles/positiveMat.py","file_name":"positiveMat.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"262424246","text":"#!/usr/bin/env python3\n\n# Homework 1 - Program 1\n# Jake Hamilton\n# 1029662\n# This program calculates the gravitational pull on Earth from\n# a given mass\n\n# Earth's Radius\nearth_radius = (6378 * (10 ** 3))\n\n# Earth's Mass\nearth_mass = (5.9742 * (10 ** 24))\n\n# Gravity Constant\nuniversal_gravity = (6.67300 * (10 ** -11))\n\n# Mass of the user as a floating point number\nmass = float(input('Input your mass: '))\n\n# F = gravity * earth_mass * mass / (earth_radius ** 2)\nforce = (universal_gravity * earth_mass * mass) / (earth_radius ** 2)\ngravity = force / mass\n\n# Output the resulting gravitational force\nprint('The resulting value of g is {:.4f} which is close to the Earth\\'s gravitational force'.format(gravity))\n\n### OUTPUT ###\n\"\"\"\nshort@null:~/class/python/homework/01$ ./program_1.py\nInput your mass: 27\nThe resulting value of g is 9.8001 which is close to the Earth's gravitational force\n\"\"\"\n","sub_path":"homework/01/program_1.py","file_name":"program_1.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"582373838","text":"#This Source Code Form is subject to the terms of the Mozilla Public\n#License, v. 2.0. If a copy of the MPL was not distributed with this\n#file, You can obtain one at http://mozilla.org/MPL/2.0/. */\n#Created by Fabrice Fernandez on 22/07/2019.\n\nimport string\nimport NatronEngine\nfrom NatronGui import *\n\n\n# CREATE A LEFT ALIGNED TRIANGLE #\n\ndef leftTriangle():\n\n\t# get current Natron instance running in memory\n\tapp = natron.getGuiInstance(0)\n\n\t# create a 'Roto' node\n\tmyRoto = app.createNode(\"fr.inria.built-in.Roto\")\n\n\t# set 'Roto' label\n\tmyRoto.setLabel('left_Triangle1')\n\n\t# get input image size\n\timageWidth = myRoto.getOutputFormat().width()\n\n\timageHeight = myRoto.getOutputFormat().height()\n\n\n\n\n\t# get roto context\n\trotoContext = myRoto.getRotoContext()\n\n\t# get 'Base Layer'\n\trootLayer = rotoContext.getBaseLayer()\n\n\n\n\n\t# create one point bezier curve at frame 1\n\tnewTriangle = rotoContext.createBezier( 0.0 , 0.0 , 1 )\n\n\tnewTriangle.setScriptName(\"left_Triangle1\")\n\tnewTriangle.setLabel(\"left_Triangle1\")\n\tnewTriangle.setLocked(False)\n\tnewTriangle.setVisible(True)\n\n\n\t# add created bezier to 'Base Layer'\n\trootLayer.addItem(newTriangle)\n\n\tnewTriangle.addControlPoint( 0.0 , imageHeight )\n\tnewTriangle.addControlPoint( imageWidth/2 , imageHeight/2 )\n\tnewTriangle.setCurveFinished(1)\n\n\t# set center position\n\tmyRoto.getParam('center').setValue(imageWidth/2,0)\n\tmyRoto.getParam('center').setValue(imageHeight/2,1)","sub_path":"Python_GUI/leftTriangle/leftTriangle.py","file_name":"leftTriangle.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"305374368","text":"import logging\nfrom queue import Empty\n\nimport pytest\nfrom ska_tango_base.base.task_queue_manager import TaskResult\nfrom ska_tango_base.commands import ResultCode\nfrom tango import EventType\n\nfrom ska_tango_examples.teams.long_running.Controller import LRController\nfrom ska_tango_examples.teams.long_running.Station import Station\nfrom ska_tango_examples.teams.long_running.Tile import Tile\n\nfrom .utils import LRCAttributesStore\n\nlogger = logging.getLogger(__name__)\n\ndevices_to_test = [\n {\n \"class\": LRController,\n \"devices\": [\n {\n \"name\": \"test/lrccontroller/1\",\n \"properties\": {\n \"stations\": [\"test/lrcstation/1\", \"test/lrcstation/2\"]\n },\n }\n ],\n },\n {\n \"class\": Station,\n \"devices\": [\n {\n \"name\": \"test/lrcstation/1\",\n \"properties\": {\"tiles\": [\"test/lrctile/1\", \"test/lrctile/2\"]},\n },\n {\n \"name\": \"test/lrcstation/2\",\n \"properties\": {\"tiles\": [\"test/lrctile/3\", \"test/lrctile/4\"]},\n },\n ],\n },\n {\n \"class\": Tile,\n \"devices\": [\n {\"name\": \"test/lrctile/1\"},\n {\"name\": \"test/lrctile/2\"},\n {\"name\": \"test/lrctile/3\"},\n {\"name\": \"test/lrctile/4\"},\n ],\n },\n]\n\n\nclass TestLRC:\n @pytest.mark.forked\n def test_long_running_device_client_on(self, multi_device_tango_context):\n store = LRCAttributesStore()\n controller = multi_device_tango_context.get_device(\n \"test/lrccontroller/1\"\n )\n controller.subscribe_event(\n \"longRunningCommandResult\",\n EventType.CHANGE_EVENT,\n store,\n wait=True,\n )\n\n controller.On()\n\n for timing in [2, 2, 2, 2]:\n try:\n val = store.get_attribute_value(\n \"longRunningCommandResult\", fetch_timeout=timing\n )\n if val[2] == \"Controller On completed\":\n break\n except Empty:\n continue\n else:\n assert 0, \"Controller On not completed\"\n\n @pytest.mark.forked\n def test_long_running_device_client_off(self, multi_device_tango_context):\n store = LRCAttributesStore()\n controller = multi_device_tango_context.get_device(\n \"test/lrccontroller/1\"\n )\n controller.subscribe_event(\n \"longRunningCommandResult\",\n EventType.CHANGE_EVENT,\n store,\n wait=True,\n )\n\n controller.Off()\n\n for timing in [2, 2, 2, 2]:\n try:\n val = store.get_attribute_value(\n \"longRunningCommandResult\", fetch_timeout=timing\n )\n if val[2] == \"Controller Off completed\":\n break\n except Empty:\n continue\n else:\n assert 0, \"Controller Off not completed\"\n\n @pytest.mark.forked\n def test_long_running_device_client_scan(self, multi_device_tango_context):\n store = LRCAttributesStore()\n controller = multi_device_tango_context.get_device(\n \"test/lrccontroller/1\"\n )\n station = multi_device_tango_context.get_device(\"test/lrcstation/1\")\n tile = multi_device_tango_context.get_device(\"test/lrctile/1\")\n controller.subscribe_event(\n \"longRunningCommandResult\",\n EventType.CHANGE_EVENT,\n store,\n wait=True,\n )\n\n controller.Scan()\n\n for timing in [2, 2, 2, 2, 2]:\n try:\n val = store.get_attribute_value(\n \"longRunningCommandResult\", fetch_timeout=timing\n )\n if val[2] == \"Controller Scan completed\":\n break\n except Empty:\n continue\n else:\n assert 0, \"Controller Scan not completed\"\n\n # Make sure a tile and a station has a result\n station_result = TaskResult.from_task_result(\n station.longRunningCommandResult\n )\n assert \"ScanCommand\" in station_result.unique_id\n assert int(station_result.result_code) == ResultCode.OK\n assert station_result.task_result == \"Station Scan completed\"\n\n tile_result = TaskResult.from_task_result(\n tile.longRunningCommandResult\n )\n assert \"ScanCommand\" in tile_result.unique_id\n assert int(tile_result.result_code) == ResultCode.OK\n assert tile_result.task_result == \"Tile Scan completed\"\n","sub_path":"tests/unit/test_long_running.py","file_name":"test_long_running.py","file_ext":"py","file_size_in_byte":4661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"86928483","text":"#!/usr/bin/python\n# Copyright: Ansible Project\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'}\n\nDOCUMENTATION = '''\n---\nmodule: ecs_attribute\nshort_description: manage ecs attributes\ndescription:\n - Create, update or delete ECS container instance attributes.\nversion_added: \"2.4\"\nauthor: Andrej Svenke (@anryko)\nrequirements: [ botocore, boto3 ]\noptions:\n cluster:\n description:\n - The short name or full Amazon Resource Name (ARN) of the cluster\n that contains the resource to apply attributes.\n required: true\n state:\n description:\n - The desired state of the attributes.\n required: false\n default: present\n choices: ['present', 'absent']\n attributes:\n description:\n - List of attributes.\n required: true\n suboptions:\n name:\n description:\n - The name of the attribute. Up to 128 letters (uppercase and lowercase),\n numbers, hyphens, underscores, and periods are allowed.\n required: true\n value:\n description:\n - The value of the attribute. Up to 128 letters (uppercase and lowercase),\n numbers, hyphens, underscores, periods, at signs (@), forward slashes, colons,\n and spaces are allowed.\n required: false\n ec2_instance_id:\n description:\n - EC2 instance ID of ECS cluster container instance.\n required: true\nextends_documentation_fragment:\n - aws\n - ec2\n'''\n\nEXAMPLES = '''\n# Note: These examples do not set authentication details, see the AWS Guide for details.\n\n# Set attributes\n- ecs_attribute:\n state: present\n cluster: test-cluster\n ec2_instance_id: \"{{ ec2_id }}\"\n attributes:\n - flavor: test\n - migrated\n delegate_to: localhost\n\n# Delete attributes\n- ecs_attribute:\n state: absent\n cluster: test-cluster\n ec2_instance_id: \"{{ ec2_id }}\"\n attributes:\n - flavor: test\n - migrated\n delegate_to: localhost\n'''\n\nRETURN = '''\nattributes:\n description: attributes\n type: complex\n returned: always\n contains:\n cluster:\n description: cluster name\n type: str\n ec2_instance_id:\n description: ec2 instance id of ecs container instance\n type: str\n attributes:\n description: list of attributes\n type: list of complex\n contains:\n name:\n description: name of the attribute\n type: str\n value:\n description: value of the attribute\n returned: if present\n type: str\n'''\n\ntry:\n import boto3\n from botocore.exceptions import ClientError, EndpointConnectionError\n HAS_BOTO3 = True\nexcept ImportError:\n HAS_BOTO3 = False\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils.ec2 import boto3_conn, ec2_argument_spec, get_aws_connection_info\n\n\nclass EcsAttributes(object):\n \"\"\"Handles ECS Cluster Attribute\"\"\"\n\n def __init__(self, module, attributes):\n self.module = module\n self.attributes = attributes if self._validate_attrs(attributes) else self._parse_attrs(attributes)\n\n def __bool__(self):\n return bool(self.attributes)\n\n __nonzero__ = __bool__\n\n def __iter__(self):\n return iter(self.attributes)\n\n @staticmethod\n def _validate_attrs(attrs):\n return all(tuple(attr.keys()) in (('name', 'value'), ('value', 'name')) for attr in attrs)\n\n def _parse_attrs(self, attrs):\n attrs_parsed = []\n for attr in attrs:\n if isinstance(attr, dict):\n if len(attr) != 1:\n self.module.fail_json(msg=\"Incorrect attribute format - %s\" % str(attr))\n name, value = list(attr.items())[0]\n attrs_parsed.append({'name': name, 'value': value})\n elif isinstance(attr, str):\n attrs_parsed.append({'name': attr, 'value': None})\n else:\n self.module.fail_json(msg=\"Incorrect attributes format - %s\" % str(attrs))\n\n return attrs_parsed\n\n def _setup_attr_obj(self, ecs_arn, name, value=None, skip_value=False):\n attr_obj = {'targetType': 'container-instance',\n 'targetId': ecs_arn,\n 'name': name}\n if not skip_value and value is not None:\n attr_obj['value'] = value\n\n return attr_obj\n\n def get_for_ecs_arn(self, ecs_arn, skip_value=False):\n \"\"\"\n Returns list of attribute dicts ready to be passed to boto3\n attributes put/delete methods.\n \"\"\"\n return [self._setup_attr_obj(ecs_arn, skip_value=skip_value, **attr) for attr in self.attributes]\n\n def diff(self, attrs):\n \"\"\"\n Returns EcsAttributes Object containing attributes which are present\n in self but are absent in passed attrs (EcsAttributes Object).\n \"\"\"\n attrs_diff = [attr for attr in self.attributes if attr not in attrs]\n return EcsAttributes(self.module, attrs_diff)\n\n\nclass Ec2EcsInstance(object):\n \"\"\"Handle ECS Cluster Remote Operations\"\"\"\n\n def __init__(self, module, cluster, ec2_id):\n self.module = module\n self.cluster = cluster\n self.ec2_id = ec2_id\n\n region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True)\n if not region:\n module.fail_json(msg=(\"Region must be specified as a parameter,\"\n \" in EC2_REGION or AWS_REGION environment\"\n \" variables or in boto configuration file\"))\n self.ecs = boto3_conn(module, conn_type='client', resource='ecs',\n region=region, endpoint=ec2_url, **aws_connect_kwargs)\n\n self.ecs_arn = self._get_ecs_arn()\n\n def _get_ecs_arn(self):\n try:\n ecs_instances_arns = self.ecs.list_container_instances(cluster=self.cluster)['containerInstanceArns']\n ec2_instances = self.ecs.describe_container_instances(cluster=self.cluster,\n containerInstances=ecs_instances_arns)['containerInstances']\n except (ClientError, EndpointConnectionError) as e:\n self.module.fail_json(msg=\"Can't connect to the cluster - %s\" % str(e))\n\n try:\n ecs_arn = next(inst for inst in ec2_instances\n if inst['ec2InstanceId'] == self.ec2_id)['containerInstanceArn']\n except StopIteration:\n self.module.fail_json(msg=\"EC2 instance Id not found in ECS cluster - %s\" % str(self.cluster))\n\n return ecs_arn\n\n def attrs_put(self, attrs):\n \"\"\"Puts attributes on ECS container instance\"\"\"\n try:\n self.ecs.put_attributes(cluster=self.cluster,\n attributes=attrs.get_for_ecs_arn(self.ecs_arn))\n except ClientError as e:\n self.module.fail_json(msg=str(e))\n\n def attrs_delete(self, attrs):\n \"\"\"Deletes attributes from ECS container instance.\"\"\"\n try:\n self.ecs.delete_attributes(cluster=self.cluster,\n attributes=attrs.get_for_ecs_arn(self.ecs_arn, skip_value=True))\n except ClientError as e:\n self.module.fail_json(msg=str(e))\n\n def attrs_get_by_name(self, attrs):\n \"\"\"\n Returns EcsAttributes object containing attributes from ECS container instance with names\n matching to attrs.attributes (EcsAttributes Object).\n \"\"\"\n attr_objs = [{'targetType': 'container-instance', 'attributeName': attr['name']}\n for attr in attrs]\n\n try:\n matched_ecs_targets = [attr_found for attr_obj in attr_objs\n for attr_found in self.ecs.list_attributes(cluster=self.cluster, **attr_obj)['attributes']]\n except ClientError as e:\n self.module.fail_json(msg=\"Can't connect to the cluster - %s\" % str(e))\n\n matched_objs = [target for target in matched_ecs_targets\n if target['targetId'] == self.ecs_arn]\n\n results = [{'name': match['name'], 'value': match.get('value', None)}\n for match in matched_objs]\n\n return EcsAttributes(self.module, results)\n\n\ndef main():\n argument_spec = ec2_argument_spec()\n argument_spec.update(dict(\n state=dict(required=False, default='present', choices=['present', 'absent']),\n cluster=dict(required=True, type='str'),\n ec2_instance_id=dict(required=True, type='str'),\n attributes=dict(required=True, type='list'),\n ))\n\n required_together = [['cluster', 'ec2_instance_id', 'attributes']]\n\n module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True,\n required_together=required_together)\n\n if not HAS_BOTO3:\n module.fail_json(msg='boto3 is required.')\n\n cluster = module.params['cluster']\n ec2_instance_id = module.params['ec2_instance_id']\n attributes = module.params['attributes']\n\n conti = Ec2EcsInstance(module, cluster, ec2_instance_id)\n attrs = EcsAttributes(module, attributes)\n\n results = {'changed': False,\n 'attributes': [\n {'cluster': cluster,\n 'ec2_instance_id': ec2_instance_id,\n 'attributes': attributes}\n ]}\n\n attrs_present = conti.attrs_get_by_name(attrs)\n\n if module.params['state'] == 'present':\n attrs_diff = attrs.diff(attrs_present)\n if not attrs_diff:\n module.exit_json(**results)\n\n conti.attrs_put(attrs_diff)\n results['changed'] = True\n\n elif module.params['state'] == 'absent':\n if not attrs_present:\n module.exit_json(**results)\n\n conti.attrs_delete(attrs_present)\n results['changed'] = True\n\n module.exit_json(**results)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"env/lib/python3.9/site-packages/ansible/modules/cloud/amazon/ecs_attribute.py","file_name":"ecs_attribute.py","file_ext":"py","file_size_in_byte":10406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"593209095","text":"from flask.blueprints import Blueprint\nfrom flask import jsonify,request\nimport psqlconfigutils\nfrom models import(User,base)\nimport json\n\n\n\nuserBluePrint=Blueprint('userBluePrint20',__name__)\n\n@userBluePrint.route('/',methods=['GET'])\ndef get():\n records = psqlconfigutils.session.query(User).all()\n return json.dumps(User.serialize_list(records))\n\n\n\n\n\n@userBluePrint.route('/user',methods=['POST'])\ndef create_record():\n id=request.json['id']\n name=request.json['name']\n full_name=request.json['full_name']\n newUser=User(id=id,name=name,full_name=full_name)\n psqlconfigutils.session.add(newUser)\n psqlconfigutils.session.commit()\n return None\n\n\n@userBluePrint.route('/ViewUser')\ndef view_user():\n return 'view user'\n\n\n@userBluePrint.route('/PostSalary',methods=['POST'])\ndef create_salary():\n id = request.json['id']\n name= request.json['name']\n emp_salary = request.json['emp_salary']\n PositionLevel = request.json['PositionLevel']\n Position = request.json['Position']\n fk_declrative = request.json['fk_declrative']\n\n new_salary_record=Salary(id=id,name=name,emp_salary=emp_salary,PositionLevel=PositionLevel,Position=Position,fk_declrative=fk_declrative)\n print(Salary.__table__)\n psqlconfigutils.session.add(new_salary_record)\n psqlconfigutils.session.commit()\n return 'Success'\n\n\n# @userBluePrint.route('/PostSalary',methods=['POST'])\n# def get_salary(id):\n\n\n\n\n# @userBluePrint.route('/StudentTb',methods=['POST'])\n# def create_student():\n","sub_path":"project/BlueprintRount.py","file_name":"BlueprintRount.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"246563256","text":"# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0.\n\nfrom awscrt import mqtt, http\nfrom awsiot import iotidentity, mqtt_connection_builder\nfrom concurrent.futures import Future\nimport sys\nimport threading\nimport time\nimport traceback\nimport json\nfrom utils.command_line_utils import CommandLineUtils\n\n# - Overview -\n# This sample uses the AWS IoT Fleet Provisioning to provision device using either the keys\n# or CSR\n#\n#\n# - Instructions -\n# This sample requires you to create a provisioning claim. See:\n# https://docs.aws.amazon.com/iot/latest/developerguide/provision-wo-cert.html\n#\n# - Detail -\n# On startup, the script subscribes to topics based on the request type of either CSR or Keys\n# publishes the request to corresponding topic and calls RegisterThing.\n\n# cmdData is the arguments/input from the command line placed into a single struct for\n# use in this sample. This handles all of the command line parsing, validating, etc.\n# See the Utils/CommandLineUtils for more information.\ncmdData = CommandLineUtils.parse_sample_input_fleet_provisioning()\n\n# Using globals to simplify sample code\nis_sample_done = threading.Event()\nmqtt_connection = None\nidentity_client = None\ncreateKeysAndCertificateResponse = None\ncreateCertificateFromCsrResponse = None\nregisterThingResponse = None\n\n\nclass LockedData:\n def __init__(self):\n self.lock = threading.Lock()\n self.disconnect_called = False\n\n\nlocked_data = LockedData()\n\n# Function for gracefully quitting this sample\ndef exit(msg_or_exception):\n if isinstance(msg_or_exception, Exception):\n print(\"Exiting Sample due to exception.\")\n traceback.print_exception(msg_or_exception.__class__, msg_or_exception, sys.exc_info()[2])\n else:\n print(\"Exiting Sample:\", msg_or_exception)\n\n with locked_data.lock:\n if not locked_data.disconnect_called:\n print(\"Disconnecting...\")\n locked_data.disconnect_called = True\n future = mqtt_connection.disconnect()\n future.add_done_callback(on_disconnected)\n\n\ndef on_disconnected(disconnect_future):\n # type: (Future) -> None\n print(\"Disconnected.\")\n\n # Signal that sample is finished\n is_sample_done.set()\n\n\ndef on_publish_register_thing(future):\n # type: (Future) -> None\n try:\n future.result() # raises exception if publish failed\n print(\"Published RegisterThing request..\")\n\n except Exception as e:\n print(\"Failed to publish RegisterThing request.\")\n exit(e)\n\n\ndef on_publish_create_keys_and_certificate(future):\n # type: (Future) -> None\n try:\n future.result() # raises exception if publish failed\n print(\"Published CreateKeysAndCertificate request..\")\n\n except Exception as e:\n print(\"Failed to publish CreateKeysAndCertificate request.\")\n exit(e)\n\n\ndef on_publish_create_certificate_from_csr(future):\n # type: (Future) -> None\n try:\n future.result() # raises exception if publish failed\n print(\"Published CreateCertificateFromCsr request..\")\n\n except Exception as e:\n print(\"Failed to publish CreateCertificateFromCsr request.\")\n exit(e)\n\n\ndef createkeysandcertificate_execution_accepted(response):\n # type: (iotidentity.CreateKeysAndCertificateResponse) -> None\n try:\n global createKeysAndCertificateResponse\n createKeysAndCertificateResponse = response\n if (cmdData.input_is_ci == False):\n print(\"Received a new message {}\".format(createKeysAndCertificateResponse))\n\n return\n\n except Exception as e:\n exit(e)\n\n\ndef createkeysandcertificate_execution_rejected(rejected):\n # type: (iotidentity.RejectedError) -> None\n exit(\"CreateKeysAndCertificate Request rejected with code:'{}' message:'{}' status code:'{}'\".format(\n rejected.error_code, rejected.error_message, rejected.status_code))\n\n\ndef createcertificatefromcsr_execution_accepted(response):\n # type: (iotidentity.CreateCertificateFromCsrResponse) -> None\n try:\n global createCertificateFromCsrResponse\n createCertificateFromCsrResponse = response\n if (cmdData.input_is_ci == False):\n print(\"Received a new message {}\".format(createCertificateFromCsrResponse))\n global certificateOwnershipToken\n certificateOwnershipToken = response.certificate_ownership_token\n\n return\n\n except Exception as e:\n exit(e)\n\n\ndef createcertificatefromcsr_execution_rejected(rejected):\n # type: (iotidentity.RejectedError) -> None\n exit(\"CreateCertificateFromCsr Request rejected with code:'{}' message:'{}' status code:'{}'\".format(\n rejected.error_code, rejected.error_message, rejected.status_code))\n\n\ndef registerthing_execution_accepted(response):\n # type: (iotidentity.RegisterThingResponse) -> None\n try:\n global registerThingResponse\n registerThingResponse = response\n if (cmdData.input_is_ci == False):\n print(\"Received a new message {} \".format(registerThingResponse))\n return\n\n except Exception as e:\n exit(e)\n\n\ndef registerthing_execution_rejected(rejected):\n # type: (iotidentity.RejectedError) -> None\n exit(\"RegisterThing Request rejected with code:'{}' message:'{}' status code:'{}'\".format(\n rejected.error_code, rejected.error_message, rejected.status_code))\n\n# Callback when connection is accidentally lost.\ndef on_connection_interrupted(connection, error, **kwargs):\n print(\"Connection interrupted. error: {}\".format(error))\n\n\n# Callback when an interrupted connection is re-established.\ndef on_connection_resumed(connection, return_code, session_present, **kwargs):\n print(\"Connection resumed. return_code: {} session_present: {}\".format(return_code, session_present))\n\n if return_code == mqtt.ConnectReturnCode.ACCEPTED and not session_present:\n print(\"Session did not persist. Resubscribing to existing topics...\")\n resubscribe_future, _ = connection.resubscribe_existing_topics()\n\n # Cannot synchronously wait for resubscribe result because we're on the connection's event-loop thread,\n # evaluate result with a callback instead.\n resubscribe_future.add_done_callback(on_resubscribe_complete)\n\n\ndef on_resubscribe_complete(resubscribe_future):\n resubscribe_results = resubscribe_future.result()\n print(\"Resubscribe results: {}\".format(resubscribe_results))\n\n for topic, qos in resubscribe_results['topics']:\n if qos is None:\n sys.exit(\"Server rejected resubscribe to topic: {}\".format(topic))\n\n\ndef waitForCreateKeysAndCertificateResponse():\n # Wait for the response.\n loopCount = 0\n while loopCount < 10 and createKeysAndCertificateResponse is None:\n if createKeysAndCertificateResponse is not None:\n break\n if not cmdData.input_is_ci:\n print('Waiting... CreateKeysAndCertificateResponse: ' + json.dumps(createKeysAndCertificateResponse))\n else:\n print(\"Waiting... CreateKeysAndCertificateResponse: ...\")\n loopCount += 1\n time.sleep(1)\n\n\ndef waitForCreateCertificateFromCsrResponse():\n # Wait for the response.\n loopCount = 0\n while loopCount < 10 and createCertificateFromCsrResponse is None:\n if createCertificateFromCsrResponse is not None:\n break\n if not cmdData.input_is_ci:\n print('Waiting...CreateCertificateFromCsrResponse: ' + json.dumps(createCertificateFromCsrResponse))\n else:\n print(\"Waiting... CreateCertificateFromCsrResponse: ...\")\n loopCount += 1\n time.sleep(1)\n\n\ndef waitForRegisterThingResponse():\n # Wait for the response.\n loopCount = 0\n while loopCount < 20 and registerThingResponse is None:\n if registerThingResponse is not None:\n break\n loopCount += 1\n if not cmdData.input_is_ci:\n print('Waiting... RegisterThingResponse: ' + json.dumps(registerThingResponse))\n else:\n print('Waiting... RegisterThingResponse: ...')\n time.sleep(1)\n\n\nif __name__ == '__main__':\n # Create the proxy options if the data is present in cmdData\n proxy_options = None\n if cmdData.input_proxy_host is not None and cmdData.input_proxy_port != 0:\n proxy_options = http.HttpProxyOptions(\n host_name=cmdData.input_proxy_host,\n port=cmdData.input_proxy_port)\n\n # Create a MQTT connection from the command line data\n mqtt_connection = mqtt_connection_builder.mtls_from_path(\n endpoint=cmdData.input_endpoint,\n port=cmdData.input_port,\n cert_filepath=cmdData.input_cert,\n pri_key_filepath=cmdData.input_key,\n ca_filepath=cmdData.input_ca,\n on_connection_interrupted=on_connection_interrupted,\n on_connection_resumed=on_connection_resumed,\n client_id=cmdData.input_clientId,\n clean_session=False,\n keep_alive_secs=30,\n http_proxy_options=proxy_options)\n\n if not cmdData.input_is_ci:\n print(f\"Connecting to {cmdData.input_endpoint} with client ID '{cmdData.input_clientId}'...\")\n else:\n print(\"Connecting to endpoint with client ID\")\n\n connected_future = mqtt_connection.connect()\n\n identity_client = iotidentity.IotIdentityClient(mqtt_connection)\n\n # Wait for connection to be fully established.\n # Note that it's not necessary to wait, commands issued to the\n # mqtt_connection before its fully connected will simply be queued.\n # But this sample waits here so it's obvious when a connection\n # fails or succeeds.\n connected_future.result()\n print(\"Connected!\")\n\n try:\n # Subscribe to necessary topics.\n # Note that is **is** important to wait for \"accepted/rejected\" subscriptions\n # to succeed before publishing the corresponding \"request\".\n\n # Keys workflow if csr is not provided\n if cmdData.input_csr_path is None:\n createkeysandcertificate_subscription_request = iotidentity.CreateKeysAndCertificateSubscriptionRequest()\n\n print(\"Subscribing to CreateKeysAndCertificate Accepted topic...\")\n createkeysandcertificate_subscribed_accepted_future, _ = identity_client.subscribe_to_create_keys_and_certificate_accepted(\n request=createkeysandcertificate_subscription_request,\n qos=mqtt.QoS.AT_LEAST_ONCE,\n callback=createkeysandcertificate_execution_accepted)\n\n # Wait for subscription to succeed\n createkeysandcertificate_subscribed_accepted_future.result()\n\n print(\"Subscribing to CreateKeysAndCertificate Rejected topic...\")\n createkeysandcertificate_subscribed_rejected_future, _ = identity_client.subscribe_to_create_keys_and_certificate_rejected(\n request=createkeysandcertificate_subscription_request,\n qos=mqtt.QoS.AT_LEAST_ONCE,\n callback=createkeysandcertificate_execution_rejected)\n\n # Wait for subscription to succeed\n createkeysandcertificate_subscribed_rejected_future.result()\n else:\n createcertificatefromcsr_subscription_request = iotidentity.CreateCertificateFromCsrSubscriptionRequest()\n\n print(\"Subscribing to CreateCertificateFromCsr Accepted topic...\")\n createcertificatefromcsr_subscribed_accepted_future, _ = identity_client.subscribe_to_create_certificate_from_csr_accepted(\n request=createcertificatefromcsr_subscription_request,\n qos=mqtt.QoS.AT_LEAST_ONCE,\n callback=createcertificatefromcsr_execution_accepted)\n\n # Wait for subscription to succeed\n createcertificatefromcsr_subscribed_accepted_future.result()\n\n print(\"Subscribing to CreateCertificateFromCsr Rejected topic...\")\n createcertificatefromcsr_subscribed_rejected_future, _ = identity_client.subscribe_to_create_certificate_from_csr_rejected(\n request=createcertificatefromcsr_subscription_request,\n qos=mqtt.QoS.AT_LEAST_ONCE,\n callback=createcertificatefromcsr_execution_rejected)\n\n # Wait for subscription to succeed\n createcertificatefromcsr_subscribed_rejected_future.result()\n\n registerthing_subscription_request = iotidentity.RegisterThingSubscriptionRequest(\n template_name=cmdData.input_template_name)\n\n print(\"Subscribing to RegisterThing Accepted topic...\")\n registerthing_subscribed_accepted_future, _ = identity_client.subscribe_to_register_thing_accepted(\n request=registerthing_subscription_request,\n qos=mqtt.QoS.AT_LEAST_ONCE,\n callback=registerthing_execution_accepted)\n\n # Wait for subscription to succeed\n registerthing_subscribed_accepted_future.result()\n\n print(\"Subscribing to RegisterThing Rejected topic...\")\n registerthing_subscribed_rejected_future, _ = identity_client.subscribe_to_register_thing_rejected(\n request=registerthing_subscription_request,\n qos=mqtt.QoS.AT_LEAST_ONCE,\n callback=registerthing_execution_rejected)\n # Wait for subscription to succeed\n registerthing_subscribed_rejected_future.result()\n\n fleet_template_name = cmdData.input_template_name\n fleet_template_parameters = cmdData.input_template_parameters\n if cmdData.input_csr_path is None:\n print(\"Publishing to CreateKeysAndCertificate...\")\n publish_future = identity_client.publish_create_keys_and_certificate(\n request=iotidentity.CreateKeysAndCertificateRequest(), qos=mqtt.QoS.AT_LEAST_ONCE)\n publish_future.add_done_callback(on_publish_create_keys_and_certificate)\n\n waitForCreateKeysAndCertificateResponse()\n\n if createKeysAndCertificateResponse is None:\n raise Exception('CreateKeysAndCertificate API did not succeed')\n\n registerThingRequest = iotidentity.RegisterThingRequest(\n template_name=fleet_template_name,\n certificate_ownership_token=createKeysAndCertificateResponse.certificate_ownership_token,\n parameters=json.loads(fleet_template_parameters))\n else:\n print(\"Publishing to CreateCertificateFromCsr...\")\n csrPath = open(cmdData.input_csr_path, 'r').read()\n publish_future = identity_client.publish_create_certificate_from_csr(\n request=iotidentity.CreateCertificateFromCsrRequest(certificate_signing_request=csrPath),\n qos=mqtt.QoS.AT_LEAST_ONCE)\n publish_future.add_done_callback(on_publish_create_certificate_from_csr)\n\n waitForCreateCertificateFromCsrResponse()\n\n if createCertificateFromCsrResponse is None:\n raise Exception('CreateCertificateFromCsr API did not succeed')\n\n registerThingRequest = iotidentity.RegisterThingRequest(\n template_name=fleet_template_name,\n certificate_ownership_token=createCertificateFromCsrResponse.certificate_ownership_token,\n parameters=json.loads(fleet_template_parameters))\n\n print(\"Publishing to RegisterThing topic...\")\n registerthing_publish_future = identity_client.publish_register_thing(\n registerThingRequest, mqtt.QoS.AT_LEAST_ONCE)\n registerthing_publish_future.add_done_callback(on_publish_register_thing)\n\n waitForRegisterThingResponse()\n exit(\"success\")\n\n except Exception as e:\n exit(e)\n\n # Wait for the sample to finish\n is_sample_done.wait()\n","sub_path":"samples/fleetprovisioning.py","file_name":"fleetprovisioning.py","file_ext":"py","file_size_in_byte":15682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"566331196","text":"\n#\n# Hubblemon - Yet another general purpose system monitor\n#\n# Copyright 2015 NAVER Corp.\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\nimport os, sys, telnetlib\nfrom syslog import syslog\n\nhubblemon_path = os.path.join(os.path.dirname(__file__), '..')\nsys.path.append(hubblemon_path)\n\nimport common.core\nfrom common.core import * # for query eval (like, return_as_table)\n\nfrom django import forms\nimport redis\n\ndef auth_fields(param):\n\tid = forms.CharField(label = 'id', required = False)\n\tpw = forms.CharField(label = 'pw', widget = forms.PasswordInput(), required = False)\n\treturn [id, pw]\n\n\ndef do_redis_command(ip, port, command, timeout=0.2):\n\ttn = telnetlib.Telnet(ip, port)\n\ttn.write(bytes(command + '\\r\\n', 'utf-8'))\n\n\tif command[0:5] == 'scrub' or command[0:5] == 'flush':\n\t\tmessage = 'OK'\n\telse:\n\t\tmessage = 'END'\n\n\tresult = tn.read_until(bytes(message, 'utf-8'), timeout)\n\n\tresult = result.decode('utf-8')\n\ttn.write(bytes('quit\\r\\n', 'utf-8'))\n\ttn.close()\n\treturn result\n\n\t\ndef query(param, ip):\n\tprint(param)\n\n\tif 'server' not in param:\n\t\treturn 'select server'\t\n\n\n\tserver = param['server']\n\tinstance = param['instance']\n\tdummy, port_suffix = instance.split('_')\n\tport, suffix = port_suffix.split('.')\n\n\tid = ''\n\tpw = ''\n\tquery = ''\n\n\tif 'id' in param:\n\t\tif isinstance(param['id'], list):\n\t\t\tid = param['id'][0]\n\t\telse:\n\t\t\tid = param['id']\n\n\tif 'pw' in param:\n\t\tif isinstance(param['pw'], list):\n\t\t\tpw = param['pw'][0]\n\t\telse:\n\t\t\tpw = param['pw']\n\n\tif 'query' in param:\n\t\tquery = param['query']\n\n\n\tif param['query_type'] == 'query':\n\t\tsyslog('[hubblemon-redis-query:%s-%s(%s)] %s' % (server, id, ip, query))\n\t\tresult_str = ''\n\n\t\tresult_str += '[%s-%s]
%s
' % (server, port, common.core.return_as_string(do_redis_command(server, port, query)))\n\t\t\t\t\n\t\treturn result_str\n\n\telse: # exec\n\t\tconn = redis.StrictRedis(server, port)\n\t\t\n\t\tp = {'conn':conn, 'result':'None' }\n\n\t\tsyslog('[hubblemon-redis-eval:%s-%s(%s)] %s' % (server, id, ip, query))\n\t\texec(query)\n\n\t\treturn p['result']\n\t\t\n\n\n\n\n\n\t\n\t\n\n\t\n\n\n","sub_path":"redis_mon/redis_query.py","file_name":"redis_query.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"92338726","text":"\"\"\"! Set of views for features of file handling in the backend\"\"\"\n\n## Imports for file_upload/views.py - \n# Used restframework api for interaction with Angular Frontend,\n# Subprocess for Compilation of files,\n# shutil for recursively clearing directories\"\"\"\nfrom logging import StreamHandler\nfrom sys import flags\nfrom django.http.response import HttpResponse\nfrom django.shortcuts import render, redirect\nfrom django.conf import Settings, settings\nfrom django.contrib.auth.forms import UserCreationForm,AuthenticationForm\nfrom django.core.files.storage import FileSystemStorage\nfrom django.contrib.auth.decorators import login_required\nfrom rest_framework import serializers\nfrom shutil import move\nfrom django.middleware.csrf import CsrfViewMiddleware\nfrom django.contrib.auth import logout\nfrom .models import UserProfile as User\nfrom django.db import IntegrityError\nfrom django.contrib import auth\nimport subprocess\nfrom django.http import JsonResponse\nimport logging\nlogger=logging.getLogger(__name__)\nfrom rest_framework.decorators import api_view, parser_classes\nfrom rest_framework.parsers import FileUploadParser, JSONParser\nfrom django.core.files.base import ContentFile\nfrom rest_framework.decorators import api_view\nfrom django.core.files import File\nimport os\nimport json\nimport shutil\n\n@api_view(['GET'])\ndef logout_user(request):\n\n \"\"\"! View for logging the user out of the workspace\n @param request GET from Angular frontend to logout current user\n @return JSON response of logged out status\n @note The user should be logged in for this feature to work\"\"\"\n logout(request)\n return JsonResponse({\"status\": \"Logged out\"})\n\n\ndef path_to_dict(path, request):\n \"\"\"! Defining the path to file/folder recieved from frontend\n @param path string, file name\n @param request user credentials\n @return dictionary of filename with corresponding path in Media directory\n @note The make_map view function uses this function \"\"\"\n ## Keys of Dictionary d\n #@var name For storing the file name\n d = {'name': os.path.basename(path)}\n\n #check if it's a file or a folder, assign type to the key\n #@var path Assigned the path to media directory\n #@var children Key for Dictionary of children directories for a directory in request\n if os.path.isdir(path):\n d['type'] = \"folder\"\n d['path']=os.path.relpath(os.path.dirname(path), settings.MEDIA_ROOT+'personal_file/'+str(request.user.id))\n d['children'] = [path_to_dict(os.path.join(path,x), request) for x in os.listdir(path)]\n else:\n d['type'] = \"file\"\n d['path']=os.path.relpath(os.path.dirname(path), settings.MEDIA_ROOT+'personal_file/'+str(request.user.id))\n return d\n\n\n@api_view(['GET'])\ndef make_map(request):\n \"\"\"! Getting the path of the file requested from frontend for an authenticated user\n @param request user credentials for authentication\n @return JsonResponse of the path of file in media directory backend\"\"\"\n if not request.user.is_authenticated:\n return JsonResponse({'Status': 'not logged in'})\n if request.method=='GET':\n return JsonResponse(path_to_dict(os.readlink(request.user.symlink), request))\n\n\n@api_view(['POST'])\ndef upload_from_computer(request):\n \"\"\"! Backend View for uploading a file chosen from User's system and POSTed on frontend\n Try making a directory for the path received from frontend, and simply create the file if the directory already exists\n @param request.user.symlink symbolic link to User Media Directory\n @param request.POST['path'] Path to file in backend, type: string\n @param request.POST['file_name'] Name of the file to be saved in backend, type: string\n @param request.POST['content'] File Content, type: file\n\n @return JsonResponse depending on status of process\n\n @brief Based on Frontend request, if a file of same name and path already exists, it is overwritten with new content, else a new file is created\"\"\"\n try:\n os.makedirs(os.readlink(request.user.symlink)+request.POST['path']+'/')\n with open(os.readlink(request.user.symlink)+request.POST['path']+'/'+request.POST['file_name'], 'w+') as stored_file:\n stored_file.write(request.FILES['content'].read().decode('utf-8'))\n except:\n if os.path.isfile(os.readlink(request.user.symlink)+request.POST['path']+'/'+request.POST['file_name']):\n return JsonResponse({'status': 'File exists!'})\n with open(os.readlink(request.user.symlink)+request.POST['path']+'/'+request.POST['file_name'], 'w+') as stored_file:\n stored_file.write(request.FILES['content'].read().decode('utf-8'))\n return JsonResponse({'status': 'file uploaded'})\n\n@api_view(['POST'])\ndef emptyFileUpload(request):\n \"\"\"! Making Empty Files - view defined for enabling upload from textbox feature\n\n @param request.user.symlink symbolic link to User Media Directory\n @param request.POST['path'] Path to file in backend, type: string\n @param request.POST['file_name'] Name of the file to be saved in backend, type: string\n\n @return JSON response depending on status of process\n @brief If a file of fetched name and path already exists, overwrite its content as empty, else create an empty file\"\"\"\n data = json.loads(request.body)\n try:\n os.makedirs(os.readlink(request.user.symlink)+data.get('path')+'/')\n with open(os.readlink(request.user.symlink)+data.get('path')+'/'+data.get('file_name'), 'w+') as stored_file:\n stored_file.write('')\n except:\n if not os.path.isfile(os.readlink(request.user.symlink)+data.get('path')+'/'+data.get('file_name')):\n with open(os.readlink(request.user.symlink)+data.get('path')+'/'+data.get('file_name'), 'w+') as stored_file:\n stored_file.write('')\n else:\n return JsonResponse({'status': 'File exists!'})\n return JsonResponse({'status': 'Empty file uploaded'})\n\n\n@api_view(['POST'])\ndef makeFolder(request):\n \"\"\"!\n View for making empty directories\n\n @param request User Details from Post Requests\n\n @return JSON Response of status of request\n @note If full path already exists, nothing is created\"\"\"\n fullPath = request.body.decode('utf-8') \n try:\n os.makedirs(os.readlink(request.user.symlink)+fullPath+'/')\n return JsonResponse({\"status\":\"done\"})\n except:\n return JsonResponse({\"status\":\"already exists!\"})\n\n\n@api_view(['POST'])\ndef edit_from_textbox(request):\n \"\"\"!\n Feature To Update the File in backend by changing the content in the Frontend using the Code Editor\n \n @param request.user.symlink symbolic link to User Media Directory\n @param request.POST['path'] Path to file in backend, type: string\n @param request.POST['file_name'] Name of the file in backend, type: string\n @param request.POST['content'] Updated File Content, type: string\n\n @return JsonResponse of success status\"\"\"\n data = json.loads(request.body)\n with open(os.readlink(request.user.symlink)+data.get('path')+'/'+data.get('name'), 'w+') as stored_file:\n stored_file.write(data.get('content'))\n return JsonResponse({\"status\":\"Edit reflected in backend\"})\n\n\n@api_view(['POST'])\ndef delete(request):\n \"\"\"!\n Feature to Delete the Files or Folders by clicking on them in the frontend\n \n @param request.user.symlink symbolic link to User Media Directory\n @param request.POST['path'] Path to file in backend, type: string\n @param request.POST['old_name'] Name of the file to be deleted from backend, type: string\n\n @note Removes the directory recursively; all children directories also deleted\n\n @return Json Response of success status\"\"\"\n data = json.loads(request.body)\n name=data.get('old_name')\n path=data.get('path')\n a_path = os.readlink(request.user.symlink) + path + '/' + name\n if os.path.isdir(a_path):\n shutil.rmtree(a_path)\n else:\n os.remove(os.readlink(request.user.symlink) + path + '/' + name)\n return JsonResponse({\"status\":\"done\"}) \n\n\n@api_view(['POST'])\ndef rename(request):\n\n \"\"\"!\n Feature to Update the file name in the user code directory\n\n @param request.user.symlink symbolic link to User Media Directory\n @param request.POST['path'] Path to file in backend, type: string\n @param request.POST['old_name'] Old Name of the file to be renamed from backend, type: string\n @param request.POST['new_name'] Updated Name of the file, type: string\n \n @return JsonResponse of status of request\"\"\"\n data = json.loads(request.body)\n if os.path.isfile((request.user.symlink)+data.get('path')+'/'+data.get('new_name')):\n return JsonResponse({'status': 'file with same name exists'})\n os.rename(os.readlink(request.user.symlink)+data.get('path')+'/'+data.get('old_name'), os.readlink(request.user.symlink)+data.get('path')+'/'+data.get('new_name'))\n return JsonResponse({\"status\":\"done\"})\n\n@api_view(['GET'])\ndef view_function(request):\n \"\"\"!\n Feature to get the file's information as a JSON response for a file clicked on frontend\n\n @param request.user.symlink symbolic link to User Media Directory\n @param request.POST['path'] Path to file in backend, type: string\n @param request.POST['name'] Name of the file to be viewed, type: string\n\n @return JsonResponse of file content (string), file name, language, else only name for a folder\"\"\"\n if os.path.isfile(os.readlink(request.user.symlink)+request.GET.get('path')+'/'+request.GET.get('name')):\n with open(os.readlink(request.user.symlink)+request.GET['path']+'/'+request.GET['name']) as f:\n lines=[line for line in f]\n return JsonResponse({'lines':''.join(lines),'name': request.GET['name'], 'language': request.GET['name'].split('.')[-1]})\n else:\n return JsonResponse({'lines':'This is a folder!', 'name': request.GET['name'], 'language': ''})\n\n\n@api_view(['POST'])\ndef exec_from_textbox(request):\n \"\"\"!\n View Function for compiling the file displayed in frontend\n \n @param request.POST['path'] Path to file in backend, type: string\n @param request.POST['Filename'] Name of the file to be compiled from backend, type: string\n @param request Language, Name, Path of the file which is to be compiled\n\n @return JSONResponse of the compiled output, or else runtime error\n\n @note Only C++,python and Java are the executable languages in this update\"\"\"\n if(request.method=='POST'):\n data = json.loads(request.body)\n filename=data.get('Filename')\n path=data.get(\"path\")\n mode=0\n args=[]\n exe=\"\"\n exename=''\n input=data.get('Input')\n language=data.get('Language')\n if language == \"cpp\" or language == \"c\":\n mode=2\n args=[\"g++\", filename]\n exe=\"./a.out\"\n elif language == \"py\": \n mode=1\n args=['python3', filename]\n elif language == \"java\":\n mode=2\n args=['javac', filename]\n exe=['java', os.path.splitext(filename)[0]]\n if(mode==0):\n return JsonResponse({'out':\"invalid language\"})\n if(mode==1):\n result=subprocess.Popen(args, cwd= os.readlink(request.user.symlink)+path+'/',stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n ans = result.communicate(input=input.encode())[0].decode('utf-8').replace('/home/danish/Videos/CodeKADeT/CodeKADeT/CodeKADeT/media/personal_file/', '')\n return JsonResponse({'out': ans})\n if(mode==2):\n comp=subprocess.run(args, cwd= os.readlink(request.user.symlink)+path+'/', capture_output=True)\n if(comp.stderr):\n return JsonResponse({'status':'1', 'out':'compilation failed\\n'+comp.stderr.decode('utf-8').replace('/home/danish/Videos/CodeKADeT/CodeKADeT/CodeKADeT/media/personal_file/', '')})\n result=subprocess.Popen(exe, cwd= os.readlink(request.user.symlink)+path+'/', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n ans = result.communicate(input=input.encode())[0].decode('utf-8')\n return JsonResponse({\"out\": ans.replace('/home/danish/Videos/CodeKADeT/CodeKADeT/CodeKADeT/media/personal_file/', '')})\n\n","sub_path":"CodeKADeT/file_upload/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"606379859","text":"# https://stackoverflow.com/questions/51805292/regarding-calculating-the-summary-statistics-for-each-group-in-a-dataframe\n\nperiod2=pd.Interval(pd.Timestamp('1998-02-02'), pd.Timestamp('1998-05-02'), closed='both')\n\n\ndf['New']='period1'\n\ndf.loc[df.Time.apply(lambda x : x in period2),'New']='period2'\n\ndf.pivot_table(index='ID',columns='New',values='Price',aggfunc='mean')\n# Out[881]: \n# New period1 period2\n# ID \n# 1002 34.0 41.5\n# 2001 NaN 45.0\n# 2003 NaN 30.0","sub_path":"python/snippets/calculate-group.py","file_name":"calculate-group.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"382812404","text":"\"\"\"\n-*- coding: utf-8 -*-\n@Time : 2021-05-08 15:31\n@Author : nanfang\n\"\"\"\nimport os\nimport threading\nimport time\n\nfrom PyQt5.QtCore import QUrl\nfrom pyecharts.charts import Pie\nfrom pyecharts import options as opts\nfrom components.dialog_novel import *\nfrom PyQt5.QtWidgets import *\nfrom threading import Thread\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nimport requests\nfrom lxml import etree\nimport re\nfrom PyQt5.QtWebEngineWidgets import *\n\n\nclass Novel_Dialog(QtWidgets.QDialog, Ui_Dialog):\n def __init__(self):\n super(Novel_Dialog, self).__init__()\n self.setupUi(self)\n self.url = 'https://m.rmxsba.com/search.html'\n self.main_url = \"https://m.rmxsba.com\"\n self.headers = {\n 'Cookie': '__cfduid=dd50fb1ed80a7d95c26140bec3bf9b0d71620107395; Hm_lvt_ff5a36d21942c35af99271f0b1999352=1620107389; Hm_lpvt_ff5a36d21942c35af99271f0b1999352=1620110682',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3861.400 QQBrowser/10.7.4313.400'\n }\n self.page_list = []\n self.chapter_list = []\n self.model = ''\n self.Threads = [] # 线程队列\n self.btn_search.clicked.connect(self.select)\n self.box_select.currentTextChanged.connect(self.show_data)\n self.table.doubleClicked.connect(self.download_novel)\n self.table.setHorizontalHeaderLabels(['书名', '作者', '地址'])\n self.btn_analyse.clicked.connect(self.get_dict_urls)\n # 小说数据分析部分\n self.ranking_url = \"https://m.rmxsba.com/top.html\"\n self.web_title = \"热门小说吧\"\n self.save_data_path = ''\n self.box_data={}\n self.threadLock=threading.Lock()\n #网页插件初始化\n self.browser = QWebEngineView()\n self.table.setSelectionBehavior(QAbstractItemView.SelectRows)\n self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)\n # 获取所有的小说名\n def download_TXT(self, searchkey):\n data = {\n 'searchkey': searchkey,\n }\n\n response = requests.post(self.url, data=data, headers=self.headers)\n # 使用正则表达式获取总页数\n pagePattern = r\"value=\\\"(/search/\\d+/\\d+.html)\\\"\"\n\n pageStrs = re.findall(pagePattern, response.text)\n for i in range(len(pageStrs)):\n pageStrs[i] = self.main_url + pageStrs[i] # 得到总的小说页数\n self.edit_log.append(\"已爬取所有页数\")\n\n novel_list = [] # 获取全部小说地址并存到这里面\n for i in range(len(pageStrs)):\n response = requests.post(pageStrs[i], data=data, headers=self.headers, timeout=5)\n # 使用xpath\n html = etree.HTML(response.text)\n book_urls = html.xpath('//p[@class=\"bookname\"]/a/@href')\n book_names = html.xpath('//p[@class=\"bookname\"]/a/text()')\n author_names = html.xpath('//p[@class=\"data\"]//a[@class=\"layui-btn layui-btn-xs layui-bg-cyan\"]/text()')\n contents = html.xpath('//p[@class=\"intro\"]/text()')\n # 得到最小的长度,防止出错\n min_length = len(book_urls)\n if min_length > len(book_names):\n min_length = len(book_names)\n elif min_length > len(author_names):\n min_length = len(author_names)\n elif min_length > len(contents):\n min_length = len(contents)\n for j in range(min_length):\n l = []\n ##### tableweight 循环添加数据\n row_cnt = self.table.rowCount() # 返回当前行数(尾部)\n self.table.insertRow(row_cnt) # 尾部插入一行新行表格\n novel_item = QTableWidgetItem(book_names[j]) # 书名\n self.table.setItem(row_cnt, 0, novel_item)\n author_item = QTableWidgetItem(author_names[j]) # 作者名\n self.table.setItem(row_cnt, 1, author_item)\n address_item = QTableWidgetItem(self.main_url + book_urls[j]) # 地址\n self.table.setItem(row_cnt, 2, address_item)\n ######\n l.append(self.main_url + book_urls[j])\n l.append(\"小说名:\" + book_names[j])\n l.append(\"作者:\" + author_names[j])\n novel_list.append(l)\n time.sleep(0.3) # 每0.3秒爬一次\n # 输出日志到界面中\n self.edit_log.append(\"已爬取第\" + str(i + 1) + \"页小说,\" + \"本页一共\" + str(min_length) + \"本小说\")\n self.edit_log.append(\"共爬取了\" + str(len(novel_list)) + \"本小说\")\n\n def select(self):\n # # 获取输入行中的信息\n try:\n self.edit_log.append(self.edit_search.text())\n thread_1 = Thread(target=self.download_TXT, args=(self.edit_search.text(),))\n thread_1.start()\n except:\n self.edit_log.append(\"Error: 无法启动线程\")\n\n ## 获取一本小说所有页数\n def get_all_page(self, novelUrl, save_path):\n response = requests.get(novelUrl, headers=self.headers, timeout=2)\n html = etree.HTML(response.text)\n ## 获取所有的页数 及多少章节\n pages_url = html.xpath('//select/option/@value')\n page_chapter = html.xpath('//select/option/text()')\n page_min_len = min(len(pages_url), len(page_chapter))\n for i in range(page_min_len):\n l = []\n l.append(self.main_url + pages_url[i])\n l.append(page_chapter[i])\n self.page_list.append(l)\n\n # 爬取所有页的章节\n for page in self.page_list:\n self.edit_log.append(\"获取到\" + page[1] + \"的地址\")\n self.get_page_chapters(page[0], save_path)\n\n time.sleep(1)\n\n def get_page_chapters(self, page_url, save_path):\n ## 获取本页所有章节的地址\n response = requests.get(page_url, headers=self.headers, timeout=2)\n html = etree.HTML(response.text)\n chapter_url = html.xpath('//ul[@class=\"read\"]/li/a/@href')\n chapter_name = html.xpath('//ul[@class=\"read\"]/li/a/text()')\n min_len = min(len(chapter_name), len(chapter_url))\n chapter_list = []\n for i in range(min_len):\n l = []\n l.append(self.main_url + chapter_url[i])\n l.append(chapter_name[i])\n chapter_list.append(l)\n for chapter in chapter_list:\n time.sleep(0.5)\n self.download_chapter_text(chapter[0], save_path)\n\n ## 获取本章节的小说内容,并下载\n def download_chapter_text(self, chapter_url, save_path):\n response = requests.get(chapter_url, headers=self.headers, timeout=2)\n html = etree.HTML(response.text)\n title = html.xpath('//h1[@class=\"headline\"]/text()')[0]\n content = html.xpath('//div[@class=\"content\"]/p/text()')\n with open(save_path, 'a', encoding='utf-8')as f:\n f.write(title + '\\n')\n for line in content:\n f.write(line + '\\n')\n f.write('\\n')\n self.edit_log.append('已下载 ' + title)\n\n def download_novel(self, index):\n row = index.row()\n ##双击获取地址\n novel_name = self.table.item(row, 0).text()\n novel_author = self.table.item(row, 1).text()\n novel_url = self.table.item(row, 2).text()\n ## 选择存储文件夹\n save_path = QFileDialog.getExistingDirectory(self, \"请选择存储路径\", \"C:\")\n if save_path == '' or save_path == \"C:/\":\n return\n save_path = save_path + '/' + novel_name + '.txt'\n self.edit_log.append(\"下载地址为:\" + save_path)\n self.edit_log.append(\"开始下载:\" + novel_name)\n self.edit_log.append(\"作者:\" + novel_author)\n # 开启新线程\n thread = Thread(target=self.get_all_page, args=(novel_url, save_path))\n # 将此线程设置为守护线程\n thread.daemon = 1\n thread.start()\n # 将线程加入线程队列\n self.Threads.append(thread)\n\n ## 统计数据\n def show_data(self):\n path=self.box_select.currentData()\n # 判断文件夹是否存在,不存在则创建一个新的\n self.browser.load(QUrl(path))\n self.browser.show()\n # 得到所有的排行榜信息\n def get_dict_urls(self) -> dict:\n self.save_data_path = QFileDialog.getExistingDirectory(self, \"请选择存储路径\", \"C:\")\n if self.save_data_path == '' or self.save_data_path == \"C:/\":\n return\n response = requests.get(self.ranking_url, headers=self.headers, timeout=2)\n html = etree.HTML(response.text)\n hrefs = html.xpath('//ul[@class=\"top\"]/li/a/@href')\n hrefs_msg = html.xpath('//ul[@class=\"top\"]/li/a/text()')\n rank_urls_dic = dict()\n for i in range(len(hrefs_msg)):\n if i < 4:\n rank_urls_dic[\"点击榜_\" + hrefs_msg[i]] = self.main_url + hrefs[i]\n elif i == 4 or i == 5 or i == 6 or i == 11:\n continue\n elif i == 7:\n rank_urls_dic[\"推荐榜_\" + hrefs_msg[i]] = self.main_url + hrefs[i]\n else:\n rank_urls_dic[hrefs_msg[i]] = self.main_url + hrefs[i]\n for k, url in rank_urls_dic.items():\n thread_1 = Thread(target=self.begin_analyse, args=(k, url))\n thread_1.start()\n return rank_urls_dic\n\n def begin_analyse(self, k, url):\n sort_list = self.get_url_data(url)\n dic = self.info_nums(sort_list)\n self.date_analyse_html(k, dic)\n\n # 示例画图\n def date_analyse_html(self, html_title: str, dic: dict):\n key_list = []\n num_list = []\n for k, v in dic.items():\n key_list.append(k)\n num_list.append(v)\n pie = (Pie()\n .add('', [list(z) for z in zip(key_list, num_list)],\n radius=[\"0%\", \"75%\"],\n )\n .set_global_opts(title_opts=opts.TitleOpts(title=self.web_title, subtitle=html_title),\n legend_opts=opts.LegendOpts(\n orient=\"vertical\", # 竖向显示\n pos_left=\"85%\", # 距离左边85%\n type_=\"scroll\" # 滚动翻页图例\n )\n )\n .set_series_opts(label_opts=opts.LabelOpts(formatter=\"{b}: {d}%\"))\n )\n path = self.save_data_path + '/' + html_title + \".html\"\n self.box_select.addItem(html_title,path)\n # self.box_data[html_title]=path\n pie.render(path)\n time.sleep(1.5)\n self.edit_log.append(html_title + \".HTML 分析结果下载完成\")\n # print(self.box_data)\n # # 加载外部的web界面\n\n # 根据排行榜地址,得到确定排行榜前10页内容\n def get_url_data(self, url: str) -> list:\n sort_list = []\n for i in range(1, 11):\n self.edit_log.append(\"开始分析\" + url + \"中的数据\")\n response = requests.get(url, headers=self.headers, timeout=2)\n html = etree.HTML(response.text)\n sort_list.extend(html.xpath(\n '//ul[@class=\"list\"]/li//p[@class=\"data\"]/span[@class=\"layui-btn layui-btn-xs layui-btn-radius\"]/text()'))\n url = url.replace(\"_\" + str(i), \"_\" + str(i + 1)) # 修改地址\n time.sleep(1.5)\n return sort_list\n\n # 统计词频\n def info_nums(self, sort_list: list) -> dict:\n dic = dict()\n for msg in sort_list:\n dic[msg] = dic.get(msg, 0) + 1\n return dic\n","sub_path":"ui_dialog/novel.py","file_name":"novel.py","file_ext":"py","file_size_in_byte":11809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"494889666","text":"from faker import Faker\nfrom xpinyin import Pinyin\n\nfaker = Faker(locale=\"zh_CN\")\np = Pinyin()\n\nfor i in range(100):\n gen_cn_name = faker.name_male()\n phone = faker.phone_number()\n yp_name = p.get_pinyin(gen_cn_name)\n yp_name = yp_name.replace(\"-\", \"\")\n print(f\"{gen_cn_name} {yp_name} {phone}\")\n\n","sub_path":"ops11/tests/bulk_c.py","file_name":"bulk_c.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"627940471","text":"from django.urls import path\n\nfrom dining import views\n\nurlpatterns = [\n path('test/', views.test),\n path('receipt//', views.receipt),\n path('cancel//', views.cancel),\n path('history//', views.status),\n path('program//', views.status)\n]\n","sub_path":"dining/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"531412484","text":"# from Input import parse_query\n# from dictionary import give_dictionary\n\n# strr = 'I cat:sport don8* \"Information Retrieval\"give\"Data Structure\" ->\"<- source: times shit'\n\n# x = '\"بازیابی اطلاعات\" امیرکبیر !درس'\n# words, exacts, nots, source, cat = parse_query(x)\n# dic = give_dictionary()\n\n\ndef words_query(word, dic): # returns doc_ids that include 'word'. e.g. [1, 2]\n res = []\n if word in dic:\n docs = dic[word]\n for d in docs:\n res.append(d[0]) \n return res\n\n# print(words_query('قرار', dic))\n# print(words_query('مبارزات', dic))\n# print(words_query('گذشته', dic))\n# print(words_query('مقام', dic))\n# print(words_query('بازیابی', dic))\n\n\ndef postings(word, doc_id, dic): # returns position of 'word' in document=doc_id. e.g. [1, 21, 59, 121]\n docs = dic[word]\n for d in docs:\n if d[0]==doc_id:\n return d[1]\n\n# print(postings('گذشته', 0, dic))\n# print(postings('گذشته', 1, dic))\n\n\ndef exact_query(exact, dic): # returns doc_ids that include the exact phrase. \n words = exact.split(' ')\n docs = []\n for word in words:\n doc = words_query(word, dic)\n if(len(doc)==0): ## one word in phrase doesn't exit at all\n # print('NOOOOOO')\n return []\n docs.append(doc)\n # print(docs)\n\n intersect = set(docs[0]).intersection(*docs) ## intersection of all postings lists\n # print(intersect) ## result is all docs that contain all words in \"phrase\"\n if len(intersect)==0:\n return []\n\n result = []\n for doc_id in intersect:\n positions = []\n for word in words:\n positions.append(postings(word, doc_id, dic))\n \n # print(positions)\n cnt = len(words) - 1\n for index in positions[0]:\n flag = True\n for i in range(cnt):\n if (index + i + 1) not in positions[i+1]:\n flag = False\n break\n if flag:\n result.append(doc_id)\n \n\n # print(result)\n return result\n\n\n# exacts = ['مقام گذشته']\n# exacts = ['حجت الاسلام']\n# exacts = ['احمد واعظی']\n# exacts = ['رئیس هیأت امنای دفتر تبلیغات اسلامی']\n# exacts = ['محمد گیلانی']\n# exact_query(exacts[0], dic)\n\ndef result(words, exacts, nots, dic):\n\n if words[0]!='':\n w_docs = words_query(words[0], dic)\n for word in words:\n tmp = words_query(word, dic)\n w_docs = list(set(w_docs) | set(tmp))\n if len(w_docs)==0:\n break\n \n # if len(w_docs)==0:\n # return []\n else:\n w_docs = \"empty\"\n \n # print(dic)\n # print('AAAAAAAAAA')\n # print(w_docs)\n # print('AAAAAAAAAA')\n\n if len(exacts)!=0:\n e_docs = exact_query(exacts[0], dic)\n for exact in exacts:\n tmp = exact_query(exact, dic)\n e_docs = list(set(e_docs) | set(tmp))\n if len(e_docs)==0:\n break\n \n if len(e_docs)==0:\n return []\n else:\n e_docs = \"empty\"\n\n # print('BBBBBBBBB')\n # print(e_docs)\n \n \n n_docs = []\n if len(nots)!=0:\n n_docs = exact_query(nots[0], dic)\n # print(n_docs)\n for nott in nots:\n tmp = exact_query(nott, dic)\n # print(tmp)\n\n n_docs = list(set(n_docs) | set(tmp))\n \n # print('CCCCCCCCC')\n # print(n_docs)\n \n if e_docs==\"empty\" and w_docs==\"empty\":\n res = list(dic.keys()) ## all docs\n res = list(set(res) - set(n_docs))\n return res\n \n if e_docs==\"empty\":\n res = w_docs\n res = list(set(res) - set(n_docs))\n return res\n \n if w_docs==\"empty\":\n res = e_docs\n res = list(set(res) - set(n_docs))\n return res\n\n res = list(set(e_docs) & set(w_docs))\n res = list(set(res) - set(n_docs))\n\n return res\n\n\n# x = '\"بازیابی اطلاعات\" امیرکبیر !درس'\n\n\n# from Input import parse_query\n# from dictionary import give_dictionary\n# x = 'گذشته'\n# words, exacts, nots, source, cat = parse_query(x)\n# # print(words)\n# # print(exacts)\n# # print(nots)\n# dic = give_dictionary()\n# # print(dic)\n# res = result(words, exacts, nots, dic)\n# print(res)","sub_path":"Phase1/search/code/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":4336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"384568519","text":"from ecff.finitefield.finitefield import FiniteField\nfrom ecff.elliptic import EllipticCurve, Point\n\n\"\"\"\nThis will be the first prng using an elliptic curve\n\nnote that damn near all of this code assumes we're\nusing a prime-order finite field, not prime-power!\nThus, our finite field MUST essentially be Z mod p.\nIf not, all sorts of things will break here.\n\nFirst EC candidate:\n F = FiniteField(104729,1)\n C = EllipticCurve(a=F(1),b=F(1))\n P = Point(C,F(32770),F(85186))\n\nthe subgroup generated by P has 211 elements (prime)\n\n\nthis subgroup takes forever to generate...\nP = Point(C,F(4),F(8945))\nthis subgroup has 35026 elements!\nhowever, the largest prime factor of 35026 is 211...\n\"\"\"\n\n\"\"\"\ncrap! we may need larger primes. 331337\nis cool, let's try it out...\n\nF = FiniteField(331337,1)\nC = EllipticCurve(a=F(1),b=F(1))\nP = Point(C, F(0), F(1))\nP has order 331621 = 53 * 6257\n\n\"\"\"\n\ndef is_quadratic_residue(n,p):\n \"\"\"\n n is some integer, p is an odd prime.\n\n This is obviously only applicable \n within a prime-order finite field,\n which thankfully is all we're using\n\n compute Legendre symbol\n \"\"\"\n n = n%p\n if n == 0:\n return True #0**2 = 0, but BOOORING\n L = (n**((p-1)//2)) % p # integer division is fine if p is an odd prime\n if L == 1:\n return True\n else:\n return False\n\ndef tonelli_shanks(n,p):\n \"\"\"\n n is some integer less than p\n p is an odd prime\n\n return integer x in Z mod p s.t. x**2 = n (mod p)\n\n INPUTS WHICH BREAK THIS:\n (2,41)\n (2,104729)\n\n TODO: return a tuple containing both solutions\n \"\"\"\n if n == 0:\n return 0\n\n if is_quadratic_residue(n,p):\n #compute p-1 = Q * 2**S\n Q = p-1\n S = 0\n while Q % 2 == 0:\n #factor out powers of 2\n Q = Q//2\n S += 1\n #print(\"Q: \",Q,\" S: \",S,\"(p-1,Q*2**S): \",(p-1,Q*2**S))\n if S == 1:\n #p = 3 (mod 4) thus p+1 % 4 = 0\n R = n**((p+1)//4) % p\n return (R,-R % p) # -R is also a solution\n\n z = 0 #scope\n for z in range(2,p):\n #lame algorithm to find a non-residue\n if not is_quadratic_residue(z,p):\n break\n #print(\"z: \",z)\n c = z**Q % p\n R = n**((Q+1)//2) % p #wiki says congruence\n t = n**Q % p #wiki says congruence\n M = S\n i = 1 #note: i=0 was screwing this up... how?\n while t % p != 1:\n #compute\n for i in range(1,M):\n #find i by repeated squaring (TODO: optimize me)\n #print(\"--i: \",i)\n if t**(2**i) % p == 1:\n #print(\"break: \",t)\n break\n b = c**(2**(M-i-1)) % p\n R = R*b % p\n t = t*(b**2) % p\n c = b**2 % p\n M = i\n #DEBUG\n #print(\"i: \",i)\n\n return (R, p-R) #2nd solution is p-R\n\n else:\n #not even a quadratic residue...\n raise Exception(\"Not a quadratic residue\")\n\ndef find_point(C,x):\n \"\"\"\n C: elliptic curve\n x: x coordinate (FiniteField object)\n\n attempts to find a point on the\n curve C with x coordinate x. Only\n one of the points is returned, as\n the other can be trivially found \n with negation\n \"\"\"\n F = C.a.field\n try:\n # y^2 = x^3 + ax + b\n val = x*x*x + C.a * x + C.b\n y = tonelli_shanks(val.n,F.p)[0]\n #print(\"point:\",x,y)\n return Point(C,F(x),F(y))\n except Exception:\n #print(\"no possible point\")\n return None #not a residue => no point on curve\n\ndef make_subgroup(P):\n \"\"\"\n return the group generated by P.\n This is of course a subgroup of\n the group on P's elliptic curve\n\n this might be REALLY slow. consider\n if find_order is more appropriate\n \"\"\"\n T=P\n I=0*P\n subgroup = [I]\n while T != I:\n subgroup.append(T)\n T+=P\n return subgroup\n\ndef find_order(P):\n \"\"\"\n Given a point P on an elliptic curve,\n find its order.\n\n This lets us find the size of the subgroup\n generated by P without keeping track of\n ALL the elements in the subgroup\n \"\"\"\n T = P\n I = 0*P\n i = 1\n while T != I:\n T+=P\n i+=1\n return i\n\n\nclass prng:\n def __init__(self,n=331337,seed=42):\n \"\"\"\n create a new prng using a finite field\n of order n. n must be prime, as we basically\n use the integers mod some prime (Z mod p).\n Jeremy Kun's code lets us make this actual\n arithmetic code quite nice. We do take a\n performance hit, but not a *ton*\n \"\"\"\n\n \"\"\"\n TERRIBLE CHOICE:\n self.P = Point(C,F(32770),F(85186))\n Q = 5*P\n \"\"\"\n\n \"\"\"\n seeds with not-incredibly-terrible initial\n cycles: 2819,\n\n some seeds lead to idntical cycles, but\n there are at least 3 distinct cycles!\n identical cycles:\n 4342,2819\n \"\"\"\n #don't need to keep field or curve beyond constructor\n F = FiniteField(n,1)\n C = EllipticCurve(a=F(1),b=F(1)) #choice of curve assumes default\n self.state = F(seed).n\n #this gives a 'cycle' of 71 elements...\n self.Q = Point(C,F(153116),F(171795)) # has order 6257\n self.P = Point(C,F(285710),F(143307))\n\n def get_num(self):\n \"\"\"\n produce a number, and update our\n internal state\n\n try to copy the EC_DRBG algorithm\n\n THIS IS SUPER BROKEN.\n \"\"\"\n r = (self.state * self.P).x.n\n self.state = (r * self.P).x.n\n t = (r * self.Q).x.n\n return t #define SO LONG AS we're in integers mod P\n\n def find_repeat(self):\n \"\"\"\n get random numbers until we receive a \n number which we've already seen.\n\n In this algorithm, we essentially are \n generating output based on a coset of \n the subgroup generated by P**2, so once\n we repeat an output, we've started to\n loop over again.\n \"\"\"\n vals = {}\n output = self.get_num()\n while output not in vals:\n vals[output] = self.get_num()\n output = vals[output]\n return len(vals)\n\n def test_output(self):\n \"\"\"\n Given the default finite field\n of order 104729, we almost always\n observe a cycle of 26182 elements.\n\n get this many random numbers, and see\n which are most frequent\n \"\"\"\n vals = {}\n #found experimentally for default order\n for i in range(211):\n key = self.get_num()\n if key in vals:\n vals[key]+=1\n else:\n vals[key]=1\n print(\"uniques: \",len(vals))\n sorted_vals = sorted(vals.items(), key=lambda x:x[1], reverse=True)\n top_ten = sorted_vals[:10]\n print(\"top 10: \",top_ten)\n bottom_ten = sorted_vals[-10:]\n bottom_ten.reverse()\n print(\"bottom 10: \",bottom_ten)\n \"\"\"\n gives WAAAY too much output if we use integers mod p\n without a mask\n\n for i in range(len(sorted_vals)-1):\n if sorted_vals[i+1] < sorted_vals[i]:\n print(\"break: \",i,\", \",sorted_vals[i:i+2])\n \"\"\"\n\n","sub_path":"prng_3.py","file_name":"prng_3.py","file_ext":"py","file_size_in_byte":7279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"292975191","text":"import os\nimport os.path\nimport csv\nimport json\n\nCSV_DIR=\"data/db/tables/\"\n\nLISTS_CSV=os.path.join(CSV_DIR, \"lists.csv\")\nSUBLISTS_CSV=os.path.join(CSV_DIR, \"sublists.csv\")\nLIST_TITLE_CSV=os.path.join(CSV_DIR, \"listtitl.csv\")\nPAGES_CSV=os.path.join(CSV_DIR, \"pages.csv\")\n\nPERSONS_CSV=os.path.join(CSV_DIR, \"persons.csv\")\nSPRAVKI_CSV=os.path.join(CSV_DIR, \"spravki.csv\")\n\n# Can be used to debug scripts\nMAX_ROWS=int(os.environ.get('MAX_ROWS', 0))\n\nHUGO_DATA_DIR=\"hugo/data\"\nHUGO_CONTENT_DIR=\"hugo/content\"\n\ndef csv_reader(file_name):\n with open(file_name) as csvfile:\n reader = csv.DictReader(csvfile)\n count = 0\n for row in reader:\n count +=1\n if MAX_ROWS and count > MAX_ROWS:\n return\n yield row\n\ndef file_writer(file_name, file_content):\n with open(file_name, 'w') as writer:\n writer.write(file_content)\n\ndef json_writer(file_name, data):\n file_writer(file_name, json.dumps(data, ensure_ascii=False))\n\ndef x2many(get_id, records):\n d = dict()\n for r in records:\n i = get_id(r)\n d.setdefault(i, [])\n d[i].append(r)\n return d\n\ndef list2name(record):\n return 'list%s' % record['listid']\n\n","sub_path":"data2hugo/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"335424012","text":"# -*- coding: utf-8 -*-\nimport sys\nimport os\nimport datetime\nimport re\n# import sphinx_readable_theme\nimport sphinxjp.themes.basicstrap\n\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.split(__file__)[0])))\nsys.path.insert(\n 0,\n os.path.abspath(\n os.path.join(\n os.path.split(__file__)[0],\n \"..\",\n \"..\",\n \"..\",\n \"..\",\n \"pyquickhelper\",\n \"src\")))\n\nfrom pyquickhelper.helpgen.default_conf import set_sphinx_variables\nset_sphinx_variables(__file__, \"jupytalk\", \"Xavier Dupré\", 2016,\n # \"readable\", [sphinx_readable_theme.get_html_theme_path()],\n \"basicstrap\", None,\n locals(), extlinks=dict(\n issue=('https://github.com/sdpython/jupytalk/issues/%s', 'issue')),\n github_user=\"sdpython\", github_repo=\"jupytalk\", book=True)\n\nblog_root = \"http://www.xavierdupre.fr/app/jupytalk/helpsphinx/\"\nblog_background = False\nhtml_context = {\n 'css_files': ['_static/my-styles.css'],\n}\n\n# https://github.com/peterhudec/foundation-sphinx-theme\n# http://docs.guzzlephp.org/en/latest/\n# http://sphinx-better-theme.readthedocs.io/en/latest/\n","sub_path":"_doc/sphinxdoc/source/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"54738300","text":"#Ezekiel D Towner\n#Longest Path Algorithm\n#programming for data analysis\n\nadjacencyList = {}\n\nheadNode = 0\n\ninputFile = open(\"output.csv\",'r') \nfor line in inputFile :\n\ttokenizedLine = line.strip().split(',')\n\ttmpList = []\n\tkey = -1\n\tfor index,element in enumerate(tokenizedLine) :\n\t\tif index == 0 :\n\t\t\tkey = int(element)\n\t\telse :\n\t\t\ttmpList.append(int(element))\n\tadjacencyList[key] = tmpList\n\ninputFile.close()\n\n\n#print(adjacencyList)\n\n\nvisited = []\nvisited.append(headNode)\n\nallPaths = []\n\ndef longestPath(allPaths): \n pathCount = 0\n while allPaths != 0:\n for index in allPaths:\n if len(index) > pathCount:\n count = len(index)\n Path = index\n print(\"Longest Path: \" + str(Path))\n print (\"\")\n return\n\ndef recursiveDFS(node,path) :\n # This is a leaf when all the elements have been visited\n visited.append(node)\n n_list = adjacencyList[node]\n for newNode in n_list :\n if newNode not in visited :\n # Piggy back the path that was passed before us, and adding the child node\n newPath = path.copy()\n newPath.append(newNode)\n recursiveDFS(newNode,newPath) \n allPaths.append(path) \n# print(\" The path from 0 to \" + str(node) + \" is \" + str(linkCount) )\n# linkCount -= 1\n return\n\nfor n_node in adjacencyList[headNode] :\n if n_node in visited :\n continue\n newPath = [headNode]\n newPath.append(n_node)\n recursiveDFS(n_node,newPath)\n longestPath(allPaths)\n\n\nprint(allPaths)\n","sub_path":"Shortest Longest ET.py","file_name":"Shortest Longest ET.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"125338297","text":"from product import Product\n\n\nclass IdCard(Product):\n card_id = 0\n\n def __init__(self, owner):\n self.id = IdCard.card_id\n IdCard.card_id += 1\n self.owner = owner\n self.identify = '{}:{}'.format(self.id, self.owner)\n print('カードが作成されました。\"{}\"'.format(self.identify))\n\n def use(self):\n print('\"{}\"がカードを使用しました。'.format(self.identify))\n","sub_path":"04_factory/idcard.py","file_name":"idcard.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"440736319","text":"import urllib\nfrom app.zookeeper import init_zk, get_namespace_saiki\nfrom app.topics.controllers import validate_topic\nfrom app.settings.controllers import get_settings\n\n# Import flask dependencies\nfrom flask import Blueprint, flash, redirect, url_for, request\nfrom app.topic_mapping.forms import MappingForm\n\nfrom app.auth import check_and_render, only_check\n\nimport logging\n\nimport json\nfrom kazoo.client import NoNodeError\n\nnamespace_saiki = get_namespace_saiki()\n\nmod_topic_mapping = Blueprint('topic_mapping',\n __name__,\n url_prefix='/topic_mapping')\n\n\n@mod_topic_mapping.route('/', methods=('GET', 'POST'))\ndef topic_mapping():\n \"\"\"Docstring.\"\"\"\n mappings = get_mappings()\n # super ugly exception catching , needs to be rewritten\n try:\n if 'error' not in mappings[0]:\n return check_and_render('topic_mapping/index.html',\n display_settings=get_settings(),\n mappings=mappings)\n else:\n logging.warning('There was an error in getting ' +\n 'the topic mappings: ' +\n mappings[0]['error'])\n flash('There was an error in getting the topic mappings: ' +\n mappings[0]['error'],\n 'critical')\n return check_and_render('topic_mapping/index.html',\n display_settings=get_settings(),\n mappings=[])\n except IndexError:\n return check_and_render('topic_mapping/index.html',\n display_settings=get_settings(),\n mappings=[])\n\n\n@mod_topic_mapping.route('/create', methods=('GET', 'POST'))\ndef create_topic_mapping():\n \"\"\"Docstring.\"\"\"\n if only_check():\n mform = MappingForm()\n mform.validate_on_submit() # to get error messages to the browser\n if request.method == 'POST':\n if mform.validate() is False:\n flash('Please check that all the fields are valid.',\n 'critical')\n return check_and_render('topic_mapping/create.html',\n display_settings=get_settings(),\n form=mform)\n else:\n if validate_topic(mform.topic.data) is True:\n write_mapping(mform.content_type.data,\n mform.topic.data,\n mform.active.data)\n flash('Added Mapping: ' +\n mform.content_type.data +\n ' <> ' +\n mform.topic.data)\n return redirect(url_for('topic_mapping.topic_mapping'))\n else:\n flash('This topic does not exist!',\n 'critical')\n return check_and_render('topic_mapping/create.html',\n display_settings=get_settings(),\n form=mform)\n elif request.method == 'GET':\n return check_and_render('topic_mapping/create.html',\n display_settings=get_settings(),\n form=mform)\n else:\n return check_and_render('index.html', display_settings=get_settings())\n\n\n@mod_topic_mapping.route('/delete', methods=('GET', 'POST'))\ndef delete_topic_mapping():\n \"\"\"Docstring.\"\"\"\n if only_check():\n delete_mapping(request.args.get('ct'), request.args.get('topic'))\n flash('Deleted Mapping: ' +\n request.args.get('ct') +\n ' <> ' +\n request.args.get('topic'))\n return redirect(url_for('topic_mapping'))\n else:\n check_and_render('index.html', display_settings=get_settings())\n\n\ndef get_mappings():\n \"\"\"Docstring.\"\"\"\n zk = init_zk(namespace_saiki)\n return_list = []\n\n try:\n c_ids = zk.get_children('/content_types')\n except NoNodeError:\n logging.error(\"no node error: zk.get_children('\" +\n \"/content_types')\")\n return return_list\n for c_id in c_ids:\n c_id_dec = urllib.parse.unquote(c_id)\n t_dict = {\"c_name\": c_id_dec, \"c_name_enc\": c_id, \"topics\": []}\n try:\n topics = zk.get_children('/content_types/' +\n c_id +\n '/topics')\n except NoNodeError:\n logging.error(\"no node error: zk.get_children('\" +\n \"/content_types/\" + c_id + \"/topics')\")\n topics = []\n logging.warning(\"there is a broken topic mapping! CT: \" +\n c_id +\n \", Topic: \")\n t_dict[\"topics\"].append({\"name\": \"\",\n \"data\": \"false\",\n \"error\": \"true\"})\n if len(topics) == 0:\n logging.warning(\"there is a broken topic mapping! CT: \" +\n c_id +\n \", Topic: \")\n t_dict[\"topics\"].append({\"name\": \"\",\n \"data\": \"false\",\n \"error\": \"true\"})\n for topic in topics:\n data, stat = zk.get('/content_types/' +\n c_id +\n '/topics/' +\n topic)\n try:\n t_dict[\"topics\"].append({\"name\": topic,\n \"data\": json.loads(\n data.decode(\"utf-8\")\n )})\n except json.decoder.JSONDecodeError:\n logging.warning(\"there is a broken topic mapping! CT: \" +\n c_id +\n \", Topic: \" + topic)\n t_dict[\"topics\"].append({\"name\": topic,\n \"data\": \"false\",\n \"error\": \"true\"})\n return_list.append(t_dict)\n return return_list\n\n\ndef write_mapping(ct, topic, active):\n \"\"\"Docstring.\"\"\"\n zk = init_zk(namespace_saiki)\n if validate_topic(topic):\n ct_enc = urllib.parse.quote(ct, safe='')\n zk.create('/content_types/' + ct_enc + '/topics/' + topic,\n json.dumps({'active': active}).encode('utf-8'),\n makepath=True)\n logging.info(\"created topic mapping : CT: \" + ct_enc + \", Topic: \" +\n topic + \", data: \" + json.dumps({'active': active}))\n\n\ndef delete_mapping(ct, topic):\n \"\"\"Docstring.\"\"\"\n zk = init_zk(namespace_saiki)\n\n ct_enc = urllib.parse.quote(ct, safe='')\n delete_whole = False\n try:\n topics = zk.get_children('/content_types/' +\n ct_enc +\n '/topics')\n except NoNodeError:\n logging.warning(\"no node error: zk.get_children('\" +\n \"/content_types')\")\n topics = []\n if len(topics) == 0:\n delete_whole = True\n if delete_whole:\n logging.warning(\"deleting whole content-type because its broken: \" +\n ct_enc)\n zk.delete('/content_types/' + ct_enc,\n recursive=True)\n else:\n logging.info(\"deleting mapping: CT: \" + ct_enc + \", Topic: \" + topic)\n zk.delete('/content_types/' +\n ct_enc +\n '/topics/' +\n topic,\n recursive=True)\n try:\n topics = zk.get_children('/content_types/' +\n ct_enc +\n '/topics')\n except NoNodeError:\n logging.warning(\"no node error: zk.get_children('\" +\n \"/content_types')\")\n topics = []\n if len(topics) == 0:\n logging.warning(\"deleting whole content-type: \" +\n ct_enc)\n zk.delete('/content_types/' + ct_enc,\n recursive=True)\n","sub_path":"app/topic_mapping/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":8373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"212953638","text":"from django.conf.urls import include, url\n\nfrom .views import admin_create_course, admin_modify_course, admin_delete_course\nfrom .views import admin_create_course_info, admin_modify_course_info, admin_delete_course_info\nfrom .views import admin_create_course_available, admin_delete_course_available\nfrom .views import admin_obligatory_course_create, admin_obligatory_course_delete\n\n\nurlpatterns = [\n url(r'^create-course/', admin_create_course, name='admin_create_course'),\n url(r'^modify-course/', admin_modify_course, name='admin_modify_course'),\n url(r'^delete-course/', admin_delete_course, name='admin_delete_course'),\n\n url(r'^create-course-info/', admin_create_course_info, name='admin_create_course_info'),\n url(r'^modify-course-info/', admin_modify_course_info, name='admin_modify_course_info'),\n url(r'^delete-course-info/', admin_delete_course_info, name='admin_delete_course_info'),\n\n url(r'^create-course-available/', admin_create_course_available, name='admin_create_course_available'),\n url(r'^delete-course-available/', admin_delete_course_available, name='admin_delete_course_available'),\n\n url(r'^obligatory-create/', admin_obligatory_course_create, name='admin_obligatory_course_create'),\n url(r'^obligatory-delete/', admin_obligatory_course_delete, name='admin_obligatory_course_delete')\n]\n","sub_path":"course_selecting/api/admin_course_urls.py","file_name":"admin_course_urls.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"87724194","text":"from scrapy import Request, signals, Spider\nfrom scrapy.exceptions import DontCloseSpider\nfrom scrapy.xlib.pydispatch import dispatcher\nfrom scrapy import signals\nfrom billiard import Process\n\nfrom scrapy.crawler import CrawlerProcess\n\n\nclass SpiderIdleTest(Spider):\n\n custom_settings = {\n 'CONCURRENT_REQUESTS': 1,\n 'DOWNLOAD_DELAY': 2,\n 'LOG_LEVEL': 'DEBUG'\n }\n\n def __init__(self):\n dispatcher.connect(self.spider_idle, signals.spider_idle)\n self.idle_retries = 0\n\n def spider_idle(self, spider):\n self.idle_retries += 1\n if self.idle_retries < 3:\n self.crawler.engine.crawl(\n Request('https://www.google.com',\n self.parse,\n dont_filter=True),\n spider)\n raise DontCloseSpider(\"Stayin' alive\")\n\n def start_requests(self):\n yield Request('https://www.google.com', self.parse)\n\n def parse(self, response):\n print(response.css('title::text').extract_first())\n\n\nclass CrawlerScript(Process):\n\n def __init__(self, spider):\n Process.__init__(self)\n self.spider = spider\n\n def run(self):\n process = CrawlerProcess()\n process.crawl(SpiderIdleTest)\n process.start()\n\n\ndef crawl_async():\n spider = SpiderIdleTest()\n crawler = CrawlerScript(spider)\n crawler.start()\n\n\nfor i in range(0, 2):\n from time import sleep\n sleep(5)\n crawl_async()\n","sub_path":"test_with_billiard_process.py","file_name":"test_with_billiard_process.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"168738626","text":"# -*- coding: utf-8 -*-\n# coding = utf-8\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport re\nimport socket\n\nARK_DEBUG_CONF = 'ark_debug.conf'\nARK_LIBCURL_HOST = '0.0.0.0'\nARK_LIBCURL_PORT = '8888'\nARK_DEBUG_DIR = 'Letv/'\n\nARK_LOCAL_PATH = './' + ARK_DEBUG_CONF\n\nARK_DEBUG_PATH = '/sdcard/' + ARK_DEBUG_DIR + ARK_DEBUG_CONF\n\nADB_SHELL = 'adb push ' + ARK_LOCAL_PATH + ' ' + ARK_DEBUG_PATH\n\nIP_SHELL = \"ifconfig | grep -A 1 \\\"en\\\" | grep broadcast | cut -d \\\" \\\" -f 2 | tr \\\"\\\" \\\" \\\"\"\n\nreip = re.compile(r'(? - v0).sum() + (Y2 < - v0).sum()\n if ers < errors:\n errors = ers\n vopt = v0\n\n Y1_test = np.dot(V.T, X1_test.T)\n Y2_test = np.dot(V.T, X2_test.T)\n errors = (Y1 > - vopt).sum() + (Y2 < - vopt).sum()\n all_errors.append(errors)\n\n sopt = s_values[all_errors.index(min(all_errors))] # Find index of the minimum value in list of all errors\n\n plt.plot(s_values, all_errors)\n plt.title('errors(s)')\n plt.xlabel('s')\n plt.show()\n\n print('Optimal value for s = ', sopt)\n\n # Calculate parameters for optimal s\n V = np.dot(np.linalg.inv(sopt*S1 + (1-sopt)*S2), (M2 - M1))\n V = np.reshape(V, (n,1))\n Y1 = np.dot(V.T, X1.T)\n Y2 = np.dot(V.T, X2.T)\n\n for v0 in np.linspace(-max(Y1.max(), Y2.max()), -min(Y1.min(), Y2.min()), num = 50):\n ers = (Y1 > - v0).sum() + (Y2 < - v0).sum()\n if ers < errors:\n errors = ers\n vopt = v0\n v0 = vopt\n\n accuracy = (2*m - errors) / (2*m)\n\n return V, v0, accuracy\n","sub_path":"common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"376635112","text":"\n\nfrom xai.brain.wordbase.nouns._lubber import _LUBBER\n\n#calss header\nclass _LUBBERS(_LUBBER, ):\n\tdef __init__(self,): \n\t\t_LUBBER.__init__(self)\n\t\tself.name = \"LUBBERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"lubber\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_lubbers.py","file_name":"_lubbers.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"17488923","text":"# -*- coding: UTF-8 -*-\n# Filename : dic_merge\n# author by : yanbing\n\n\"\"\"\n将两个字典融合成一个\n\"\"\"\n\n# 两个字典\ndict1 = {'a': 10, 'b': 8}\ndict2 = {'d': 6, 'c': 4}\n\"\"\"\n方法一:运用updata方法,第二个参数合并第一个参数,注意的是update没有返回值\n\"\"\"\ndef Merge(dict1, dict2):\n return (dict1.update(dict2))\n\n# 返回 None\nprint(Merge(dict1, dict2))\n\n# dict2 合并了 dict1\nprint(dict1)\n\n\"\"\"\n方法二:使用 **,函数将参数以字典的形式导入\n\"\"\"\ndef Merge(dict2, dict1):\n res = {**dict1, **dict2}\n return res\n\n# 两个字典\ndict1 = {'a': 10, 'b': 8}\ndict2 = {'d': 6, 'c': 4}\ndict3 = Merge(dict1, dict2)\nprint(dict3)","sub_path":"dic_merge.py","file_name":"dic_merge.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"598086525","text":"import configparser\nimport os\n\nTEST_SERVER_HOST = 'alc01.aa-iot.com'\nBUILD_SERVER_HOST = 'alcpd01.aa-iot.com'\n# BUILD_SERVER_HOST = 'tencentclub.aa-iot.com'\n# TEST_SERVER_HOST = 'tencentclub.aa-iot.com'\n# BUILD_SERVER_HOST = 'meeting.smartcity-top.com'\n# TEST_SERVER_HOST = 'meeting.smartcity-top.com'\nLOCAL_SERVER_HOST = '127.0.0.1'\n\n# 运行环境设置\nENVIRONMENT = 'build' #生产环境\n# ENVIRONMENT = 'test' # 测试环境\n# ENVIRONMENT = 'local' #本地\n# ENVIRONMENT = 'local_test' #本地测试环境\n\n#路径获取\nSERVICE_NAME = 'contentUnionService'\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nPROJECT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n#\nLOG_DIR = os.path.join('/alog',SERVICE_NAME)\nLOG_TOPIC = 'contentUnionService'\nDATABASE_FILE = '/company_info/database.conf'\n\n# 多数据库获取\ndatabase_config = configparser.ConfigParser()\ndatabase_config.read(DATABASE_FILE, encoding='utf-8')\nDATABASES = []\nfor k, database_info in database_config.items():\n DATABASE = {}\n for key, value in database_info.items():\n DATABASE[key] = value\n else:\n DATABASES.append(DATABASE)\n\n#按照服务,工程生成日志目录\nif ENVIRONMENT == 'test' or ENVIRONMENT == 'build' or ENVIRONMENT == 'local_test':\n for DATABASE in DATABASES:\n company_name = DATABASE.get('company_name')\n if not os.path.exists(os.path.join(LOG_DIR,company_name,'debug')):\n os.makedirs(os.path.join(LOG_DIR,company_name,'debug'))\n print('日志目录:{}'.format(os.path.join(LOG_DIR,company_name,'debug')))\n if not os.path.exists(os.path.join(LOG_DIR,company_name,'info')):\n os.makedirs(os.path.join(LOG_DIR,company_name,'info'))\n print('日志目录:{}'.format(os.path.join(LOG_DIR, company_name, 'info')))\n if not os.path.exists(os.path.join(LOG_DIR,company_name,'warning')):\n os.makedirs(os.path.join(LOG_DIR,company_name,'warning'))\n print('日志目录:{}'.format(os.path.join(LOG_DIR, company_name, 'warning')))\n if not os.path.exists(os.path.join(LOG_DIR,company_name,'error')):\n os.makedirs(os.path.join(LOG_DIR,company_name,'error'))\n print('日志目录:{}'.format(os.path.join(LOG_DIR, company_name, 'error')))\n else:\n company_name = 'default'\n if not os.path.exists(os.path.join(LOG_DIR,company_name,'debug')):\n os.makedirs(os.path.join(LOG_DIR,company_name,'debug'))\n print('日志目录:{}'.format(os.path.join(LOG_DIR,company_name,'debug')))\n if not os.path.exists(os.path.join(LOG_DIR,company_name,'info')):\n os.makedirs(os.path.join(LOG_DIR,company_name,'info'))\n print('日志目录:{}'.format(os.path.join(LOG_DIR, company_name, 'info')))\n if not os.path.exists(os.path.join(LOG_DIR,company_name,'warning')):\n os.makedirs(os.path.join(LOG_DIR,company_name,'warning'))\n print('日志目录:{}'.format(os.path.join(LOG_DIR, company_name, 'warning')))\n if not os.path.exists(os.path.join(LOG_DIR,company_name,'error')):\n os.makedirs(os.path.join(LOG_DIR,company_name,'error'))\n print('日志目录:{}'.format(os.path.join(LOG_DIR, company_name, 'error')))\n\n\n#生产环境\nif ENVIRONMENT == 'build':\n DEBUG = False\n # log等级定义\n LOG_LEVEL = 'INFO'\n #直接访问本地数据库\n for DATABASE in DATABASES:\n DATABASE['host'] = LOCAL_SERVER_HOST\n #连接本地运行的mysql服务\n MY_SQL_SERVER_HOST = LOCAL_SERVER_HOST\n #连接本地运行的log服务\n LOG_SERVICE_HOST = LOCAL_SERVER_HOST\n #连接本地运行的MQTT broker\n MQTT_SERVICE_HOST = LOCAL_SERVER_HOST\n #MQTT qos等级为0,最多发送一次,不进行确认\n QOS = 2\n QOS_LOCAL = 0\n#todo:测试环境\nelif ENVIRONMENT == 'test':\n DEBUG = False\n # log等级定义\n LOG_LEVEL = 'INFO'\n # 测试环境,直接访问本地数据库\n for DATABASE in DATABASES:\n DATABASE['host'] = LOCAL_SERVER_HOST\n # 连接本地运行的mysql服务\n MY_SQL_SERVER_HOST = LOCAL_SERVER_HOST\n # 连接本地运行的log服务\n LOG_SERVICE_HOST = LOCAL_SERVER_HOST\n # 连接本地运行的MQTT broker\n MQTT_SERVICE_HOST = LOCAL_SERVER_HOST\n # MQTT qos等级为0,最多发送一次,不进行确认\n QOS = 2\n QOS_LOCAL = 0\n#todo:本地环境\nelif ENVIRONMENT == 'local':\n DEBUG = True\n # log等级定义\n LOG_LEVEL = 'DEBUG'\n # 本地环境,直接访问测试环境数据库\n for DATABASE in DATABASES:\n DATABASE['host'] = BUILD_SERVER_HOST\n # 连接测试服务器运行的mysql服务\n MY_SQL_SERVER_HOST = BUILD_SERVER_HOST\n # 连接测试服务器运行的log服务\n LOG_SERVICE_HOST = BUILD_SERVER_HOST\n # 连接测试服务器运行的MQTT broker\n MQTT_SERVICE_HOST = BUILD_SERVER_HOST\n # MQTT_SERVICE_HOST = '192.168.5.2'\n # MQTT qos等级为2,只有一次,通过四步握手后发送一次数据\n QOS = 2\n QOS_LOCAL = 2\nelif ENVIRONMENT == 'local_test':\n DEBUG = False\n # log等级定义\n LOG_LEVEL = 'INFO'\n # 测试环境,直接访问本地数据库\n for DATABASE in DATABASES:\n DATABASE['host'] = TEST_SERVER_HOST\n # 连接本地运行的mysql服务\n MY_SQL_SERVER_HOST = LOCAL_SERVER_HOST\n # 连接本地运行的log服务\n LOG_SERVICE_HOST = LOCAL_SERVER_HOST\n # 连接本地运行的MQTT broker\n MQTT_SERVICE_HOST = LOCAL_SERVER_HOST\n # MQTT qos等级为0,最多发送一次,不进行确认\n QOS = 2\n QOS_LOCAL = 0\nelse:\n raise IndexError('运行环境错误')\n\n#网关在线\nONLINE = 'on'\n#网关离线\nOFFLINE = 'off'\n#控制类型转换\nCOMMANDBAKC = {\n 0: 'button',\n 1: 'channel',\n 2: 'level',\n 3: 'command',\n 4: 'string',\n 5: 'macro',\n 6:'none',\n 7:'matrix',\n }\nTYPEBACK = {\n 'button':0,\n 'channel':1,\n 'level':2,\n 'command':3,\n 'string':4,\n 'macro':5,\n 'none':6,\n 'matrix':7,\n}\nEVENT_TYPE = {\n 0:'click',\n 1:'push',\n 2:'release',\n 3:'on',\n 4:'off',\n 5:'pulsh',\n}\nWEBSOCKETALLOWTYPE = ['ipad','back-end','applet','front-end']\nUSE_MACRO = False\n# MY_SQL_SERVER_HOST = LOCAL_SERVER_HOST\nprint('服务启动场景:({})'.format(ENVIRONMENT))\nprint('调试模式:({})'.format(DEBUG))\nprint('输出日志等级:({})'.format(LOG_LEVEL))\nprint('日志服务器地址:({})'.format(LOCAL_SERVER_HOST))\nprint('数据库服务器地址:({})'.format(MY_SQL_SERVER_HOST))\nprint('MQTT服务器地址:({})'.format(MQTT_SERVICE_HOST))\nprint('外网MQTT连接等级:({})'.format(QOS))\nprint('本地MQTT连接等级:({})'.format(QOS_LOCAL))\n\n","sub_path":"setting/setting.py","file_name":"setting.py","file_ext":"py","file_size_in_byte":6776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"87339616","text":"from mujoco_env import MujocoEnv\nfrom rllab.core.serializable import Serializable\nimport numpy as np\n\nfrom rllab.envs.base import Step\nfrom rllab.misc.overrides import overrides\nfrom rllab.misc import logger\n\n\nclass PegEnv(MujocoEnv, Serializable):\n\n FILE = 'pr2_arm3d_damp.xml'\n\n def __init__(self, *args, **kwargs):\n super(PegEnv, self).__init__(*args, **kwargs)\n Serializable.__init__(self, *args, **kwargs)\n self.PR2_GAINS = np.array([3.09, 1.08, 0.393, 0.674, 0.111, 0.152, 0.098])\n self.t = 0\n self.T = 100\n self.init_body_pos = self.model.body_pos.copy()\n\n def get_current_obs(self): \n return np.concatenate([\n self.model.data.qpos.flatten(),\n self.model.data.qvel.flatten(),\n self.model.data.site_xpos.flatten(),\n np.zeros_like(self.model.data.site_xpos.flatten()),\n ]).reshape(-1)\n\n def step(self, action):\n dt = 0.05\n self.t += 1\n eepts_before = self.model.data.site_xpos.flatten() \n self.forward_dynamics(action)\n eepts_after = self.model.data.site_xpos.flatten()\n eepts_vel = (eepts_after - eepts_before)/dt\n dim = eepts_vel.shape[0]\n reward = self.cost(action)\n done = False\n ob = self.get_current_obs()\n ob[-dim:] = eepts_vel\n return Step(ob, float(reward), done)\n\n def reset_mujoco(self):\n self.model.data.qpos = self.init_qpos = np.array([0.1, 0.1, -1.54, -1.7, 1.54, -0.2, 0])\n self.model.data.qvel = self.init_qvel\n self.model.data.qacc = self.init_qacc\n self.model.data.ctrl = self.init_ctrl\n if hasattr(self, 'init_body_pos'):\n tmp_body_pos = self.init_body_pos.copy()\n tmp_body_pos[1] += np.array([0.4*np.random.rand()-0.25, 0.4*np.random.rand()-0.25, 0.0])\n self.model.body_pos = tmp_body_pos\n self.t = 0\n\n def cost(self, action):\n reward = 0\n wu = 1e-3/self.PR2_GAINS\n cost_action = (wu*(action**2)).sum()\n reward -= cost_action\n \n target = np.array([0.0, 0.3, -0.5, 0.0, 0.3, -0.2])\n wp = np.array([2, 2, 1, 2, 2, 1])\n \n l1, l2 = 0.1, 10.0\n\n alpha = 1e-5\n wpm = 1\n wp = wp*wpm\n d = self.model.data.site_xpos.flatten() - target\n sqrtwp = np.sqrt(wp)\n dsclsq = d * sqrtwp\n dscl = d * wp\n l = 0.5 * np.sum(dsclsq ** 2) * l2 + \\\n 0.5 * np.log(alpha + np.sum(dscl ** 2)) * l1\n reward -= l\n\n l1, l2 = 1.0, 0.0\n\n if self.t == self.T:\n wpm = 10.0\n else:\n wpm = 0\n wp = wp*wpm\n sqrtwp = np.sqrt(wp)\n dsclsq = d * sqrtwp\n dscl = d * wp\n l = 0.5 * np.sum(dsclsq ** 2) * l2 + \\\n 0.5 * np.log(alpha + np.sum(dscl ** 2)) * l1\n reward -= l\n\n return reward\n\n def simple_cost(self, action):\n reward = 0\n wu = 5e-3/self.PR2_GAINS\n cost_action = (wu*(action**2)).sum()\n reward -= cost_action\n \n target = np.array([0.0, 0.3, -0.5, 0.0, 0.3, -0.2])\n wp = np.array([2, 2, 1, 2, 2, 1])\n \n l1, l2 = 1.0, 0.0001\n\n alpha = 1e-5\n wpm = 1\n wp = wp*wpm\n d = self.model.data.site_xpos.flatten() - target\n sqrtwp = np.sqrt(wp)\n dsclsq = d * sqrtwp\n dscl = d * wp\n l = 0.5 * np.sum(dsclsq ** 2) * l2 + \\\n 0.5 * np.sqrt(alpha + np.sum(dscl ** 2)) * l1\n reward -= l\n\n return reward\n","sub_path":"rllab/envs/mujoco/peg_env.py","file_name":"peg_env.py","file_ext":"py","file_size_in_byte":3555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"142592747","text":"# -*- coding: utf-8 -*-\n\"\"\"Utility functions for pyIEM package\n\nThis module contains utility functions used by various parts of the codebase.\n\n\"\"\"\nimport psycopg2\n\n\ndef get_properties():\n \"\"\"Fetch the properties set\"\"\"\n pgconn = psycopg2.connect(database='mesosite', host='iemdb')\n cursor = pgconn.cursor()\n cursor.execute(\"\"\"SELECT propname, propvalue from properties\"\"\")\n res = {}\n for row in cursor:\n res[row[0]] = row[1]\n return res\n\n\ndef drct2text(drct):\n \"\"\"Convert an degree value to text representation of direction.\n\n Args:\n drct (int or float): Value in degrees to convert to text\n\n Returns:\n str: String representation of the direction, could be `None`\n\n \"\"\"\n if drct is None:\n return None\n # Convert the value into a float\n drct = float(drct)\n if drct > 360:\n return None\n text = None\n if drct >= 350 or drct < 13:\n text = \"N\"\n elif drct >= 13 and drct < 35:\n text = \"NNE\"\n elif drct >= 35 and drct < 57:\n text = \"NE\"\n elif drct >= 57 and drct < 80:\n text = \"ENE\"\n elif drct >= 80 and drct < 102:\n text = \"E\"\n elif drct >= 102 and drct < 127:\n text = \"ESE\"\n elif drct >= 127 and drct < 143:\n text = \"SE\"\n elif drct >= 143 and drct < 166:\n text = \"SSE\"\n elif drct >= 166 and drct < 190:\n text = \"S\"\n elif drct >= 190 and drct < 215:\n text = \"SSW\"\n elif drct >= 215 and drct < 237:\n text = \"SW\"\n elif drct >= 237 and drct < 260:\n text = \"WSW\"\n elif drct >= 260 and drct < 281:\n text = \"W\"\n elif drct >= 281 and drct < 304:\n text = \"WNW\"\n elif drct >= 304 and drct < 324:\n text = \"NW\"\n elif drct >= 324 and drct < 350:\n text = \"NNW\"\n return text\n","sub_path":"pyiem/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"264363492","text":"from ...nsproblem import NSProblem\nfrom ...nssolver import NSSolver\n\n''' The tests snes, newton, qnewton, picard, aitken_converge_to_tol should take\n9.5s together '''\n\n\ndef test_snes_converge_to_tol():\n ''' test if snes solver reach tolerance within predetermined number of\n iterations (REGRESSION TEST) for Re = 1000 '''\n\n pb = NSProblem('cavity.yaml')\n assert pb.options['nonlinear']['method'] == 'snes', (\n 'test not configured correctly! expected SNES.')\n pb.init()\n snes_sol = NSSolver(pb)\n snes_sol.solve()\n\n assert len(snes_sol.residual) <= 11\n\n\ndef test_newton_converge_to_tol():\n ''' test if manual newton solver reach tolerance within predetermined\n number of iterations (REGRESSION TEST) for Re = 1000 '''\n\n pb = NSProblem('cavity.yaml')\n pb.options['nonlinear']['method'] = 'newton'\n pb.init()\n newton_sol = NSSolver(pb)\n newton_sol.solve()\n\n assert len(newton_sol.residual) <= 11\n\n\ndef test_qnewton_converge_to_tol():\n ''' test if quasi-newton solver reach tolerance within predetermined\n number of iterations (REGRESSION TEST) for Re = 1000 '''\n pb = NSProblem('cavity.yaml')\n pb.options['nonlinear']['method'] = 'qnewton'\n pb.init()\n qnewton_sol = NSSolver(pb)\n qnewton_sol.solve()\n\n assert len(qnewton_sol.residual) <= 11\n\n\ndef test_picard_converge_to_tol():\n ''' test if picard solver reach tolerance within predetermined\n number of iterations (REGRESSION TEST) for Re = 1000 '''\n pb = NSProblem('cavity.yaml')\n pb.options['nonlinear']['method'] = 'picard'\n pb.init()\n picard_sol = NSSolver(pb)\n picard_sol.solve()\n\n assert len(picard_sol.residual) <= 51\n\n\ndef test_aitken_converge_to_tol():\n ''' test if Picard + Aitken solves Re = 1000 case within 40 iterations '''\n pb = NSProblem('cavity.yaml')\n pb.options['nonlinear']['method'] = 'picard'\n pb.options['nonlinear']['use_aitken'] = True\n pb.init()\n picard_sol = NSSolver(pb)\n picard_sol.solve()\n\n assert len(picard_sol.residual) <= 42\n","sub_path":"source/solvers/ns_steady/tests/regression/test_ns_steady_cavity.py","file_name":"test_ns_steady_cavity.py","file_ext":"py","file_size_in_byte":2033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"92225132","text":"\"\"\"\n - Add this line to /etc/rc.local (before the exit 0):\n - /home/pi/ONBOOT.sh 2> /home/pi/ONBOOT.errors > /home/pi/ONBOOT.stdout &\n - Add the following ONBOOT.sh script to /home/pi and make it executable:\n \n#!/bin/bash\ncd /home/pi/megabugs\npython3 app_frame_viewer.py \n\"\"\"\n\nimport time\nimport sys\nimport os\n\nimport socket\n\nfrom rgbmatrix import RGBMatrix, RGBMatrixOptions\nfrom rgbmatrix import graphics\n\noptions = RGBMatrixOptions()\n \n# This chain is mapped as a 64*2 x 32 grid.\n \noptions.rows = 32 # 32 rows per display\noptions.cols = 64 # 64 rows per display (64x32)\noptions.chain_length = 2 # 2 displays per chain (128x32)\noptions.parallel = 1 # 3 (128x96)\n \nmatrix = RGBMatrix(options = options) \n\n\ndef draw_graphic(x,y,data,color,canvas):\n data = data.replace(' ','').replace('\\n','') \n pos = 0 \n for j in range(12):\n for i in range(12):\n if data[pos]=='*':\n canvas.SetPixel(x+i,y+j,100,255,255) \n pos+=1\n \ndef draw_frame(colors,pixels):\n canvas = matrix.CreateFrameCanvas() \n for y in range(32):\n for x in range(128):\n val = pixels[128*y+x]\n #print('##',val)\n pix = colors[val]\n canvas.SetPixel(x,y,pix[0],pix[1],pix[2])\n matrix.SwapOnVSync(canvas)\n\ndef main():\n ss = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n ss.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n ss.bind(('',1234))\n ss.listen(1)\n \n print('Listening on',ss)\n \n while True:\n cs,_ = ss.accept()\n print('Got a connection from',cs)\n #try: \n sz = cs.recv(1) \n sz = sz[0] + 1\n print('Loading',sz,'colors')\n colors = []\n for _ in range(sz):\n pix = [cs.recv(1)[0],cs.recv(1)[0],cs.recv(1)[0]]\n colors.append(pix)\n print(colors)\n pixels = []\n for _ in range(32):\n for _ in range(128):\n pixels.append(cs.recv(1)[0])\n #print(len(pixels))\n draw_frame(colors,pixels)\n cs.close()\n print('done')\n #except:\n # Eating exceptions on purpose\n # print('eating')\n \n\nmain()\n \ncolors = [[0,0,0],[100,100,100]]\npixels = [0]*128*32\n\nfor x in range(32):\n pixels[128*x+x] = 1\n \ndraw_frame(colors,pixels) \n \nwhile True:\n time.sleep(1)\n \n \nwhile True: \n \n offscreen_canvas = matrix.CreateFrameCanvas() \n draw_graphic(56,10,bug1,1,offscreen_canvas) \n matrix.SwapOnVSync(offscreen_canvas)\n time.sleep(0.25) \n \n offscreen_canvas = matrix.CreateFrameCanvas() \n draw_graphic(56,10,bug2,1,offscreen_canvas) \n matrix.SwapOnVSync(offscreen_canvas)\n time.sleep(0.25) \n \n","sub_path":"old/app_frame_viewer.py","file_name":"app_frame_viewer.py","file_ext":"py","file_size_in_byte":2821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"316488228","text":"# standart library\nfrom datetime import datetime, date, time\n\n# django library\nfrom django.urls import reverse\nfrom django.contrib import messages\nfrom django.views.generic import View\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import render, HttpResponseRedirect\n\n# my models\nfrom registration.models import Patient\nfrom account.models import Profile, ProfessionalGroup\nfrom medical_visit.models import Medical, Specialization, MedicalVisit\n\n# my forms\nfrom medical_visit.forms import DateVisitRegisterForm, MedicalAddForm\n\n# my functions\nfrom functions.myfunctions import visits_list, holidays, diacritical_remover\n\n\n# Create your views here.\n\n\n# adding new medical view\nclass MedicalAddView(View):\n\n def get(self, request):\n conrooms = Medical.objects.values_list('consulting_room', flat=True)\n if conrooms:\n conrooms = max(list(conrooms)) + 1\n else:\n conrooms = 1\n form = MedicalAddForm(initial={'consulting_room': conrooms})\n\n return render(request, 'medical_visit/medical_add.html', {'form': form})\n\n def post(self, request):\n kwargs, nickname, password, medical = None, None, None, None\n\n if len(request.POST) > 1:\n form = MedicalAddForm(data=request.POST)\n\n if form.is_valid():\n cd = form.cleaned_data\n specialization = cd['specialization']\n forename = cd['forename']\n surname = cd['surname']\n email = cd['email']\n consulting_room = cd['consulting_room']\n\n kwargs = {'email': email,\n 'surname': surname,\n 'forename': forename,\n 'specialization': specialization,\n 'consulting_room': consulting_room}\n\n new_medical = Medical.objects.create(**kwargs)\n\n if new_medical.id:\n # create credentials for new medicals\n strid = str(new_medical.id)\n medical = Medical.objects.get(id=new_medical.id)\n\n if new_medical.id > 0 and new_medical.id <= 9:\n strid = '0' + str(new_medical.id)\n\n nickname = ''.join([medical.forename[:2], medical.surname[:2], str(medical.specialization)[:2], strid]).lower()\n password = ''.join([str(medical.specialization), strid]).lower()\n nickname = diacritical_remover(nickname)\n password = diacritical_remover(password)\n\n if nickname and password:\n\n Medical.objects.filter(id=new_medical.id).update(nickname=nickname)\n user=User.objects.create_user(username=nickname,\n password=password,\n email=new_medical.email,\n first_name=new_medical.forename,\n last_name=new_medical.surname)\n group = ProfessionalGroup.objects.get(slug='medical-staff')\n Profile.objects.create(user=user, group=group)\n\n kwargs['medical'] = medical\n kwargs['nickname'] = nickname\n kwargs['password'] = password\n\n return render(request, 'medical_visit/medical_add.html', kwargs)\n\n else:\n\n conrooms = Medical.objects.values_list('consulting_room', flat=True)\n\n return render(request, 'medical_visit/medical_add.html', {'conrooms': max(list(conrooms))})\n\n\n# medical's register visit view\nclass MedicalView(View):\n\n def get(self, request, patient_id, spec):\n specialization = Specialization.objects.get(slug=spec)\n patient = Patient.objects.get(id=patient_id)\n medicals = Medical.objects.filter(specialization=specialization).order_by('surname')\n # li = Medical.objects.filter(email__contains='onet')\n # cs = Medical.objects.filter(consulting_room__gte=7)\n # cg = Medical.objects.filter(consulting_room__gte=2,consulting_room__lte=10)\n for medical in medicals:\n user = User.objects.get(username=medical.nickname)\n if user.is_active == False:\n medicals = medicals.exclude(pk=medical.id)\n visits = visits_list(patient=patient, date_of_visit__gte=date.today())\n\n if not medicals.exists():\n msg = r'No doctors in selected specialization ({})'\n messages.error(request, msg.format(spec))\n kwargs={'patient_id':patient_id}\n return HttpResponseRedirect(reverse('registrations:register_patient_detail', kwargs=kwargs))\n else:\n context = {'spec': spec,\n 'visits': visits,\n 'patient': patient,\n 'medicals': medicals,\n 'patient_id': patient_id}\n return render(request, 'medical_visit/medical_staff_list.html', context)\n\n\n def post(self, request, patient_id, spec):\n\n if len(request.POST) > 1:\n medical_id = request.POST['medical_id']\n kwargs = {'spec': spec, 'medical_id': medical_id, 'patient_id': patient_id}\n return HttpResponseRedirect(reverse('medical_visit:visit_date_register', kwargs=kwargs))\n\n else:\n msg = r'Please select doctor name'\n messages.error(request, msg)\n kwargs={'spec': spec, 'patient_id':patient_id}\n return HttpResponseRedirect(reverse('medical_visit:medical_staff_view', kwargs=kwargs))\n\n\n# booking data visit view\nclass VisitDateView(View):\n\n def get(self, request, patient_id, spec, medical_id):\n form = DateVisitRegisterForm()\n patient = Patient.objects.get(id=patient_id)\n medical = Medical.objects.get(id=medical_id)\n visits = visits_list(patient=patient, date_of_visit__gte=date.today())\n context = {'spec': spec,\n 'form': form,\n 'visits': visits,\n 'patient': patient,\n 'medical': medical,\n 'patient_id': patient_id,}\n return render(request, 'medical_visit/visit_date_register.html', context)\n\n def post(self, request, patient_id, spec, medical_id):\n kwargs={'spec': spec,\n 'patient_id': patient_id,\n 'medical_id': medical_id}\n\n if len(request.POST) > 1:\n form = DateVisitRegisterForm(data=request.POST)\n\n if form.is_valid():\n cd = form.cleaned_data\n date_of_visit = cd['date_of_visit']\n\n if date_of_visit >= date.today():\n if date_of_visit.weekday() < 5:\n if date_of_visit not in holidays(date_of_visit).values():\n date_of_visit = datetime.strftime(date_of_visit,'%Y-%m-%d')\n kwargs['date_of_visit'] = date_of_visit\n return HttpResponseRedirect(reverse('medical_visit:visit_hour_register', kwargs=kwargs))\n else:\n msg =r'Selected date is a holiday ({}). Please select correct date!'\n for key, value in holidays(date_of_visit).items():\n if value == date_of_visit:\n messages.error(request, msg.format(key))\n else:\n if date_of_visit.weekday() == 5:\n msg =r'Selected date is a Saturday... Please select correct date!'\n messages.error(request, msg)\n else:\n msg =r'Selected date is a Sunday... Please select correct date!'\n messages.error(request, msg)\n\n else:\n msg = r\"Please select today's or future date...\"\n messages.error(request, msg)\n\n return HttpResponseRedirect(reverse('medical_visit:visit_date_register', kwargs=kwargs))\n\n else:\n msg = r'Please select a valid visit date...'\n messages.error(request, msg)\n\n return HttpResponseRedirect(reverse('medical_visit:visit_date_register', kwargs=kwargs))\n\n# booking hour visit view\nclass VisitHourView(View):\n\n def get(self, request, patient_id, spec, medical_id, date_of_visit):\n # hours of visit\n hours, minutes = (8,12), (0,41,20)\n # permanent hours of medical visits list = phomv_list\n phomv_list = [str(time(x,y)) for x in range(*hours) for y in range(*minutes)]\n patient = Patient.objects.get(id=patient_id)\n doctor = Medical.objects.get(id=medical_id)\n doc_visit_list = visits_list(doctor=doctor, date_of_visit=date_of_visit)\n visit_hour_list = visits_list(patient_id=patient_id, date_of_visit=date_of_visit)\n visits = MedicalVisit.objects.filter(patient=patient, date_of_visit=date_of_visit)\n valid_hour_list = {}\n\n if visits:\n for visit in visits:\n if visit.doctor.id != int(medical_id) and str(visit.doctor.specialization) == spec:\n visit_hour_list.remove(visit.hour_of_visit)\n valid_hour_list = set(visit_hour_list + doc_visit_list)\n valid_hour_list = sorted(list(valid_hour_list))\n\n else:\n valid_hour_list = set(visit_hour_list + doc_visit_list)\n valid_hour_list = sorted(list(valid_hour_list))\n else:\n valid_hour_list = doc_visit_list\n\n visits = visits_list(patient=patient, date_of_visit__gte=date.today())\n date_of_visit = datetime.strptime(date_of_visit, '%Y-%m-%d')\n date_of_visit = date_of_visit.date()\n context = {'spec': spec,\n 'doctor': doctor,\n 'visits': visits,\n 'patient':patient,\n 'medical_id': medical_id,\n 'patient_id': patient_id,\n 'date_of_visit': date_of_visit,\n 'phomv_list': phomv_list,\n 'valid_hour_list': valid_hour_list,}\n return render(request, 'medical_visit/visit_hour_register.html', context)\n\n def post(self, request, patient_id, spec, medical_id, date_of_visit):\n date_of_visit = datetime.strptime(date_of_visit, '%Y-%m-%d')\n date_of_visit = date_of_visit.date()\n kwargs={'spec': spec,\n 'patient_id':patient_id,\n 'medical_id': medical_id,\n 'date_of_visit': date_of_visit}\n\n if len(request.POST) > 1:\n hour_of_visit = request.POST['hour_of_visit']\n patient = Patient.objects.get(id=patient_id)\n doctor = Medical.objects.get(id=medical_id)\n visits = MedicalVisit.objects.filter(patient=patient, date_of_visit=date_of_visit)\n doc_id = None\n data = {'doctor': doctor,\n 'patient': patient,\n 'date_of_visit': date_of_visit,\n 'hour_of_visit': hour_of_visit}\n\n if not visits.exists():\n MedicalVisit.objects.create(**data)\n msg = r'Successful create new medical visit for {} {}'\n messages.success(request, msg.format(patient.first_name, patient.last_name))\n else:\n for visit in visits:\n if str(visit.doctor.specialization) == spec:\n doc_id = visit.doctor.id\n\n if doc_id:\n values = {'doctor': doctor, 'hour_of_visit':hour_of_visit}\n MedicalVisit.objects.filter(doctor_id=doc_id,\n patient=patient,\n date_of_visit=date_of_visit).update(**values)\n msg = r'Successful update medical visit for {} {}'\n messages.success(request, msg.format(patient.first_name, patient.last_name))\n else:\n MedicalVisit.objects.create(**data)\n msg = r'Successful create new medical visit for {} {}'\n messages.success(request, msg.format(patient.first_name, patient.last_name))\n\n visits = visits_list(patient=patient, date_of_visit__gte=date.today())\n context = {'spec': spec,\n 'visits': visits,\n 'doctor': doctor,\n 'patient': patient,\n 'patient_id': patient_id,\n 'date_of_visit': date_of_visit,\n 'hour_of_visit': hour_of_visit,}\n return render(request, 'medical_visit/visit_hour_register.html', context)\n\n else:\n msg = r'Please select a visit hour...'\n messages.error(request, msg)\n return HttpResponseRedirect(reverse('medical_visit:visit_hour_register', kwargs=kwargs))\n\n\n# visit delete view\nclass VisitDeleteView(View):\n\n def get(self, request, patient_id):\n patient = Patient.objects.get(id=patient_id)\n visits = MedicalVisit.objects.filter(patient=patient, date_of_visit__gte=date.today())\n visits = visits.order_by('date_of_visit', 'hour_of_visit')\n context = {'visits': visits,\n 'patient': patient,\n 'patient_id': patient_id}\n return render(request, 'medical_visit/delete_visits.html',context)\n\n def post(self, request, patient_id):\n\n if len(request.POST) > 1:\n patient = Patient.objects.get(id=patient_id)\n visits = MedicalVisit.objects.filter(patient=patient, date_of_visit__gte=date.today())\n visits = visits.order_by('date_of_visit', 'hour_of_visit')\n visit_id = request.POST.getlist('visit')\n\n for id in visit_id:\n instance = MedicalVisit.objects.filter(id=id)\n instance.delete()\n\n msg = r'Successful delete medical visit(s) for patient {} {}'\n messages.success(request, msg.format(patient.first_name, patient.last_name))\n context = {'visits': visits,\n 'patient': patient,\n 'patient_id': patient_id}\n return render(request, 'medical_visit/delete_visits.html', context)\n\n else:\n msg = r'Please select a visit(s) to delete...'\n messages.error(request, msg)\n return HttpResponseRedirect(reverse('medical_visit:visit_delete', kwargs={'patient_id':patient_id}))\n","sub_path":"medical_visit/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"324315953","text":"class Solution:\n def removeDuplicates(self, s: str, k: int) -> str:\n \"\"\"\n Time Complexity: O(n)\n Space Complexity: O(n)\n \"\"\"\n stack = [(s[0], 1)]\n for ch in s[1:]:\n if stack and ch == stack[-1][0]:\n new_counter = stack[-1][1] + 1\n stack.append((ch, new_counter))\n\n if new_counter == k:\n for _ in range(k):\n stack.pop(-1)\n else:\n stack.append((ch, 1))\n\n return ''.join([itm[0] for itm in stack])","sub_path":"LeetCodeLearn/stack/1209.py","file_name":"1209.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"619186832","text":"import torch\nimport torch.nn as nn\nfrom ..modules.git_attention import Attention, NewAttention\nfrom ..modules.git_language_model import WordEmbedding, QuestionEmbedding\nfrom ..modules.git_classifier import SimpleClassifier\nfrom ..modules.git_fc import FCNet\n\nfrom question_parse.models.encoder import Encoder as QuesEncoder\nfrom roi_pooling.functions.roi_pooling import roi_pooling_2d\nimport utils.utils as utils\n\nclass BaseModel2(nn.Module):\n\tdef __init__(self, args, word2vec=None, rel_word2vec=None):\n\t\tsuper(BaseModel2, self).__init__()\n\t\tself.w_emb = WordEmbedding(args.ques_vocab_sz, args.ques_word_vec_dim)\n\t\tself.q_emb = QuestionEmbedding(args.ques_word_vec_dim, args.n_attn, 1, False)\n\t\tself.v_att = Attention(args.n_img_feats, self.q_emb.num_hid, args.n_attn, args.device)\n\t\tself.q_net = FCNet([args.n_attn, args.n_attn])\n\t\tself.v_net = FCNet([args.n_img_feats, args.n_attn])\n\t\tself.classifier = SimpleClassifier(args.n_attn, 2 * args.n_attn, args.n_ans, 0.5)\n\n\t\tself.roi_output_size = (5,5)\n\t\tself.avg_layer = nn.AvgPool2d(self.roi_output_size)\n\t\tself.device = args.device\n\t\tself.bidirectional = args.bidirectional\n\t\tself.ques_encoder = QuesEncoder(args.ques_vocab_sz, args.max_ques_len, args.ques_word_vec_dim, args.n_ques_emb, args.n_ques_layers, input_dropout_p=args.drop_prob, dropout_p=args.drop_prob, bidirectional=args.bidirectional, variable_lengths=args.variable_lengths, word2vec=word2vec)\n\n\t\n\tdef forward(self, img_feats, ques, objs, adj_mat, ques_lens, num_obj):\n\t\t# Obtain Object Features for the Image\n\t\trois = utils.batch_roiproposals(objs, self.device)# Change this later\n\t\tobj_feats = roi_pooling_2d(img_feats, rois, self.roi_output_size)#.detach()\n\t\tv = self.avg_layer(obj_feats).view(objs.size(0), objs.size(1), -1)\n\n\t\t# torch.set_printoptions(profile=\"full\")\n\t\t# print (num_obj)\n\t\t# torch.set_printoptions(profile=\"default\")\n\t\t# Obtain Question Embedding\n\t\tques_output, (ques_hidden, _) = self.ques_encoder(ques, ques_lens)\n\t\t\n\t\tif self.bidirectional:\n\t\t\tq_emb = torch.cat([ques_hidden[-2, :, :], ques_hidden[-1, :, :]], 1)\n\t\t\tq_emb = self.dropout_layer(self.ques_proj(ques_emb))\n\t\telse:\n\t\t\tq_emb = ques_hidden[-1, :, :]\n\n\n\t\tatt = self.v_att(v, q_emb, num_obj)\n\t\tv_emb = (att * v).sum(1) # [batch, v_dim]\n\n\t\tq_repr = self.q_net(q_emb)\n\t\tv_repr = self.v_net(v_emb)\n\t\tjoint_repr = q_repr * v_repr\n\t\tlogits = self.classifier(joint_repr)\n\t\treturn logits","sub_path":"src/graphQA/models/git_bua2.py","file_name":"git_bua2.py","file_ext":"py","file_size_in_byte":2380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"478924810","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\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.linux-i686/egg/mpd_webamp/findlyrics.py\n# Compiled at: 2007-06-11 06:34:27\nimport string, urllib, datetime\nfrom types import *\n\nclass ParseResults:\n \"\"\"Container for Parsed Results\"\"\"\n __module__ = __name__\n\n def __init__(self):\n self.table = ''\n self.lyrics = ''\n self.image = ''\n self.similar = ''\n\n\nclass SearchResults:\n \"\"\"Container for Search Results\"\"\"\n __module__ = __name__\n\n def __init__(self):\n self.count = 0\n self.links = []\n self.labels = []\n self.similarXML = ''\n self.albumXML = ''\n\n def parse(self, result=0):\n try:\n link = self.links[result]\n except:\n link = ''\n\n return parse(link, self.albumXML, self.similarXML)\n\n\nclass Song:\n __module__ = __name__\n\n def __init__(self, song=''):\n self.artist = ''\n self.album = ''\n self.title = ''\n self.SearchResults = SearchResults()\n if len(song) > 0:\n self.load(song)\n\n def load(self, song):\n artist = ''\n album = ''\n title = ''\n if type(song) is StringType:\n myfileFull = song.split('/')\n else:\n if song.has_key('album'):\n album = song['album']\n if song.has_key('artist'):\n artist = song['artist']\n if song.has_key('title'):\n title = song['title']\n if song.has_key('file'):\n myfileFull = song['file'].split('/')\n if title == '':\n myfile = myfileFull.pop()\n myfile = myfile[:-4]\n s = myfile.find('(')\n if s > 0:\n e = myfile.rfind(')')\n if e < 0:\n e = s\n myfile = myfile[:s - 1] + myfile[e + 1:]\n s = myfile.split('-')\n if len(s) > 0:\n title = s.pop().strip()\n artist = s[0].strip()\n if artist.isdigit():\n artist = ''\n if len(s) > 1:\n artist = s[1]\n else:\n title = myfile\n self.artist = artist\n self.album = album\n self.title = title\n\n def search(self):\n artist = _clean(self.artist)\n album = _clean(self.album)\n title = _clean(self.title)\n year = str(datetime.date.today().year)\n try:\n search_url = 'http://ws.audioscrobbler.com/1.0/artist/' + artist + '/similar.xml'\n conn = urllib.urlopen(search_url)\n data = conn.read()\n conn.close()\n self.SearchResults.similarXML = 'http://www.last.fm/music/' + artist + '' + data\n except:\n self.SearchResults.similarXML = ''\n\n try:\n search_url = 'http://musicbrainz.org/ws/1/release/?type=xml&artist=' + artist + '&title=' + album + '&limit=1'\n conn = urllib.urlopen(search_url)\n data = conn.read()\n conn.close()\n self.SearchResults.albumXML = data\n except:\n self.SearchResults.albumXML = ''\n\n if len(title) > 0:\n search = 'http://www.findlyrics.com/search/?as_q=1&artist=$artist&artist_match=0&song=$title&song_match=0&album=$album&album_match=1&from_year=1900&to_year=' + year + '&lyrics%5B1%5D=&lyrics_match%5B1%5D=1&lyrics%5B2%5D=&lyrics_match%5B2%5D=1&lyrics%5B3%5D=&lyrics_match%5B3%5D=1'\n search_temp = string.Template(search)\n search_url = search_temp.safe_substitute(artist=artist, title=title, album=album)\n conn = urllib.urlopen(search_url)\n data = conn.read()\n conn.close()\n if data.find('Your search did not match any lyrics.') > 0 and len(album) > 0:\n search_url = search_temp.safe_substitute(artist=artist, title=title, album='')\n conn = urllib.urlopen(search_url)\n data = conn.read()\n conn.close()\n if data.find('Your search did not match any lyrics.') > 0:\n search_url = string.replace(search_url, '_match=0', '_match=1')\n conn = urllib.urlopen(search_url)\n data = conn.read()\n conn.close()\n if data.find('Your search did not match any lyrics.') < 0:\n s = data.find('

Advanced Search Results

')\n e = data.find(' 0 and e > 0:\n s = data.find('', s) - 1\n if s > 0 and e > 0:\n links.append('http://www.findlyrics.com' + data[s:e] + '/?print')\n s = data.find('>', e) + 1\n e = data.find('', s)\n if s > 0 and e > 0:\n labels.append(data[s:e])\n data = data[e:]\n\n self.SearchResults.links = links\n self.SearchResults.labels = labels\n self.SearchResults.count = len(links)\n\n def quickSearch(self):\n self.search()\n return self.SearchResults.parse()\n\n\ndef _clean(item):\n s = item.find('(')\n if s > 0:\n e = item.rfind(')')\n if e < 0:\n e = s\n item = item[:s - 1] + item[e + 1:]\n item = string.replace(item, '&', 'and')\n item = string.replace(item, '!', '')\n item = string.replace(item, '?', '')\n item = string.replace(item, '.', '')\n item = string.replace(item, ':', '')\n item = string.replace(item, ';', '')\n item = string.replace(item, \"'\", '')\n item = string.replace(item, '\"', '')\n item = string.replace(item, ',', ' ')\n item = string.replace(item, ' - ', ' ')\n item = string.replace(item, '-', ' ')\n item = urllib.quote_plus(item)\n return item\n\n\ndef _parseSimilar(xml):\n s = 1\n e = 1\n h = ''\n s = xml.find('') + 11\n if s > 0:\n e = xml.find('')\n if e > 0:\n u = \"\"\n s = xml.find(' 0:\n e = xml.find('\"', s)\n if e > 0:\n h = u + xml[s:e] + '

'\n i = 0\n h += \"Top 10 Similar Artists\"\n while s > 0 and e > 0 and i < 10:\n s = xml.find('')\n name = ''\n url = ''\n match = ''\n if s > 0:\n e = xml.find('') + 9\n data = xml[s:e]\n xml = xml[e:]\n s = data.find('') + 6\n e = data.find('', s)\n if s > 0 and e > 0:\n name = data[s:e]\n s = data.find('') + 5\n e = data.find('', s)\n if s > 0 and e > 0:\n url = data[s:e]\n s = data.find('') + 7\n e = data.find('', s)\n if s > 0 and e > 0:\n if len(data[s:e]) > 0:\n match = '  (score: ' + data[s:e] + ')'\n if len(name) > 0 and len(url) > 0:\n h += \"
\" + name + '' + match + '
'\n i += 1\n\n return h\n\n\ndef _getValidImage(asin):\n base = 'http://images.amazon.com/images/P/' + asin\n f = urllib.urlopen(base + '.01._AA240_SCLZZZZZZZ_.jpg')\n s = len(f.read())\n if s > 1000:\n return base + '.01._AA240_SCLZZZZZZZ_.jpg'\n else:\n f = urllib.urlopen(base + '.01.MZZZZZZZ.jpg')\n s = len(f.read())\n if s > 1000:\n return base + '.01.MZZZZZZZ.jpg'\n else:\n return ''\n\n\ndef parse(lyrics='', album='', similar=''):\n \"\"\"parse(lyrics, album, similar)\n Parse print view lyrics page from findlyrics.com and return a ParseResults object.\n lyrics should be a findlyrics.com url, album should be musicbrainz release xml, similar\n should be audioscrobbler's similar.xml\"\"\"\n pr = ParseResults()\n if similar != '':\n pr.similar = _parseSimilar(similar)\n else:\n pr.similar = ''\n asin = ''\n if album != '':\n s = album.find('') + 6\n if s > 6:\n e = album.find('', s)\n if e > 0:\n asin = album[s:e]\n if len(asin) == 10:\n pr.image = _getValidImage(asin)\n if len(pr.image) == 0:\n s = similar.find('picture=') + 9\n if s > 8:\n e = similar.find('\"', s)\n if e > 0:\n pr.image = similar[s:e]\n if len(lyrics) > 0:\n conn = urllib.urlopen(lyrics)\n data = conn.read()\n conn.close\n s = data.find('') + 16\n e = data.find('', s) + 8\n data = data[s:e]\n i = 0\n while data.find(' 0:\n start_a = data.find('', start_a) + 4\n if data.find('Music Download', start_a, end_a) > 0:\n data = data[:start_a - 1] + data[end_a + 1:].lstrip('
')\n data.lstrip\n i = end_a\n\n pr.lyrics = string.replace(data, '
\"\n pr.lyrics = \"
\" + unicode(pr.lyrics, 'utf-8') + '
'\n pr.similar = \"
\" + unicode(pr.similar, 'utf-8') + '
'\n pr.table = \"

\" + pr.image + pr.similar\n pr.table += \"
 \" + pr.lyrics + '
'\n return pr","sub_path":"pycfiles/MPD_WebAMP-1.1-py2.4/findlyrics.py","file_name":"findlyrics.py","file_ext":"py","file_size_in_byte":10403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"335587516","text":"from toolz.itertoolz import groupby\nfrom collections import Counter\n\n\ndef sanitize(doc, sanitize_key):\n \"\"\"\n Salary data often has mixed types ie. $30000.00 and 33000.00 etc so\n I filter all of that and return a cleaned version of the incoming document with the same schema\n \"\"\"\n row = doc.copy()\n assert isinstance(row[sanitize_key], (unicode, str))\n\n temp = row[sanitize_key].split(\".\")[0] if \".\" in row[sanitize_key] else row[sanitize_key]\n\n row[sanitize_key] = int(\"\".join(char for char in temp if char.isalnum()))\n assert isinstance(row[sanitize_key], int)\n return row\n\n\ndef income_level(doc, salary_key):\n \"\"\"\n Creates qualitative descriptions of salaries based on income ranges. Requires sanitize annual_salary value\n \"\"\"\n\n row = doc.copy()\n key = \"income_level\"\n lower = \"Lower Income Range (Less than $33,000)\"\n middle = \"Middle Income Range ($33,000 and $66,000)\"\n upper = \"Upper Income Range (Greater than $66,000)\"\n\n if row[salary_key] < 33000:\n row[key] = lower\n \n elif 33000 <= row[salary_key] < 66000:\n row[key] = middle\n else:\n row[key] = upper\n\n return row\n\n\ndef return_sanitized(data):\n \"\"\"\n Make the API request and scrup all incoming data. Return unmodified aside from etl step. \n \"\"\"\n\n demographics = [income_level(sanitize(row, \"annual_salary\"), \"annual_salary\") for row in data] \n return demographics\n\n\ndef count_by_key(grouby_dict, key_to_count):\n \"\"\"\n Replace each element with a dict mapping a key to it's counts, per group in the value returned by toolz.itertoolz.groupby\n\n This is iterating through a fairly nested object that looks like:\n\n {\n key1: [\n {sub_key: val},\n ...\n ],\n key2: [\n {sub_key: val},\n ...\n ]\n }\n\n The tricky part of this is that dict can be initialized with a list of tuples, for each tuple the first element\n becomes the key, and the second the value. Counter.most_common returns a list of tuples with the first element\n being the element being counted, and the second it's count.\n\n Basically data jujitsu\n \"\"\"\n\n return {\n key: dict(\n Counter(\n elem[key_to_count]\n for elem in elems\n ).most_common()\n )\n for key, elems in grouby_dict.iteritems()\n }\n\n\ndef group_all(sanitized_data):\n \"\"\"\n Handle all the required data manipulations in memory. Should simply map to the required objects for the front end.\n \"\"\"\n grouped = groupby(\"current_dept_description\", sanitized_data)\n assert isinstance(grouped, dict)\n assert grouped\n\n double_grouped = [\n {\n \"name\": key,\n \"ethnicity\": count_by_key(groupby(\"income_level\", grouped[key]), \"ethnic_code_description\"),\n \"gender\": count_by_key(groupby(\"income_level\", grouped[key]), \"gender\")\n }\n for key in grouped\n ]\n\n assert all(isinstance(key, dict) for key in double_grouped)\n\n return double_grouped\n\n\ndef format_for_insert(sanitized_data):\n \"\"\"\n Convert the double nested dictionary structure into json-like values for each demographic\n\n The schema prior to this stage is\n\n {\"\": { : }}\n\n and the desired schema is going to be something like\n {\"\": [{: , : }]}\n \n \"\"\"\n \n def to_json_like(dictionary, key_name, value_name):\n \"\"\"\n convert a dictionary into json_like\n \"\"\"\n json_like = [{key_name: elem[0], value_name: [list(tupl) for tupl in elem[1].items()]} for elem in dictionary.items()]\n return json_like\n \n def valmap_if(dictionary, key_name, value_name):\n \"\"\"\n Apply to_json_like to values within the data that are lists. \n \"\"\"\n return {\n key: to_json_like(dictionary[key], key_name, value_name) if isinstance(dictionary[key], dict) else dictionary[key] \n for key in dictionary\n }\n\n formatted = [valmap_if(item, \"title\", \"data\") for item in sanitized_data]\n\n return formatted \n\n\n\ndef prepare_static_data(sanitized_data):\n \"\"\"\n Perform all aggregation operations in incoming data from open data portal\n \"\"\"\n return format_for_insert(group_all(sanitized_data))\n\n\ndef prepare_temporal_data(sanitized_data):\n \"\"\"\n Handle all data manipulations needed to create temporal data graphs\n \"\"\"\n return sanitized_data \n","sub_path":"ntp/data/etl.py","file_name":"etl.py","file_ext":"py","file_size_in_byte":4528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"144372958","text":"# encoding=utf-8\n\nfrom PyQTST import Moldata,Reaction\n\n# Reacant\nR=Moldata(\n U0K=0.0, # electronic energy+ZPE (internal energy at T=0K) kJ/mol\n GTK=0.0 # Gibbs free energy at reaction temperature kJ/mol\n )\n\nR2=Moldata(\n U0K=0.0, # electronic energy+ZPE (internal energy at T=0K) kJ/mol\n GTK=0.0 # Gibbs free energy at reaction temperature kJ/mol\n )\n\n# Transition State\nTS=Moldata(\n U0K=88.6132504999874,\n GTK=112.0\n )\n\n# Product\nP=Moldata(\n U0K=30.0,\n GTK=10.0\n )\n\n\n# Reaction A->TS->P\nreac=Reaction(\n Nmol=2, # number of reactant\n molR=R+R2,\n molTS=TS,\n molP=P,\n Temp=300.0, # reaction temperature K\n iFreq=-1000.0 # imaginary freq of TS cm-1\n )\n\n\n# Print Result\nreac.printf(QMethod=False) # use Gibbs free energy method moly\n\n# Print Result to text file (.tst)\nreac.print2file(output='2-1-g.tst',QMethod=False) # use Gibbs free energy method moly\n\n# Show Reaction Energy image\nreac.showimg()\n","sub_path":"example/2-1-g.py","file_name":"2-1-g.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"275461675","text":"from django.shortcuts import render, redirect\n\nfrom instructorRegistration.forms import RegisterInstructor\nfrom registrations.models import Account\nfrom .models import Instructor\n\nfrom django.urls import resolve\nfrom django.contrib.auth.models import User\nfrom django.conf import settings\n# Create your views here.\n\n\ndef instructor_view(request):\n\n\tcontext = {}\n\n\tuser = request.user\n\tif not user.is_authenticated:\n\t\treturn redirect('index')\n\n\tform = RegisterInstructor(request.POST or None, request.FILES or None)\n\tif form.is_valid():\n\t\tobj = form.save(commit=False)\n\t\tuser = Account.objects.filter(email=user.email).first()\n\t\t\n\t\tobj.user = user\n\t\t# reg=RegisterInsructor.objects.create(isinstructor=\"False\")\n\t\t# print(\"data is ---------------------------\",reg)\n\t\n\t\t# user.is_instructor=True\n\t\t# user.save()\n\n\t\tu=Account.objects.filter(email=request.user.email)\n\t\tu.is_instructor=True\n\t\tu.update()\n\n\t\t\n\n\n\t\tobj.save()\n\t\tform = RegisterInstructor()\n\n\tcontext['form'] = form\n\n\treturn render(request, \"instructor/instructor.html\",context)","sub_path":"Educaa/instructorRegistration/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"588286298","text":"from kafka import KafkaProducer\n\nproducer = KafkaProducer(bootstrap_servers=['localhost:9092'], compression_type='gzip')\nfuture = producer.send('my_topic' , key= b'key_3', value= b'value_3', partition= 0)\nfuture.get(timeout= 10)\n\n'''\n发送msgpack消息\nmsgpack为MessagePack的简称,是高效二进制序列化类库,比json高效\n\nproducer = KafkaProducer(value_serializer=msgpack.dumps)\nproducer.send('msgpack-topic', {'key': 'value'})\n'''\n","sub_path":"tests/kafka_tests/producer_gzip.py","file_name":"producer_gzip.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"432170204","text":"import time\nimport json\nimport yaml,random\nimport hashlib\nfrom merkle_tree import *\nfrom Crypto.PublicKey import RSA\n\n# import mysql.connector\n\n\nclass Block(object):\n def __init__(self, index='', nonce='', last_hash='',transactions=None, timestamp=None):\n self.index = index\n self.nonce = nonce\n self.last_hash = last_hash\n self.transactions = transactions\n if transactions == None:\n self.merkleRoot = '0'\n else:\n self.merkleRoot = MerkleTree(transactions).root.data\n\n self.timestamp = timestamp or time.time()\n\n def get_block_hash(self):\n block_string = \"{}{}{}{}{}\".format(self.index, self.nonce, self.last_hash, self.merkleRoot, self.timestamp)\n return hashlib.sha256(block_string.encode()).hexdigest()\n\n def parseBlock(self,blockstr):\n print(\"~~~~~~~\",blockstr)\n jsonBlock = yaml.safe_load(blockstr)\n print(jsonBlock)\n self.index = jsonBlock['index']\n self.nonce = jsonBlock['nonce']\n self.last_hash = jsonBlock['last_hash']\n self.timestamp = jsonBlock['timestamp']\n self.transactions = jsonBlock['transactions']\n self.merkleRoot = jsonBlock['merkleRoot']\n\n return self\n\n def getBlockDict(self):\n dict = {}\n dict['index'] = self.index\n dict['nonce'] = self.nonce\n dict['last_hash'] = self.last_hash\n dict['timestamp'] = self.timestamp\n dict['transactions'] = self.transactions\n dict['merkleRoot'] = self.merkleRoot\n\n return dict\n\n def getBlockStr(self):\n\n return yaml.dump(self.getBlockDict())\n\n\n\n\nclass MindNextBlock():\n def __init__(self,lastBlock):\n self.lastBlock = lastBlock\n self.nextBlock = Block()\n self.nextBlock.index = lastBlock.index + 1\n self.nextBlock.last_hash = lastBlock.get_block_hash()\n self.nextBlock.timestamp = str(time.time())\n self.nextBlock.nonce = random.randint(-1,999999) # or random number\n self.guess = 0\n self.guess_hash = 0\n\n def valid_proof(self, difficulty=5):\n \"\"\"Validates the Proof\n :param last_nonce: Previous Proof\n :param nonce: Current Proof\n :param last_hash: The hash of the Previous Block\n :return: True if correct, False if not.\n \"\"\"\n self.guess = '{}{}{}{}{}'.format(self.nextBlock.index,\n self.nextBlock.nonce,\n self.nextBlock.last_hash,\n self.nextBlock.merkleRoot,\n self.nextBlock.timestamp).encode()\n self.guess_hash = hashlib.sha256(self.guess).hexdigest()\n return self.guess_hash[:difficulty] == \"0\" * difficulty\n\n\n def mineOneStep(self):\n\n self.nextBlock.nonce += 1\n result = self.valid_proof()\n\n return result\n def addTransactions(self,transactions):\n\n self.nextBlock.transactions = []\n # deep copy\n for transaction in transactions:\n self.nextBlock.transactions.append(transaction)\n tree = MerkleTree(self.nextBlock.transactions)\n self.nextBlock.merkleRoot = tree.root.data\n\n# class GenesisBlock(Block)\n","sub_path":"blockchain.py","file_name":"blockchain.py","file_ext":"py","file_size_in_byte":3258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"428914711","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom models import *\n\nimport json\nimport logging\nimport urllib,urllib2\n\nclass LoginException(Exception):\n\tdef __init__(self,msg='Login Exception'):\n\t\tself.msg = str(msg)\n\tdef __str__(self):\n\t\treturn self.msg\n\nclass RequestException(Exception):\n\tdef __init__(self,error):\n\t\tself.error = error\n\t\tself.code = error['error']['error_code']\n\t\tself.message = error['error']['error_msg']\n\n\tdef __str__(self):\n\t\treturn 'Error ' + str(self.code) + ': ' + self.message\n\nclass VK(object):\n\tdef __init__(self,jid=None):\n\t\tif jid and jid.access_token:\n\t\t\tself.access_token = jid.access_token\n\t\telse:\n\t\t\traise LoginException('User not logged in')\n\n\tdef request(self,method,params):\n\t\tlogging.info('Request: ' + method + ' : ' + str(params))\n\t\tparams.update({'access_token':self.access_token})\n\t\treply = urllib2.urlopen(url='https://api.vk.com/method/'+method, data=urllib.urlencode(params))\n\t\tanswer = reply.read()\n\t\tlogging.info('Answer: ' + answer)\n\t\tresult = json.loads(answer)\n\t\tif 'response' in result:\n\t\t\treturn result['response']\n\t\traise RequestException(result)\n\n\tdef get_group(self,feed_id):\n\t\treturn self.request('groups.getById',{'gid':feed_id})[0]\n\n\tdef get_user(self,feed_id):\n\t\treturn self.request('users.get',{'uids':feed_id})[0]\n\n\tdef get_info(self,feed):\n\t\t#logging.info('get_info Id: ' + str(Id))\n\t\tif feed.feed_type == 'group':\n\t\t\tr = self.request('groups.getById',{'gid':feed.feed_id,\n\t\t\t\t'fields':'start_date,end_date,gid,name,link,is_closed,is_admin,type,photo,photo_medium,photo_big,screen_name'})[0]\n\t\t\tfeed.feed_title = r['name']\n\t\t\tfeed.feed_name = r['screen_name']\n\t\telse:\n\t\t\tr = self.request('users.get',{'uids':feed.feed_id, \n\t\t\t\t'fields':'uid,first_name,last_name,nickname,screen_name'})[0]\n\t\t\tfeed.feed_title = r['first_name'] + ((' *' + r['nickname'] + '* ') \\\n\t\t\t\tif ('nickname' in r and len(r['nickname'])>0) else ' ') + r['last_name']\n\t\t\tfeed.feed_name = r['screen_name']\n\t\tfeed.put()\n\t\treturn {'title':feed.feed_title,'name':feed.feed_name}\n\n\tdef get_title(self,feed_id):\n\t\tf_type = 'group' if int(feed_id) < 0 else 'user'\n\t\tf_id = str(abs(int(feed_id)))\n\t\tf,created = Feed.get_or_create(feed_type=f_type,feed_id=f_id)\n\t\tif created or not f.feed_title:\n\t\t\tself.get_info(f)\n\t\treturn f.feed_title\n\n\tdef get_name(self,feed_id):\n\t\tf_type = 'group' if int(feed_id) < 0 else 'user'\n\t\tf_id = str(abs(int(feed_id)))\n\t\tf,created = Feed.get_or_create(feed_type=f_type,feed_id=f_id)\n\t\tif created or not f.feed_name:\n\t\t\tself.get_info(f)\n\t\treturn f.feed_name\n\n\tdef get_last_message(self,feed):\n\t\tr = self.request('wall.get',{'owner_id':feed.minus_id(), 'count':'1'})\n\t\tif r[0]>0:\n\t\t\treturn r[1]['id']\n\t\telse:\n\t\t\treturn 0\n\n\tdef render_message(self,m):\n\t\tresult = ''\n\t\ttitle = '@' + self.get_name(m['to_id'])\n\t\t#if not m['from_id']==m['to_id']:\n\t\ttitle += ': ' + self.get_title(m['from_id'])\n\t\tresult += title + '\\n'\n\t\tif 'copy_text' in m:\n\t\t\tresult += m['copy_text'] + '\\n\\n'\n\t\tif 'copy_owner_id' in m:\n\t\t\ttitle = self.get_title(m['copy_owner_id'])\n\t\t\tresult += u'\\u267a' + title + '\\n'\n\t\tif 'attachments' in m:\n\t\t\tfor a in m['attachments']:\n\t\t\t\tif a['type'] in ('photo','posted_photo','graffiti'):\n\t\t\t\t\tresult += 'Pic: ' + a[a['type']]['src_big'] + '\\n'\n\t\t\t\tif a['type'] == 'link':\n\t\t\t\t\tresult += 'Link: ' + a[a['type']]['title'] + ' ' + a[a['type']]['url'] + '\\n'\n\t\t\t\tif a['type'] == 'video':\n\t\t\t\t\tdur = str(int(a[a['type']]['duration'])/60) + ':' + str(int(a[a['type']]['duration'])%60)\n\t\t\t\t\tresult += 'Video: ' + a[a['type']]['title'] + ' (' + dur + ') ' + \\\n\t\t\t\t\t\t'http://vk.com/video'+ str(a[a['type']]['owner_id']) + \\\n\t\t\t\t\t\t'_' + str(a[a['type']]['vid']) + '\\n'\n\t\t\t\tif a['type'] == 'audio':\n\t\t\t\t\tdur = str(int(a[a['type']]['duration'])/60) + ':' + str(int(a[a['type']]['duration'])%60)\n\t\t\t\t\tresult += 'Audio: ' + a[a['type']]['performer'] + ' - ' + a[a['type']]['title'] + \\\n\t\t\t\t\t\t' (' + dur + ') ' + 'http://vk.com/audio?id=' + str(a[a['type']]['owner_id']) + \\\n\t\t\t\t\t\t'&audio_id=' + str(a[a['type']]['aid']) + '\\n'\n\t\t\t\tif a['type'] == 'note':\n\t\t\t\t\tresult += 'Note: ' + a[a['type']]['title'] + ' Not implemented yet\\n'\n\t\t\t\tif a['type'] == 'poll':\n\t\t\t\t\tresult += 'Pool: ' + a[a['type']]['question'] + ' Not implemented yet\\n'\n\t\t\t\tif a['type'] == 'page':\n\t\t\t\t\tresult += 'Page: ' + a[a['type']]['title'] + ' Not implemented yet\\n'\n\t\t\t\tif a['type'] == 'app':\n\t\t\t\t\tresult += 'App: ' + a[a['type']]['app_name'] + ' Not implemented yet\\n'\t\n\t\t\t\tif a['type'] == 'doc':\n\t\t\t\t\tresult += 'Doc: ' + a[a['type']]['title'] + a[a['type']]['ext'] + ' Not implemented yet\\n'\t\n\n\t\tresult += m['text'] + '\\n'\n\t\tresult += '#'+ str(m['to_id'])+ '_' + str(m['id']) + \\\n\t\t\t' http://vk.com/wall' + str(m['to_id']) + '_' + str(m['id'])\n\t\treturn result\n\n\tdef render_comment(self,m,post_id):\n\t\tresult = '@' + self.get_title(m['uid']) + '\\n'\n\t\tresult += m['text'] + '\\n'\n\t\tresult += '#'+ str(post_id) + '/' + str(m['cid'])\n\t\treturn result\n\n\tdef get_message(self,feed_id,post_id):\n\t\tr = self.request('wall.getById',{'posts':str(feed_id)+'_'+str(post_id)})\n\t\treturn self.render_message(r[0])\n\n\tdef get_comments(self,feed_id,post_id):\n\t\tr = self.request('wall.getComments',{'owner_id':str(feed_id),'post_id':str(post_id),'preview_length':0,'count':100})\n\t\tresult = []\n\t\tif len(r)>1:\n\t\t\tfor m in r[1:]:\n\t\t\t\tresult.append({'id':m['cid'],\n\t\t\t\t\t\t\t 'date':m['date'],\n\t\t\t\t\t\t\t 'text':self.render_comment(m,str(feed_id)+'_'+str(post_id))})\n\t\t\t\t#logging.info('COMMENT: '+result[-1]['text'])\n\t\treturn result\n\n\n\tdef post_message(self,feed_id,text):\n\t\tr = self.request('wall.post',{'owner_id':str(feed_id),'message':text})\n\t\treturn 'Posted: #' + str(feed_id) + '_' + str(r['post_id']) + \\\n\t\t\t' http://vk.com/wall' + str(feed_id) + '_' + str(r['post_id'])\n\n\tdef post_comment(self,feed_id,post_id,text,comment_id=None):\n\t\tparams = {'owner_id':str(feed_id),'post_id':post_id,'text':text}\n\t\tif comment_id:\n\t\t\tparams['reply_to_cid'] = comment_id\n\t\tr = self.request('wall.addComment', params)\n\t\treturn 'Posted: #' + str(feed_id) + '_' + str(post_id)+ '/' + str(r['cid']) + \\\n\t\t\t' http://vk.com/wall' + str(feed_id) + '_' + str(post_id) + '?reply=' + str(r['cid'])\n\n\tdef get_messages(self,feed_id,last=0,count=10):\n\t\tr = self.request('wall.get',{'owner_id':feed_id, 'count':count})\n\t\tresult = []\n\t\tif len(r)>1:\n\t\t\tfor m in r[1:]:\n\t\t\t\tif m['id']>last:\n\t\t\t\t\tresult.append({'id':m['id'],\n\t\t\t\t\t\t\t\t 'date':m['date'],\n\t\t\t\t\t\t\t\t 'text':self.render_message(m)})\n\t\treturn result\n","sub_path":"vk.py","file_name":"vk.py","file_ext":"py","file_size_in_byte":6386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"4202378","text":"\"\"\"\n1348. Tweet Counts Per Frequency\n\nImplement the class TweetCounts that supports two methods:\n\n1. recordTweet(string tweetName, int time)\n\nStores the tweetName at the recorded time (in seconds).\n2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)\n\nReturns the total number of occurrences for the given tweetName per minute, hour, or day (depending on freq) starting from the startTime (in seconds) and ending at the endTime (in seconds).\nfreq is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName.\nThe first time interval always starts from the startTime, so the time intervals are [startTime, startTime + delta*1>,\n[startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)> for some non-negative number i and delta (which depends on freq).\n\n\nExample:\n\nInput\n[\"TweetCounts\",\"recordTweet\",\"recordTweet\",\"recordTweet\",\"getTweetCountsPerFrequency\",\"getTweetCountsPerFrequency\",\"recordTweet\",\"getTweetCountsPerFrequency\"]\n[[],[\"tweet3\",0],[\"tweet3\",60],[\"tweet3\",10],[\"minute\",\"tweet3\",0,59],[\"minute\",\"tweet3\",0,60],[\"tweet3\",120],[\"hour\",\"tweet3\",0,210]]\n\nOutput\n[null,null,null,null,[2],[2,1],null,[4]]\n\nExplanation\nTweetCounts tweetCounts = new TweetCounts();\ntweetCounts.recordTweet(\"tweet3\", 0);\ntweetCounts.recordTweet(\"tweet3\", 60);\ntweetCounts.recordTweet(\"tweet3\", 10); // All tweets correspond to \"tweet3\" with recorded times at 0, 10 and 60.\ntweetCounts.getTweetCountsPerFrequency(\"minute\", \"tweet3\", 0, 59); // return [2]. The frequency is per minute (60 seconds), so there is one interval of time: 1) [0, 60> - > 2 tweets.\ntweetCounts.getTweetCountsPerFrequency(\"minute\", \"tweet3\", 0, 60); // return [2, 1]. The frequency is per minute (60 seconds), so there are two intervals of time: 1) [0, 60> - > 2 tweets, and 2) [60,61> - > 1 tweet.\ntweetCounts.recordTweet(\"tweet3\", 120); // All tweets correspond to \"tweet3\" with recorded times at 0, 10, 60 and 120.\ntweetCounts.getTweetCountsPerFrequency(\"hour\", \"tweet3\", 0, 210); // return [4]. The frequency is per hour (3600 seconds), so there is one interval of time: 1) [0, 211> - > 4 tweets.\n\n\nConstraints:\n\nThere will be at most 10000 operations considering both recordTweet and getTweetCountsPerFrequency.\n0 <= time, startTime, endTime <= 10^9\n0 <= endTime - startTime <= 10^4\n\"\"\"\nfrom bisect import insort, bisect_left, bisect_right\nfrom math import ceil\n\n\nclass TweetCounts_bisect:\n\n def __init__(self):\n self.tweets={}\n\n def recordTweet(self, tweetName: str, time: int) -> None:\n if tweetName not in self.tweets:\n self.tweets[tweetName] = []\n insort(self.tweets[tweetName], time)\n\n def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int):\n entry = self.tweets[tweetName]\n diff = endTime - startTime\n\n factor = 86400\n if freq == 'minute':\n factor = 60\n elif freq == 'hour':\n factor = 3600\n\n buckets = ceil((diff + 1) / factor)\n ans = [0]*buckets\n\n start = bisect_left(entry, startTime)\n end = bisect_right(entry, endTime)\n\n for i in range(start, end):\n time = entry[i]\n d = (time - startTime) // factor\n ans[d] += 1\n return ans\n\n\nclass TweetCounts:\n\n def __init__(self):\n self._buf = []\n self._timestep = {'minute': 60, 'hour': 3600, 'day': 3600 * 24}\n\n def search(self, time, left=True):\n\n low, high = 0, len(self._buf)\n while low < high:\n\n mid = (low + high) // 2\n\n if self._buf[mid][0] > time or (left and self._buf[mid][0] == time):\n high = mid\n else:\n low = mid + 1\n\n return low\n\n def recordTweet(self, tweetName: str, time: int) -> None:\n\n i = self.search(time)\n if i < len(self._buf) and self._buf[i][0] == time:\n self._buf[i][1][tweetName] = self._buf[i][1].get(tweetName, 0) + 1\n else:\n self._buf.insert(i, (time, {tweetName: 1}))\n\n def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int):\n if freq not in self._timestep:\n return []\n step, res = self._timestep[freq], []\n for s in range(startTime, endTime+1, step):\n l, r = self.search(s), self.search(min(s+step, endTime+1))\n res.append(sum(self._buf[i][1][tweetName] for i in range(l, r) if tweetName in self._buf[i][1]))\n return res\n\n\nif __name__ == '__main__':\n\n obj = TweetCounts()\n\n obj.recordTweet(\"tweet3\", 0)\n\n obj.recordTweet(\"tweet3\", 60)\n\n obj.recordTweet(\"tweet3\", 10)\n\n obj.getTweetCountsPerFrequency(\"minute\", \"tweet3\", 0, 59)\n\n obj.getTweetCountsPerFrequency(\"minute\", \"tweet3\", 0, 60)\n\n obj.recordTweet(\"tweet3\", 120)\n\n obj.getTweetCountsPerFrequency(\"hour\", \"tweet3\", 0, 120)","sub_path":"PythonLeetcode/Leetcode/1348_TweetCountsPerFrequency.py","file_name":"1348_TweetCountsPerFrequency.py","file_ext":"py","file_size_in_byte":5069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"511104323","text":"import os\nimport requests\nimport json\n\nfrom flask import Flask, render_template, request, send_from_directory\n#import numpy as np # numeric processing package\n#import skimage\n#import skimage.io as io # image processing\n\n#from tensorflow import keras\n\n__author__ = 'lmw'\n\napp = Flask(__name__)\n\nAPP_ROOT = os.path.dirname(os.path.abspath(__file__))\n\n#DIGITOCR_API = 'http://10.100.200.12:8000/api'\nDIGITOCR_API = 'http://digitocr-service:8000/api'\n\n@app.route(\"/\")\ndef index():\n return render_template(\"upload.html\")\n\n@app.route(\"/upload\", methods=[\"POST\"])\ndef upload():\n target = os.path.join(APP_ROOT, 'uploaded_images/')\n # target = os.path.join(APP_ROOT, 'static/')\n print(target)\n if not os.path.isdir(target):\n os.mkdir(target)\n else:\n print(\"Couldn't create upload directory: {}\".format(target))\n\n print(request.files.getlist(\"file\"))\n for upload in request.files.getlist(\"file\"):\n\n filename = upload.filename\n destination = \"/\".join([target, filename])\n\n upload.save(destination)\n\n f = open(destination, 'rb')\n myfiles = {'image': f}\n digitocr = requests.post(DIGITOCR_API, files = myfiles)\n f.close()\n digitocr_dict = digitocr.json()\n\n prediction = digitocr_dict['prediction']\n ver = digitocr_dict['ver']\n\n# return send_from_directory(\"images\", filename, as_attachment=True)\n return render_template(\"complete_display_image.html\", image_name=filename, ocr_output = prediction, ocr_ver = ver )\n\n\n@app.route('/upload/')\ndef send_image(filename):\n return send_from_directory(\"uploaded_images\", filename)\n\nif __name__ == \"__main__\":\n port = int(os.getenv(\"PORT\", 80))\n app.run(host='0.0.0.0', port=port, debug=False)","sub_path":"LESSON-14-Kubernetes-DigitOCR-RESTAPI/DigitOCR-Frontend/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"57456279","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Company',\n fields=[\n ('company_id', models.IntegerField(serialize=False, primary_key=True)),\n ('name', models.CharField(max_length=50)),\n ('website', models.CharField(default=b'0', max_length=100)),\n ('total_Reviews', models.IntegerField(default=0)),\n ('average', models.DecimalField(default=0, max_digits=3, decimal_places=2)),\n ('logo', models.CharField(default=b'0', max_length=200)),\n ('industry', models.CharField(default=b'0', max_length=50)),\n ],\n ),\n ]\n","sub_path":"crunchDoorApp/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"381852815","text":"import socket\nimport time\nimport threading\nfrom Embedded_System.DataBase import database\n\nmsg = \"non\"\npf = True\ncf = True\n\ndef phone(sp):\n global msg\n while pf:\n try:\n request = sp.recv(1024)\n reply = \"phone say : \" + request.decode() + \"/\\n\"\n sp.sendall(reply.encode())\n msg = request.decode()\n except socket.timeout:\n pass\n \ndef car(sc):\n global msg\n while cf:\n try:\n request = sc.recv(1024)\n reply = \"Car say : \" + request.decode() + \"/\\n\"\n print(reply)\n sc.sendall(reply.encode())\n except socket.timeout:\n if msg == \"get\":\n sc.sendall(\"Car gogogo!!!\".encode())\n msg = \"non\"\n \n\n\nif __name__ == \"__main__\":\n \n host = \"192.168.50.1\"\n port = 55688\n\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.bind((host,port)) # 固定ip與port\n s.listen(1) # 監聽最大數量\n s.settimeout(5)\n try : \n while True:\n try : \n con,addr = s.accept()\n print(con,\"//\",addr)\n request = con.recv(1024)\n print(\"request : \",request.decode())\n reply = \"You are / \" + request.decode() + \" /\"\n print(reply)\n con.sendall(reply.encode())\n if request.decode() == \"phone\":\n con.settimeout(0.5)\n pt = threading.Thread(target = phone,args=[con])\n pt.start()\n elif request.decode() == \"car_WiFi\":\n con.settimeout(0.5)\n ct = threading.Thread(target=car,args=[con])\n ct.start()\n else:\n con.close()\n except socket.timeout:\n print(\".\")\n\n except KeyboardInterrupt:\n cf = False\n pf = False\n try : \n pt.join()\n ct.join()\n except NameError:\n pass\n s.close()\n print(\"Server Close\")\n\n\n","sub_path":"Python/socketServer.py","file_name":"socketServer.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"244208624","text":"from __future__ import absolute_import\nimport unittest\n\n\ndef reverse_vowel(raw_string):\n \"\"\"\n Given a string, reverse only the vowel characters.\n\n ie: \"hello\" -> \"holle\"\n \"helelo\" -> \"holele\"\n\n :param raw_string: Lowercase alphabet string\n :return: Same string but with the vowels in reversed order\n \"\"\"\n\n \"\"\"\n Consider having two pointers and each end of the strings, we'll move them inwards until they collide or until they\n both reach a vowel, then we swap the letters they point to.\n \"\"\"\n\n letters = list(raw_string)\n vowels = ('a', 'e','i','o', 'u')\n\n def swap(a, b):\n temp = letters[a]\n letters[a] = letters[b]\n letters[b] = temp\n\n head = 0\n tail = len(raw_string) - 1\n\n while head <= tail:\n\n while letters[head] not in vowels and head < tail:\n head += 1\n\n while letters[tail] not in vowels and head < tail:\n tail -= 1\n\n if head > tail:\n return \"\".join(letters)\n\n swap(head, tail)\n head += 1\n tail -= 1\n\n return \"\".join(letters)\n\n\nclass TestReverseVowels(unittest.TestCase):\n def test_normals(self):\n self.assertEquals(reverse_vowel(\"hello\"), \"holle\")\n self.assertEquals(reverse_vowel(\"helelo\"), \"holele\")\n self.assertEquals(reverse_vowel(\"bcdfgh\"),\"bcdfgh\")\ngi\n\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"python/reverse_vowels.py","file_name":"reverse_vowels.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"97761085","text":"#!/usr/bin/env python\n# coding: UTF-8\n\nimport parcelles_buildings_2_db as a\nimport sys\nimport os\n\nif len(sys.argv) != 2:\n print('Mauvais nombre d\\'arguments')\n print('USAGE : ./import_parcelles_buildings.py ')\n os._exit(0)\n\nclause_where = ''\nif sys.argv[1].upper() != 'FRANCE':\n\tnum_dept_cadastre = ('000'+sys.argv[1])[-3:]\n\tclause_where = 'AND cadastre_dept = \\'{:s}\\''.format(num_dept_cadastre)\n\t\npgc = a.get_pgc()\n#str_query = 'SELECT DISTINCT c.insee_com,c.nom_com,c.cadastre_dept FROM code_cadastre c LEFT OUTER JOIN (SELECT cadastre_com FROM batch WHERE etape = \\'{:s}\\' AND date_fin IS NOT NULL AND nombre_adresses > 0 INTERSECT SELECT cadastre_com FROM batch WHERE etape = \\'{:s}\\' AND date_fin IS NOT NULL AND nombre_adresses > 0 ) j ON c.cadastre_com = j.cadastre_com WHERE j.cadastre_com IS NULL AND c.format_cadastre = \\'VECT\\' {:s} ORDER BY 3,2;'.format('importParcelles','importBuildings',clause_where)\n#str_query = \"SELECT DISTINCT c.insee_com,c.nom_com,c.cadastre_dept FROM code_cadastre c JOIN (SELECT cadastre_com FROM code_cadastre WHERE format_cadastre = 'VECT' {:s} EXCEPT SELECT b1.cadastre_com FROM batch b1 JOIN batch b2 USING (cadastre_com) WHERE b1.etape in ('importParcelles','importBuildings') AND b2.etape = 'recupCadastre' AND b1.timestamp_debut > b2.timestamp_debut)j USING (cadastre_com) ORDER BY 3,2;\".format(clause_where)\n#str_query = \"SELECT DISTINCT c.insee_com,c.nom_com,c.cadastre_dept FROM code_cadastre c WHERE format_cadastre = 'VECT' {:s} ORDER BY 3,2;\".format(clause_where)\n\n# On ne traite que les communes dont l'import initial est posterieur au dernier import de bâtiments\nstr_query = \"SELECT DISTINCT c.insee_com,c.nom_com,c.cadastre_dept FROM code_cadastre c JOIN (SELECT cadastre_com FROM code_cadastre WHERE format_cadastre = 'VECT' {:s} EXCEPT SELECT b1.cadastre_com FROM batch b1 JOIN batch b2 USING (cadastre_com) WHERE b1.etape = 'importQadastre' AND b2.etape = 'importBuildings' AND b1.timestamp_debut < b2.timestamp_debut)j USING (cadastre_com) ORDER BY 3,2;\".format(clause_where)\n\ncur = pgc.cursor()\ncur.execute(str_query)\nfor c in cur:\n\tprint(c[0]+' '+c[1])\n\ta.main(['','{:s}'.format(c[0])])\n","sub_path":"import_parcelles_buildings.py","file_name":"import_parcelles_buildings.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"443906073","text":"__author__ = 'yuriic'\n\n\"\"\"\nImplement LRU.\n\"\"\"\n\nclass node:\n def __init__(self, value, prev = None, next = None ):\n self.value = value\n self.next= next\n self.prev= prev\n\n\nclass LRU:\n def __init__(self, capacity):\n self.capacity = capacity\n self.items = 0\n self.hash={}\n self.root = None\n self.tail = None\n\n def add(self, value):\n if value in self.hash:\n self.__bubble(self.hash[value])\n else:\n if self.LRU_full:\n self.__pop()\n self.__push(value)\n\n def top(self):\n if self.root is not None:\n return self.root.value\n return None\n\n @property\n def LRU_full(self):\n return self.items >= self.capacity\n\n def __bubble(self, node):\n if node.prev is not None:\n node.prev.next = node.next\n if node.next is not None:\n node.next.prev = node.prev\n\n node.prev = None\n node.next = self.root\n if self.root is not None:\n self.root.prev = node\n self.root = node\n\n\n def __pop(self):\n if not self.tail:\n return\n del self.hash[self.tail.value]\n self.tail = self.tail.prev\n self.items -= 1\n\n\n def __push(self, value):\n if self.LRU_full:\n return\n new_root = node(value, None, self.root)\n if self.root is not None:\n self.root.prev=new_root\n self.root = new_root\n self.items += 1\n if self.tail is None:\n self.tail = new_root\n self.hash[value]=self.root\n\n\nlru = LRU(3)\nlru.add(1)\nprint(lru.top(), lru.items)\nlru.add(2)\nprint(lru.top(), lru.items)\nlru.add(1)\nprint(lru.top(), lru.items)\nlru.add(3)\nlru.add(4)\nprint(lru.top(), lru.items)\nlru.add(5)\nprint(lru.top(), lru.items)","sub_path":"q_01.py","file_name":"q_01.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"97929793","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 12 00:07:41 2018\n\n@author: b10l07\n\"\"\"\n\nfobj = open(\"ircnicks.txt\",\"w\")\nfobj.write(\"Bennie\\n\")\nfobj.write(\"Lydia\")\nfobj.close()\n\n","sub_path":"file_operating.py","file_name":"file_operating.py","file_ext":"py","file_size_in_byte":198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"471612342","text":"from pathlib import Path\nimport requests\nimport argparse\nimport logging\nimport shutil\nimport json\nimport sys\nimport re\nimport os\n\nimport pprint\n\n# Initialize logger for this module.\nLOG_FMT_STRING = (\n\t'[%(asctime)s] %(levelname)s %(module)s %(lineno)d - %(message)s'\n)\nlogging.basicConfig(level=logging.INFO, format=LOG_FMT_STRING)\nlog = logging.getLogger(__name__)\n\n# create a 'copied_files' folder\ndef checkDir(name, list_path):\n\tfile_path = ''.join((list_path, name))\n\n\tif os.path.isdir(file_path):\n\t\tlog.info(f'<{name}> directory exists')\n\telse:\n\t\tlog.info(f'Does not exist. Creating <{name}> directory...')\n\t\t# subprocess.run(['mkdir', name])\n\t\tos.mkdir(file_path)\n\ndef rename_file(file_path, new_name, counter=None):\n\tnew_name = f'{new_name}{counter}{file_path.suffix}'\n\n\treturn new_name\n\ndef get_files(target_path, filter_pat=None):\n\ttry:\n\t\tif filter_pat:\n\t\t\tfilter_pat = re.compile(filter_pat)\n\t\t\tlog.debug(\n\t\t\t\tf'Searching files matching pattern: {filter_pat.pattern}'\n\t\t\t)\n\texcept Exception as err:\n\t\tmsg = f'Invalid filter: {err}'\n\t\tlog.error(msg)\n\t\traise Exception(msg)\n\n\tfor file_ in target_path.iterdir():\n\t\tif filter_pat:\n\t\t\tif filter_pat.match(file_.name):\n\t\t\t\tyield file_\n\t\t\telse:\n\t\t\t\tlog.debug(f'File {file_.name} did not match pattern.')\n\t\telse:\n\t\t\tyield file_\n\ndef copy_file(target_dir, file_pattern=None, log_level=None):\n\tsource_application = os.path.basename(__file__)\n\torig_dir = target_dir\n\ttarget_dir = Path(target_dir)\n\n\tif not target_dir.is_dir():\n\t\tlog_level = 'error'\n\t\tmessage = '[target_dir] does not exist or is not a directory.'\n\t\tlog.error(message)\n\t\t\n\t\ttemp = {\n\t\t\t\"log_level\": log_level.upper(),\n\t\t\t\"message\": message,\n\t\t\t\"details\": \"\",\n\t\t\t\"source_application\": source_application\n\t\t}\n\n\t\tpayload = json.dumps(temp)\n\t\tcallLoggingAndNotifAPI(payload)\t\n\telse:\n\t\tbase_path = '/home/kent/Desktop/python/python_capstone/python_capstone_project/'\n\t\tdir_name = 'copied_files'\n\n\t\t# check if 'copied_files' directory exists\n\t\t# if not, create one\n\t\tcheckDir(dir_name, base_path)\n\n\t\tdir_path = ''.join((base_path, dir_name))\n\t\trequest_message = ''\n\t\tmessage_list = []\n\n\t\t# iterate through matched files \n\t\tfor file_ in get_files(target_dir, filter_pat=file_pattern):\n\t\t\tlog.info(f'Found {file_}')\n\t\t\n\t\t\t# create and store copy of each file in the 'copied_files' directory\n\t\t\tsrc = orig_dir + file_.name\n\t\t\tshutil.copy(src, dir_path)\n\t\t\tmessage = f'Copied {src} -> {dir_path},'\n\t\t\tlog.info(f'{message}\\n\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n')\n\n\t\t\t# populate message_list\n\t\t\tmessage_list.append(message)\n\n\t\t# append each row of 'message_list' into 'request_message',\n\t\t# which will be passed as the 'key2' or 'Message' parameter\n\t\t# for the 'callLoggingAndNotifAPI' function\n\t\tfor row in message_list:\n\t\t\tmessages = row.strip()\n\t\t\t# add a newline per row for better readability\n\t\t\trequest_message = '\\n'.join((request_message, messages))\n\t\t\t\n\t\tif len(request_message) == 0:\n\t\t\trequest_message = f'File/s with file pattern <{file_pattern}> not found.'\n\t\t\tlog_level = 'error'\n\n\t\t# generate payload to be passed as an argument to the \n\t\t# 'callLoggingAndNotifAPI' function\n\t\ttemp = {\n\t\t\t\"log_level\": log_level.upper(),\n\t\t\t\"message\": request_message,\n\t\t\t\"details\": \"\",\n\t\t\t\"source_application\": source_application\n\t\t}\n\n\t\tpayload = json.dumps(temp)\n\t\tcallLoggingAndNotifAPI(payload)\t\n\t\t\t\n\t\treturn True\n\ndef bulk_rename_files(target_dir, new_name, file_pattern=None, log_level=None):\n\tsource_application = os.path.basename(__file__)\n\ttarget_dir = Path(target_dir)\t\t\n\n\tif not target_dir.is_dir():\n\t\tmessage = f'<{target_dir}> does not exist or is not a directory.'\n\t\tlog.error(message)\n\n\t\t# generate payload to be passed as an argument to the \n\t\t# callLoggingAndNotifAPI function\n\t\ttemp = {\n\t\t\t\"log_level\": 'ERROR',\n\t\t\t\"message\": message,\n\t\t\t\"details\": \"\",\n\t\t\t\"source_application\": source_application\n\t\t}\n\n\t\tpayload = json.dumps(temp)\n\t\tcallLoggingAndNotifAPI(payload)\n\n\t\treturn False\n\telse:\n\t\trequest_message = ''\n\t\tmessage_list = []\n\t\tcounter = 1\n\n\t\t# iterate through matched files \n\t\tfor file_ in get_files(target_dir, filter_pat=file_pattern):\n\t\t\tlog.info(f'Found {file_}')\n\n\t\t\t# generate new filenames and paths for every matched file \n\t\t\tupdated_name = rename_file(file_, new_name, counter=counter)\n\t\t\tnew_path = file_.parent.joinpath(updated_name)\t\t\n\n\t\t\t# update paths\n\t\t\tshutil.move(file_, new_path)\n\t\t\tmessage = f'Renamed {file_.name} -> {new_path.name}, '\n\t\t\tlog.info(f'{message}\\n\\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n')\n\n\t\t\tcounter += 1\n\n\t\t\t# populate message_list\n\t\t\tmessage_list.append(message)\n\n\t\t# append each row of message_list into request_message,\n\t\t# which will be passed as the 'key2' or 'Message' parameter\n\t\t# for the 'callLoggingAndNotifAPI' function\n\t\tfor row in message_list:\n\t\t\tmessages = row.strip()\n\t\t\t# add a newline per row for better readability\n\t\t\trequest_message = '\\n'.join((request_message, messages))\n\t\t\n\t\tif len(request_message) == 0:\n\t\t\trequest_message = f'File/s with file pattern <{file_pattern}> not found.'\n\t\t\tlog_level = 'error'\n\n\t\t# generate payload to be passed as an argument to the \n\t\t# 'callLoggingAndNotifAPI' function\n\t\ttemp = {\n\t\t\t\"log_level\": log_level.upper(),\n\t\t\t\"message\": request_message,\n\t\t\t\"details\": \"\",\n\t\t\t\"source_application\": source_application\n\t\t}\n\n\t\tpayload = json.dumps(temp)\n\t\tcallLoggingAndNotifAPI(payload)\n\t\t\t\n\t\treturn True\n\ndef callLoggingAndNotifAPI(payload):\n\tlog.info('Processing request...')\n\n\tresponse = requests.post(\n\t\turl=\"https://qm5etw0909.execute-api.ap-southeast-1.amazonaws.com/default/kent-capstone\",\n\t\theaders={'x-api-key': ''},\n\t\tdata=payload\n\t)\n\n\tlog.info(f'{response.json()}')\n\ndef main(args):\n\ttry:\t\t\n\t\t\n\t\tif args.copy == 'True':\n\t\t\tsuccess = copy_file(\n\t\t\t\targs.target_dir, \n\t\t\t\targs.file_pattern, \n\t\t\t\targs.log_level\n\t\t\t)\n\t\telse:\t\t\t\n\t\t\tsuccess = bulk_rename_files(\n\t\t\t\targs.target_dir, \n\t\t\t\targs.new_name, \n\t\t\t\targs.file_pattern,\n\t\t\t\targs.log_level\n\t\t\t)\n\t\t\n\t\tif success:\n\t\t\tsys.exit(0)\n\t\telse:\n\t\t\tsys.exit(1)\n\texcept Exception:\n\t\tsys.exit(1)\n\nif __name__ == '__main__':\t\n\tparser = argparse.ArgumentParser()\n\n\tparser.add_argument(\n\t\t'new_name',\n\t\thelp=('Files matching `file_pattern` will be renamed with this value. '\n\t\t\t 'An incrementing count will also be added.'),\n\t)\n\tparser.add_argument(\n\t\t'file_pattern',\n\t\thelp='Files to rename (Regex compatible).',\n\t)\n\tparser.add_argument(\n\t\t'target_dir',\n\t\thelp='Directory where the files to rename or copy reside.',\n\t)\n\tparser.add_argument(\n\t\t'-L', '--log-level',\n\t\thelp='Set log level: (NOTSET / DEBUG / INFO / WARNING / ERROR / CRITICAL).',\n\t\tdefault='info'\n\t)\n\tparser.add_argument(\n\t\t'-C', '--copy',\n\t\thelp='Create a copy: (True / False).',\n\t\tdefault='False'\n\t)\n\t\n\targs = parser.parse_args()\n\n\t# Configure logger\n\tlogging.basicConfig(\n\t\tlevel=getattr(logging, args.log_level.upper()),\n\t\tformat=LOG_FMT_STRING,\n\t)\n\n\tmain(args)\n","sub_path":"bulk_renamer.py","file_name":"bulk_renamer.py","file_ext":"py","file_size_in_byte":6783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"344798769","text":"# import the general settings for the project\nfrom django_project.settings.common import *\nfrom django_project.settings.logging import *\nimport logging\n\nlogger = logging.getLogger(__name__)\n\ntry:\n # read secret key\n keyfile = os.path.join(BASE_DIR, \"..\", \"..\", \"secret_key.key\")\n if os.path.exists(keyfile):\n f = open(keyfile)\n SECRET_KEY = f.read()\n else:\n SECRET_KEY = \"PlsChgMe\"\n\nexcept:\n SECRET_KEY = \"PlsChgMe\"\n logger.error(\"Django CONFIG: Default secret key not reconfigured, use '%s'\" % SECRET_KEY)\n\n# include production configuration (if available)\ntry:\n # deploy configuration requires a postgres server environment\n from django_project.settings.deploy import *\n\n SECURE_CONTENT_TYPE_NOSNIFF = True\n SECURE_BROWSER_XSS_FILTER = True\n\nexcept:\n logger.warn(\"Django CONFIG: Deploy configuration not found, use development configuration\")\n\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, \"..\", \"db.sqlite3\"),\n }\n }\n\n DEBUG = True\n ALLOWED_HOSTS = []\n\nfrom django_project.settings.celery import *\n\n\"\"\"\nConfigure logging settings\n\"\"\"\nlevel = os.getenv('DJANGO_LOG_LEVEL', 'INFO')\n\n# if debug mode is enabled in Django, also set the global logging level to Debug\nif DEBUG:\n level = 'DEBUG'\n\nlog_file = os.path.join(BASE_DIR, \"..\", \"..\", \"logs\")\nLOGGING = configure_logging(level, log_file, \"product_db.log\")\n\nlogging.getLogger().warn(\"DJANGO CONFIG: Start logging on level: %s\" % level)\n\nfrom django_project.settings.rest_framework import *\nfrom django_project.settings.swagger_api import *\n","sub_path":"django_project/settings/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"98990605","text":"# -*- coding: utf-8 -*-\r\n#\r\n# utils.py\r\n#\r\n# Copyright (C) libracore, 2017-2020\r\n# https://www.libracore.com or https://github.com/libracore\r\n#\r\n# For information on ERPNext, refer to https://erpnext.org/\r\n#\r\n\r\nimport frappe\r\nimport json\r\nimport urllib.parse\r\nimport six\r\nimport pdfkit, os\r\nfrom frappe import _, attach_print\r\nfrom frappe.utils.data import today, add_days\r\nfrom frappe.contacts.doctype.address.address import get_address_display\r\nimport csv\r\nfrom PyPDF2 import PdfFileWriter, PdfFileReader\r\nimport socket\r\n\r\n@frappe.whitelist()\r\ndef check_batch_release(delivery_note=None):\r\n data = {}\r\n data['status'] = 'ok'\r\n data['items'] = []\r\n\t\r\n if delivery_note:\r\n items = frappe.db.sql(\"\"\"SELECT `item_name`, `item_code`, `customer_item_code`, `batch_no` FROM `tabDelivery Note Item` WHERE `parent` = '{delivery_note}'\"\"\".format(delivery_note=delivery_note), as_dict=True)\r\n for item in items:\r\n if item.batch_no:\r\n item_master = frappe.get_doc(\"Item\", item.item_code)\r\n if item_master.benoetigt_chargenfreigabe:\r\n batch = frappe.get_doc(\"Batch\", item.batch_no)\r\n if not batch.freigabedatum:\r\n data['status'] = 'nok'\r\n data['items'].append(item)\r\n return data\r\n\r\n@frappe.whitelist()\r\ndef get_help_links():\r\n sql_query = \"\"\"SELECT * FROM `tabEinstellungen Dokumentation DocTypes`\"\"\"\r\n links = frappe.db.sql(sql_query, as_dict=True)\r\n if links:\r\n return links\r\n else:\r\n return False\r\n\r\n@frappe.whitelist()\r\ndef transfer_item_drawings(po, items):\r\n if isinstance(items, six.string_types):\r\n items = json.loads(items)\r\n counter = 0\r\n for _item in items:\r\n item = frappe.get_doc(\"Item\", _item)\r\n if item.zeichnung:\r\n file_url = item.zeichnung\r\n filename = get_file_name(file_url)\r\n dt = 'Purchase Order'\r\n dn = po\r\n if len(check_if_attachment_exist(file_url, dn)) < 1:\r\n f = frappe.get_doc({\r\n \"doctype\": \"File\",\r\n \"file_url\": file_url,\r\n \"file_name\": filename,\r\n \"attached_to_doctype\": dt,\r\n \"attached_to_name\": dn,\r\n \"folder\": 'Home/Attachments',\r\n \"file_size\": 0,\r\n \"is_private\": 0\r\n })\r\n f.flags.ignore_permissions = True\r\n try:\r\n f.insert()\r\n frappe.db.commit()\r\n counter += 1\r\n except:\r\n pass\r\n return counter\r\n\r\ndef get_file_name(file_url):\r\n return frappe.db.sql(\"\"\"SELECT `file_name` FROM `tabFile` WHERE `file_url` = '{file_url}' LIMIT 1\"\"\".format(file_url=file_url), as_list=True)[0][0]\r\n\r\ndef check_if_attachment_exist(file_url, dn):\r\n return frappe.db.sql(\"\"\"SELECT `name` FROM `tabFile` WHERE `file_url` = '{file_url}' AND `attached_to_name` = '{dn}'\"\"\".format(file_url=file_url, dn=dn), as_list=True)\r\n\r\n@frappe.whitelist()\r\ndef get_next_purchase_item_number():\r\n latest_pt_number = frappe.db.sql(\"\"\"SELECT `name` FROM `tabItem` WHERE `is_purchase_item` = 1 AND `name` LIKE 'PT-%' ORDER BY `creation` DESC\"\"\", as_list=True)\r\n raw_pt_number = latest_pt_number[0][0]\r\n pt_number = int(raw_pt_number.replace(\"PT-\", ''))\r\n new_pt_number = pt_number + 1\r\n new_pt_number = \"PT-\"+(\"0000{pt}\".format(pt=new_pt_number))[-5:]\r\n return new_pt_number\r\n\r\n@frappe.whitelist()\r\ndef entnahme_blech(item):\r\n item = frappe.get_doc(\"Item\", item)\r\n if item.stock_uom == 'Stk':\r\n return {\r\n 'qty': 1.000,\r\n 'conversion_factor': 1,\r\n 'stock_uom': item.stock_uom\r\n }\r\n else:\r\n for uom in item.uoms:\r\n if uom.uom == 'Stk':\r\n return {\r\n 'qty': 1 * uom.conversion_factor,\r\n 'conversion_factor': uom.conversion_factor,\r\n 'stock_uom': item.stock_uom\r\n }\r\n return {'error': _('No Conversion Factor to UOM Stk')}\r\n\r\n@frappe.whitelist()\r\ndef check_for_batch_quick_stock_entry(batch_no, warehouse, item):\r\n benoetigt_chargenfreigabe = float(frappe.get_doc(\"Item\", item).benoetigt_chargenfreigabe)\r\n if batch_no and warehouse:\r\n entry_qty = float(frappe.db.sql(\"\"\"SELECT SUM(`actual_qty`)\r\n FROM `tabStock Ledger Entry`\r\n WHERE `warehouse` = '{warehouse}' AND `batch_no` = '{batch_no}' AND `actual_qty` > 0\"\"\".format(warehouse=warehouse, batch_no=batch_no), as_list=True)[0][0] or 0)\r\n return {\r\n 'entry_qty': entry_qty,\r\n 'benoetigt_chargenfreigabe': benoetigt_chargenfreigabe\r\n }\r\n\r\n@frappe.whitelist()\r\ndef batch_quick_stock_entry(batch_no, warehouse, item, qty):\r\n stock_entry = frappe.get_doc({\r\n 'doctype': 'Stock Entry',\r\n 'stock_entry_type': \"Material Receipt\",\r\n 'to_warehouse': warehouse,\r\n 'items': [{\r\n 'item_code': item,\r\n 'qty': qty,\r\n 'batch_no': batch_no\r\n }]\r\n }).insert()\r\n stock_entry.submit()\r\n\r\n return stock_entry.name\r\n\r\n@frappe.whitelist()\r\ndef nachbestellung(item, supplier, qty, taxes):\r\n lieferzeit = frappe.get_doc(\"Item\", item).lead_time_days or 0\r\n schedule_date = add_days(today(), lieferzeit)\r\n \r\n purchase_order = frappe.get_doc({\r\n 'doctype': 'Purchase Order',\r\n 'supplier': supplier,\r\n 'schedule_date': schedule_date,\r\n 'taxes_and_charges': taxes,\r\n 'items': [{\r\n 'item_code': item,\r\n 'qty': qty,\r\n 'schedule_date': schedule_date\r\n }]\r\n }).insert()\r\n\r\n return purchase_order.name\r\n \r\n@frappe.whitelist()\r\ndef update_adress_display(doctype, doc_name, fields, addresses, as_list=False):\r\n if as_list:\r\n if isinstance(fields, six.string_types):\r\n fields = json.loads(fields)\r\n if isinstance(addresses, six.string_types):\r\n addresses = json.loads(addresses)\r\n count = 0\r\n response = []\r\n for field in fields:\r\n address = addresses[count]\r\n address_html = get_address_display(address)\r\n old_display = frappe.db.sql(\"\"\"SELECT `{field}` FROM `tab{doctype}` WHERE `name` = '{doc_name}'\"\"\".format(field=field, doctype=doctype, doc_name=doc_name), as_dict=True)\r\n count += 1\r\n if len(old_display) >= 1:\r\n if old_display[0][field] != address_html:\r\n frappe.db.sql(\"\"\"UPDATE `tab{doctype}` SET `{field}` = '{address_html}' WHERE `name` = '{doc_name}'\"\"\".format(field=field, doctype=doctype, doc_name=doc_name, address_html=address_html), as_list=True)\r\n frappe.db.commit()\r\n response.append('updated')\r\n else:\r\n response.append('passed')\r\n else:\r\n response.append('no address')\r\n return response\r\n else:\r\n field = fields\r\n address = addresses\r\n address_html = get_address_display(address)\r\n old_display = frappe.db.sql(\"\"\"SELECT `{field}` FROM `tab{doctype}` WHERE `name` = '{doc_name}'\"\"\".format(field=field, doctype=doctype, doc_name=doc_name), as_dict=True)\r\n if len(old_display) >= 1:\r\n if old_display[0][field] != address_html:\r\n frappe.db.sql(\"\"\"UPDATE `tab{doctype}` SET `{field}` = '{address_html}' WHERE `name` = '{doc_name}'\"\"\".format(field=field, doctype=doctype, doc_name=doc_name, address_html=address_html), as_list=True)\r\n frappe.db.commit()\r\n return 'updated'\r\n else:\r\n return 'passed'\r\n else:\r\n return 'no address'\r\n \r\n@frappe.whitelist()\r\ndef calculate_versanddatum(so):\r\n sales_order = frappe.get_doc(\"Sales Order\", so)\r\n vorlauf = frappe.get_doc(\"Customer\", sales_order.customer).vorlaufzeit_versand\r\n if vorlauf and vorlauf > 0:\r\n try:\r\n new_date = add_days(sales_order.delivery_date, vorlauf * -1)\r\n frappe.db.sql(\"\"\"UPDATE `tabSales Order` SET `versanddatum` = '{new_date}' WHERE `name` = '{so}'\"\"\".format(new_date=new_date, so=so), as_list=True)\r\n frappe.db.commit()\r\n return 'updated'\r\n except:\r\n return 'passed'\r\n else:\r\n try:\r\n new_date = sales_order.delivery_date\r\n frappe.db.sql(\"\"\"UPDATE `tabSales Order` SET `versanddatum` = '{new_date}' WHERE `name` = '{so}'\"\"\".format(new_date=new_date, so=so), as_list=True)\r\n frappe.db.commit()\r\n return 'updated'\r\n except:\r\n return 'passed'\r\n \r\n@frappe.whitelist()\r\ndef create_payment(sinv):\r\n try:\r\n sinv = frappe.get_doc(\"Sales Invoice\", sinv)\r\n pe = frappe.get_doc({\r\n \"doctype\": \"Payment Entry\",\r\n 'posting_date': today(),\r\n \"payment_type\": \"Receive\",\r\n \"party_type\": \"Customer\",\r\n \"party\": sinv.customer,\r\n \"paid_from\": '1100 - Forderungen Schweiz - ST',\r\n 'paid_to': '1020 - KK ZKB 1042-0171.171 - ST',\r\n 'paid_amount': sinv.outstanding_amount,\r\n 'received_amount': sinv.outstanding_amount,\r\n \"references\": [\r\n {\r\n \"reference_doctype\": \"Sales Invoice\",\r\n 'reference_name': sinv.name,\r\n 'allocated_amount': sinv.outstanding_amount\r\n }\r\n ],\r\n \"reference_no\": sinv.name,\r\n 'reference_date': today(),\r\n 'remarks': 'Auto Payment for {sinv}'.format(sinv=sinv.name)\r\n })\r\n pe.insert()\r\n pe.submit()\r\n return pe.name\r\n except Exception as err:\r\n return err\r\n\r\n@frappe.whitelist()\r\ndef get_histogramm_data(item, batch, messdaten_nullpunkt=None, messdaten_last=None):\r\n histogramm_data = []\r\n max_anzahl = 0\r\n item = frappe.get_doc(\"Item\", item)\r\n for _histogramm in item.histogramme:\r\n histogramm = frappe.get_doc(\"Senstech Histogramm\", _histogramm.histogramm)\r\n _histogramm_data = {\r\n 'title': histogramm.histogramm_titel,\r\n 'x_title': histogramm.x_beschriftung,\r\n 'y_title': histogramm.y_beschriftung,\r\n 'bins': [],\r\n 'bin_range': [],\r\n 'values': [],\r\n 'qty': 0\r\n }\r\n data_row = histogramm.daten_spalte\r\n for bin in histogramm.klassen:\r\n _histogramm_data['bin_range'].append([bin.range_von, bin.range_bis])\r\n _histogramm_data['values'].append(0)\r\n _histogramm_data['bins'].append(bin.bezeichnung)\r\n\r\n if messdaten_nullpunkt:\r\n with open(frappe.get_site_path(messdaten_nullpunkt.strip('/')), 'r') as f:\r\n reader = csv.reader(f, dialect='excel', delimiter='\\t')\r\n first_row = True\r\n data_row_found = False\r\n data_row_int = 0\r\n for row in reader:\r\n if first_row:\r\n for num, _data_row in enumerate(row):\r\n if _data_row == data_row:\r\n data_row_found = True\r\n first_row = False\r\n data_row_int = num\r\n else:\r\n if data_row_found:\r\n for num, bin_range in enumerate(_histogramm_data['bin_range']):\r\n if float(row[data_row_int]) >= float(bin_range[0]):\r\n if float(row[data_row_int]) < float(bin_range[1]):\r\n _histogramm_data['values'][num] += 1\r\n _histogramm_data['qty'] += 1\r\n pass\r\n if messdaten_last:\r\n with open(frappe.get_site_path(messdaten_last.strip('/')), 'r') as f:\r\n reader = csv.reader(f, dialect='excel', delimiter='\\t')\r\n first_row = True\r\n data_row_found = False\r\n data_row_int = 0\r\n for row in reader:\r\n if first_row:\r\n for num, _data_row in enumerate(row):\r\n if _data_row == data_row:\r\n data_row_found = True\r\n first_row = False\r\n data_row_int = num\r\n else:\r\n if data_row_found:\r\n for num, bin_range in enumerate(_histogramm_data['bin_range']):\r\n if float(row[data_row_int]) >= float(bin_range[0]):\r\n if float(row[data_row_int]) < float(bin_range[1]):\r\n _histogramm_data['values'][num] += 1\r\n _histogramm_data['qty'] += 1\r\n pass\r\n if _histogramm_data['qty'] > max_anzahl:\r\n max_anzahl = _histogramm_data['qty']\r\n histogramm_data.append(_histogramm_data)\r\n\r\n histogramm_uri = [] \r\n for data in histogramm_data:\r\n params = {\r\n 'x[0]': ','.join(map(str, data['bins'])),\r\n 'y[0]': ','.join(map(str, data['values'])),\r\n 'title': data['title'],\r\n 'xlabel': data['x_title'],\r\n 'ylabel': data['y_title']\r\n }\r\n histogramm_uri.append(urllib.parse.urlencode(params))\r\n\r\n frappe.db.sql(\"UPDATE tabBatch SET histogramm_daten = %(histogramm_daten)s, histogramm_anz_gemessene = %(histogramm_anz_gemessene)s WHERE name = %(name)s\",\r\n {\"histogramm_daten\": json.dumps(histogramm_uri), \"histogramm_anz_gemessene\": max_anzahl, \"name\": batch}, as_list=True)\r\n return histogramm_uri\r\n\r\n# für Parsen von Histogrammdaten in Jinja\r\n@frappe.whitelist()\r\ndef json_loads(data):\r\n return json.loads(data)\r\n\r\n# Prüfen auf Existenz eines Templates in Jinja\r\n@frappe.whitelist()\r\ndef template_exists(path):\r\n if not path.startswith('templates/'):\r\n return False\r\n full_path = os.path.join(frappe.get_app_path('senstech'), path)\r\n return os.path.exists(full_path)\r\n\r\n@frappe.whitelist()\r\ndef print_multiple_label_pdf(label_reference, contents):\r\n label = frappe.get_doc(\"Label Printer\", label_reference)\r\n pdf_fnames = []\r\n if isinstance(contents, six.string_types):\r\n contents = json.loads(contents)\r\n \r\n #create single label pdf for each item batch based on verpackungseinheit\r\n for content in contents:\r\n item = frappe.get_doc(\"Item\", content[0])\r\n if item.verpackungseinheit > 0:\r\n loops = int(content[1] / item.verpackungseinheit)\r\n loop_qty = item.verpackungseinheit\r\n item_code = content[0]\r\n if item.artikelcode_kunde:\r\n item_code = item.artikelcode_kunde\r\n for i in range(loops):\r\n _content = \"\"\"\r\n
\r\n Artikel: {item_code}
\r\n Produktionscharge: {batch}
\r\n Menge: {qty} {stock_uom}\r\n
\r\n \"\"\".format(item_code=item_code, batch=content[2], qty=loop_qty, stock_uom=item.stock_uom)\r\n pdf_fnames.append(create_single_label_pdf(label, _content))\r\n if (loops * loop_qty) < content[1]:\r\n _content = \"\"\"\r\n
\r\n Artikel: {item_code}
\r\n Produktionscharge: {batch}
\r\n Menge: {qty} {stock_uom}\r\n
\r\n \"\"\".format(item_code=item_code, batch=content[2], qty=(content[1] - (loops * loop_qty)), stock_uom=item.stock_uom)\r\n pdf_fnames.append(create_single_label_pdf(label, _content))\r\n \r\n # merge all single label pdf to one pdf\r\n merged_pdf = merge_pdfs(pdf_fnames)\r\n \r\n # remove all single label pdfs\r\n cleanup(pdf_fnames)\r\n \r\n direct_print_pdf(merged_pdf)\r\n \r\n # and clean up the merged pdf as well\r\n if os.path.exists(merged_pdf):\r\n os.remove(merged_pdf)\r\n \r\n return\r\n\r\n\r\ndef create_single_label_pdf(label_printer, content):\r\n # create temporary file\r\n fname = os.path.join(\"/tmp\", \"frappe-pdf-{0}.pdf\".format(frappe.generate_hash()))\r\n\r\n options = { \r\n 'page-width': '{0}mm'.format(label_printer.width), \r\n 'page-height': '{0}mm'.format(label_printer.height), \r\n 'margin-top': '0mm',\r\n 'margin-bottom': '0mm',\r\n 'margin-left': '0mm',\r\n 'margin-right': '0mm' }\r\n\r\n html_content = \"\"\"\r\n \r\n \r\n \r\n \r\n \r\n \r\n {content}\r\n \r\n \r\n \"\"\".format(content=content)\r\n\r\n pdfkit.from_string(html_content, fname, options=options or {})\r\n\r\n return fname\r\n\r\ndef merge_pdfs(pdf_fnames):\r\n from PyPDF2 import PdfFileMerger\r\n\r\n pdfs = pdf_fnames\r\n merger = PdfFileMerger()\r\n\r\n for pdf in pdfs:\r\n merger.append(pdf)\r\n\r\n fname = \"merge-{0}.pdf\".format(frappe.generate_hash())\r\n fpath = frappe.get_site_path('private', 'files', fname)\r\n\r\n merger.write(fpath)\r\n merger.close()\r\n\r\n return fpath\r\n\r\ndef cleanup(pdf_fnames):\r\n for fname in pdf_fnames:\r\n if os.path.exists(fname):\r\n os.remove(fname)\r\n return\r\n\r\n@frappe.whitelist()\r\ndef unlinke_email_queue(communication):\r\n frappe.db.sql(\"\"\"UPDATE `tabEmail Queue` SET `communication` = '' WHERE `communication` = '{communication}'\"\"\".format(communication=communication), as_list=True)\r\n frappe.db.commit()\r\n\r\n@frappe.whitelist()\r\ndef add_freeze_pdf_to_dt(dt, dn, printformat, language=''):\r\n \r\n if not language:\r\n language = frappe.get_doc(dt, dn).language or 'de'\r\n\r\n filedata = attach_print(doctype=dt, name=dn, print_format=printformat, lang=language)\r\n fpath = frappe.get_site_path('private', 'files', filedata['fname'])\r\n\r\n with open(fpath, \"wb\") as w:\r\n w.write(filedata['fcontent'])\r\n\r\n file_record = {\r\n \"doctype\": \"File\",\r\n \"file_url\": '/private/files/{0}'.format(filedata['fname']),\r\n \"file_name\": filedata['fname'],\r\n \"attached_to_doctype\": dt,\r\n \"attached_to_name\": dn,\r\n \"folder\": 'Home/Attachments',\r\n \"file_size\": 0,\r\n \"is_private\": 1\r\n }\r\n if not frappe.db.exists(file_record):\r\n f = frappe.get_doc(file_record)\r\n f.flags.ignore_permissions = True\r\n f.insert()\r\n frappe.db.commit()\r\n\r\n return\r\n\r\n@frappe.whitelist()\r\ndef add_cancelled_watermark(dt, dn):\r\n\r\n fname = \"{0}.pdf\".format(dn)\r\n _fname = \"{0}_cancelled.pdf\".format(dn)\r\n input_file_fpath = str(frappe.get_site_path('private', 'files', fname))\r\n output_file_fpath = str(frappe.get_site_path('private', 'files', _fname))\r\n\r\n pdf_file = input_file_fpath\r\n merged = output_file_fpath\r\n watermark = frappe.get_site_path('public', 'pdf', 'abgebrochen.pdf')\r\n\r\n try:\r\n with open(pdf_file, \"rb\") as input_file, open(watermark, \"rb\") as watermark_file:\r\n input_pdf = PdfFileReader(input_file)\r\n watermark_pdf = PdfFileReader(watermark_file)\r\n watermark_page = watermark_pdf.getPage(0)\r\n\r\n output = PdfFileWriter()\r\n\r\n for i in range(input_pdf.getNumPages()):\r\n pdf_page = input_pdf.getPage(i)\r\n pdf_page.mergePage(watermark_page)\r\n output.addPage(pdf_page)\r\n\r\n with open(merged, \"wb\") as merged_file:\r\n output.write(merged_file)\r\n\r\n except FileNotFoundError as e:\r\n pass\r\n\r\n f = frappe.get_doc({\r\n \"doctype\": \"File\",\r\n \"file_url\": '/private/files/{0}'.format(_fname),\r\n \"file_name\": _fname,\r\n \"attached_to_doctype\": dt,\r\n \"attached_to_name\": dn,\r\n \"folder\": 'Home/Attachments',\r\n \"file_size\": 0,\r\n \"is_private\": 1\r\n })\r\n f.flags.ignore_permissions = True\r\n f.insert()\r\n frappe.db.commit()\r\n \r\n \r\n files = frappe.get_all('File', filters={'attached_to_doctype': dt, 'attached_to_name': dn}, fields=['name', 'file_url'])\r\n for file in files:\r\n if file.file_url == '/private/files/{0}'.format(fname):\r\n f_to_remove = frappe.get_doc('File', file.name)\r\n f_to_remove.delete()\r\n \r\n if os.path.exists(input_file_fpath):\r\n os.remove(input_file_fpath)\r\n \r\n return\r\n\r\n\r\n@frappe.whitelist()\r\ndef direct_print_pdf(file):\r\n\r\n label_printer_hostname = frappe.db.get_single_value('Senstech Einstellungen', 'label_printer_hostname');\r\n\r\n if not os.path.abspath(file).startswith(os.path.abspath(frappe.get_site_path())+os.sep):\r\n raise Exception('Only files within the site can be printed')\r\n return\r\n \r\n pdf = open(file, 'rb')\r\n pdfcontent = pdf.read()\r\n pdf.close()\r\n soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n soc.connect((label_printer_hostname, 9100))\r\n soc.sendall(pdfcontent)\r\n soc.close()\r\n \r\n return\r\n \r\n@frappe.whitelist()\r\ndef change_blanket_order_to_date(bo, date):\r\n frappe.db.sql(\"\"\"UPDATE `tabBlanket Order` SET `to_date` = '{date}' WHERE `name` = '{bo}'\"\"\".format(date=date, bo=bo), as_list=True)\r\n return\r\n","sub_path":"senstech/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":21633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"85797740","text":"import json\nimport urllib\n\nfrom collections import defaultdict\nfrom collections import OrderedDict\nfrom datetime import datetime\nfrom decimal import Decimal\n\nfrom storescraper.product import Product\nfrom storescraper.store import Store\nfrom storescraper.utils import html_to_markdown, session_with_proxy, \\\n check_ean13\nfrom storescraper import banner_sections as bs\n\n\nclass LiderGet(Store):\n @classmethod\n def categories(cls):\n return [\n 'Notebook',\n 'Monitor',\n 'Television',\n 'Tablet',\n 'Refrigerator',\n 'Printer',\n 'Oven',\n 'VacuumCleaner',\n 'WashingMachine',\n 'Cell',\n 'Camera',\n 'StereoSystem',\n 'OpticalDiskPlayer',\n 'ExternalStorageDrive',\n 'UsbFlashDrive',\n 'MemoryCard',\n 'VideoGameConsole',\n 'AllInOne',\n 'Projector',\n 'SpaceHeater',\n 'AirConditioner',\n 'Mouse',\n 'Keyboard',\n 'KeyboardMouseCombo',\n 'Headphones',\n 'Wearable',\n 'Stove',\n 'WaterHeater',\n ]\n\n @classmethod\n def discover_entries_for_category(cls, category, extra_args=None):\n category_paths = [\n ['Electrónica/TV y Video/Televisores', ['Television'],\n 'TV y Video > Televisores', 1],\n # ['DVDs_y_Blu-Ray', ['OpticalDiskPlayer'],\n # 'TV y Video > DVDs y Blu-Ray', 1],\n ['Electrónica/Equipos De Audio/Audífonos', ['Headphones'],\n 'Equipos de Audio > Audífonos', 1],\n ['Electrónica/Equipos De Audio/Parlantes Portables',\n ['StereoSystem'], 'Equipos de Audio > Parlantes portables', 1],\n ['Electrónica/Equipos De Audio/Equipos De Música y Karaokes',\n ['StereoSystem'], 'Equipos de Audio > Equipos de música', 1],\n ['Electrónica/Videojuegos/Consolas', ['VideoGameConsole'],\n 'Videojuegos > Consolas', 1],\n ['Telefonía/Celulares_y_Teléfonos/Smartphones',\n ['Cell'], 'Celulares y Teléfonos > Smartphones', 1],\n # ['Celulares_básicos', ['Cell'],\n # 'Celulares y Teléfonos > Celulares básicos', 1],\n # ['Telefonía y fotografía/Wearables/Smartwatchs',\n # ['Wearable'], 'Celulares y Teléfonos > Smartwatch', 1],\n ['Computación/Almacenamiento/Tarjetas De Memoria', ['MemoryCard'],\n 'Almacenamiento > Tarjetas de memoria', 1],\n ['Computación/Computadores/Notebooks', ['Notebook'],\n 'Computación > Notebooks', 1],\n # ['Computación/Computadores/Convertibles', ['Notebook'],\n # 'Computación > Convertibles', 1],\n ['Computación/Computadores/Gamers', ['Notebook'],\n 'Computación > Convertibles', 1],\n ['Computación/Computadores/Monitores', 'Monitor',\n 'Computación > Monitores', 1],\n ['Computación/Computadores/All In One', ['AllInOne'],\n 'Computación > All in One', 1],\n ['Computación/Computadores/Tablets', ['Tablet'],\n 'Computación > Tablets', 1],\n ['Computación/Almacenamiento/Discos Duros',\n ['ExternalStorageDrive'], 'Almacenamiento > Discos duros', 1],\n ['Computación/Almacenamiento/Pendrives', ['UsbFlashDrive'],\n 'Almacenamiento > Pendrives', 1],\n ['Computación/Impresión/Impresoras y Multifuncionales',\n ['Printer'], 'Impresión > Impresoras y Multifuncionales', 1],\n ['Computación/Accesorios De Computación/Teclados y Mouse',\n ['Mouse', 'Keyboard'],\n 'Accesorios de Computación > Teclados y Mouse', 0.5],\n # ['Computación/Accesorios De Computación/Accesorios Gamers',\n # ['Mouse', 'Keyboard'],\n # 'Accesorios de Computación > Accesorios Gamers', 0.5],\n ['Electrohogar/Lavado y Secado/Lavadoras Superiores',\n ['WashingMachine'], 'Lavado y Secado > Lavadoras superiores', 1],\n # ['Lavadoras_frontales', ['WashingMachine'],\n # 'Lavado y Secado > Lavadoras frontales', 1],\n ['Electrohogar/Lavado y Secado/Lavadoras - Secadoras',\n ['WashingMachine'], 'Lavado y Secado > Lavadoras - secadoras', 1],\n ['Electrohogar/Lavado y Secado/Secadoras', ['WashingMachine'],\n 'Lavado y Secado > Secadoras', 1],\n ['Electrohogar/Refrigeración', ['Refrigerator'],\n 'Refrigeración', 1],\n ['Electrohogar/Climatización/Aire Acondicionado',\n ['AirConditioner'], 'Ventilación > Aire acondicionado', 1],\n ['Electrohogar/Cocina/Encimeras', ['Stove'],\n 'Cocina > Encimeras', 1],\n ['Electrohogar/Cocina/Cocinas A Gas', ['Stove'],\n 'Cocinas a Gas > Cocina', 1],\n ['Electrohogar/Cocina/Horno Empotrable', ['Oven'],\n 'Cocina > Horno Empotrable', 1],\n ['Electrohogar/Electrodomésticos/Hornos Eléctricos', ['Oven'],\n '-NO-TITLE- > Hornos eléctricos', 1],\n ['Electrohogar/Electrodomésticos/Microondas', ['Oven'],\n '-NO-TITLE- > Microondas', 1],\n ['Electrohogar/Cocina/Calefont', ['WaterHeater'],\n 'Calefacción > Calefont', 1],\n ['Electrohogar/Climatización/Estufas Eléctricas', ['SpaceHeater'],\n 'Calefacción > Estufas Eléctricas', 1],\n ['Electrohogar/Electrodomésticos/Aspiradoras y Limpieza',\n ['VacuumCleaner'],\n 'Electrodomésticos > Aspiradoras y Limpieza', 1],\n ]\n\n session = session_with_proxy(extra_args)\n product_entries = defaultdict(lambda: [])\n\n for e in category_paths:\n category_id, local_categories, section_name, category_weight = e\n\n if category not in local_categories:\n continue\n\n query_url = 'https://529cv9h7mw-dsn.algolia.net/1/indexes/*/' \\\n 'queries?x-algolia-application-id=529CV9H7MW&x-' \\\n 'algolia-api-key=c6ab9bc3e19c260e6bad42abe143d5f4'\n\n query_params = {\n \"requests\": [\n {\n \"indexName\": \"campaigns_production\",\n \"params\": \"hitsPerPage=1000&facetFilters=%5B%22\"\n \"categorias%3A{}%22%5D\".format(\n urllib.parse.quote(\n category_id.replace('_', ' ')))\n }\n ]\n }\n\n response = session.post(query_url, json.dumps(query_params))\n data = json.loads(response.text)\n\n if not data['results'][0]['hits']:\n raise Exception('Empty category: ' + category_id)\n\n for idx, entry in enumerate(data['results'][0]['hits']):\n product_url = 'https://www.lider.cl/product/sku/{}'\\\n .format(entry['sku'])\n product_entries[product_url].append({\n 'category_weight': category_weight,\n 'section_name': section_name,\n 'value': idx + 1\n })\n\n return product_entries\n\n @classmethod\n def discover_urls_for_keyword(cls, keyword, threshold, extra_args=None):\n session = session_with_proxy(extra_args)\n product_urls = []\n\n query_url = 'https://529cv9h7mw-dsn.algolia.net/1/indexes/*/' \\\n 'queries?x-algolia-application-id=529CV9H7MW&x-' \\\n 'algolia-api-key=c6ab9bc3e19c260e6bad42abe143d5f4'\n\n query_params = {\n \"requests\": [{\n \"indexName\": \"campaigns_production\",\n \"params\": \"query={}&hitsPerPage=1000\"\n .format(keyword)}]}\n\n response = session.post(query_url, json.dumps(query_params))\n data = json.loads(response.text)\n\n if not data['results'][0]['hits']:\n return []\n\n for entry in data['results'][0]['hits']:\n product_url = 'https://www.lider.cl/product/sku/{}' \\\n .format(entry['sku'])\n product_urls.append(product_url)\n\n if len(product_urls) == threshold:\n return product_urls\n\n return product_urls\n\n @classmethod\n def products_for_url(cls, url, category=None, extra_args=None):\n print(url)\n session = session_with_proxy(extra_args)\n sku_id = url.split('/')[-1]\n\n query_url = 'https://buysmart-bff-production.lider.cl/buysmart-bff/' \\\n 'products/{}?appId=BuySmart'.format(sku_id)\n\n response = session.get(query_url)\n\n if response.status_code in [500]:\n return []\n\n entry = json.loads(response.text)\n\n name = '{} {}'.format(entry['brand'], entry['displayName'])\n ean = entry['gtin13']\n\n if not check_ean13(ean):\n ean = None\n\n sku = str(entry['sku'])\n stock = -1 if entry['available'] else 0\n normal_price = Decimal(entry['price']['BasePriceSales'])\n offer_price_container = entry['price']['BasePriceTLMC']\n\n if offer_price_container:\n offer_price = Decimal(offer_price_container)\n if not offer_price:\n offer_price = normal_price\n else:\n offer_price = normal_price\n\n specs = OrderedDict()\n for spec in entry.get('filters', []):\n specs.update(spec)\n\n part_number = specs.get('Modelo')\n if part_number:\n part_number = part_number[:49]\n\n description = None\n if 'longDescription' in entry:\n description = entry['longDescription']\n\n if description:\n description = html_to_markdown(description)\n\n picture_urls = ['https://images.lider.cl/wmtcl?source=url'\n '[file:/productos/{}{}]&sink'.format(sku, img)\n for img in entry['imagesAvailables']]\n\n return [Product(\n name,\n cls.__name__,\n category,\n url,\n url,\n sku,\n stock,\n normal_price,\n offer_price,\n 'CLP',\n sku=sku,\n ean=ean,\n part_number=part_number,\n picture_urls=picture_urls,\n description=description\n )]\n\n @classmethod\n def banners(cls, extra_args=None):\n base_url = 'https://buysmartstatic.lider.cl/' \\\n 'landing/json/banners.json?ts={}'\n # base_url = 'https://productionbuysmart.blob.core.windows.net/' \\\n # 'landing/json/banners.json?ts={}'\n\n destination_url_base = 'https://www.lider.cl{}'\n image_url_base = 'https://buysmartstatic.lider.cl/' \\\n 'landing/banners/{}'\n\n session = session_with_proxy(extra_args)\n banners = []\n\n url = base_url.format(datetime.now().timestamp())\n response = session.get(url)\n\n banners_json = json.loads(response.text)\n sliders = banners_json['Slider']\n\n index = 0\n\n for slider in sliders:\n if not slider['mobile']:\n destination_urls = [destination_url_base.format(slider['url'])]\n picture_url = image_url_base.format(slider['image'])\n\n banners.append({\n 'url': destination_url_base.format(''),\n 'picture_url': picture_url,\n 'destination_urls': destination_urls,\n 'key': picture_url,\n 'position': index + 1,\n 'section': bs.HOME,\n 'subsection': 'Home',\n 'type': bs.SUBSECTION_TYPE_HOME\n })\n\n index += 1\n\n return banners\n","sub_path":"storescraper/stores/lider_get.py","file_name":"lider_get.py","file_ext":"py","file_size_in_byte":11988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"578583868","text":"import os\nfrom flask import Flask, render_template, redirect, request, url_for, flash\nfrom flask_pymongo import PyMongo\nfrom bson.objectid import ObjectId\nif os.path.exists(\"env.py\"):\n import env\n\n\napp = Flask(__name__)\n\napp.config[\"MONGO_URI\"] = os.getenv(\"MONGO_URI\")\nDBS_NAME = \"ademre\"\nCOLLECTION_NAME = \"words\"\n\nmongo = PyMongo(app)\nWORDS = mongo.db.words.find()\nWORDS_LIST = list(WORDS)\nCATEGORY = mongo.db.category.find()\nCAT_LIST = list(CATEGORY)\n\n@app.route('/')\n@app.route('/index')\ndef index():\n return render_template(\"index.html\")\n\n\n@app.route('/admin')\ndef admin():\n return render_template(\"admin.html\")\n\n@app.route('/all_words')\ndef all_words():\n words = mongo.db.words.find()\n return render_template(\"all_words.html\", words=words)\n\n\n@app.route('/add_word')\ndef add_word():\n return render_template(\"add_word.html\", words=WORDS)\n\n\n@app.route('/insert_word', methods=['POST'])\ndef insert_word():\n words = mongo.db.words\n words.insert_one(request.form.to_dict())\n return redirect(url_for('all_words'))\n\n\n@app.route('/edit_word/')\ndef edit_word(word_id):\n the_word = mongo.db.words.find_one({'_id': ObjectId(word_id)}) \n return render_template(\"edit_word.html\", word=the_word)\n\n\n@app.route('/update_word/', methods=['POST'])\ndef update_word(word_id):\n words = mongo.db.words\n words.update({'_id': ObjectId(word_id)}, \n {\n 'eng': request.form.get('eng'), \n 'gesture': request.form.get('gesture'),\n 'name': request.form.get('name'),\n 'more_info': request.form.get('more_info')\n })\n \n return redirect(url_for('all_words'))\n\n\n@app.route('/delete_word/')\ndef delete_word(word_id):\n the_word = mongo.db.words.find_one({'_id': ObjectId(word_id)}) \n return render_template(\"delete_word.html\", word=the_word)\n\n\n@app.route('/remove_word/', methods=['POST', 'GET'])\ndef remove_word(word_id):\n mongo.db.words.remove({'_id': ObjectId(word_id)})\n return redirect(url_for('all_words'))\n\n\n@app.route('/contact')\ndef contact():\n return render_template(\"contact.html\")\n\n\nif __name__ == '__main__':\n app.run(host=os.environ.get('IP'),\n port=int(os.environ.get('PORT')),\n debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"628253910","text":"#!/usr/bin/env python3\n\nimport rospy\nfrom hebi_motor.msg import custom_msg # from import \n\ndef publisher():\n\n pub = rospy.Publisher('move_real_hebi', custom_msg, queue_size=10) # topic name and message type\n rospy.init_node('hebi_publisher', anonymous=True) # initialize node\n rate = rospy.Rate(5) # rate in [Hz] at which messages are published\n\n msg_to_publish = custom_msg() # The msg_to_publish will contain the desired joint angle in [rad]\n\n while not rospy.is_shutdown():\n # Desired joint angle\n theta = input('Enter desired joint value in radiants: ')\n\n msg_to_publish.data = theta # 'data' is the name of a desired float64 value\n\n pub.publish(msg_to_publish) # what this node is going to publish\n\n rospy.loginfo(theta) # to print the published message in the terminal\n\n rate.sleep()\n\n# Call the publisher function:\n\nif __name__ == '__main__':\n publisher()\n","sub_path":"catkin_ws/build/hebi_motor/catkin_generated/installspace/hebi_pub.py","file_name":"hebi_pub.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"621471649","text":"# lazy, use: python manage.py shell < scripts/populate_database.py\n\nfrom apps.workout_tracker.models import * # noqa\n\n# Delete potential old data\nExercise.objects.all().delete()\nExerciseType.objects.all().delete()\nWorkout.objects.all().delete()\nWeek.objects.all().delete()\nProgram.objects.all().delete()\n\nprogram = Program(name='Lvysaur 4-4-8 for beginners')\nprogram.save()\n\nweeks = dict(\n a=Week(name='Week A', program_id=program.id, position=0),\n b=Week(name='Week B', program_id=program.id, position=1)\n)\n\n_ = [o.save() for _, o in weeks.items()]\n\nexercise_types = dict(\n bench=ExerciseType(name='Bench press', weight_progression=5),\n squat=ExerciseType(name='Squat', weight_progression=7.5),\n dl=ExerciseType(name='Deadlift', weight_progression=7.5),\n row=ExerciseType(name='Barbell row', weight_progression=7.5),\n ohp=ExerciseType(name='Overhead press', weight_progression=2.5),\n chinup=ExerciseType(name='Chinup', weight_progression=0)\n)\n\n\n_ = [o.save() for _, o in exercise_types.items()]\n\nworkouts_week_a = dict(\n day_1=Workout(week_id=weeks['a'].id, name='Day 1', position=0),\n day_2=Workout(week_id=weeks['a'].id, name='Day 2', position=1),\n day_3=Workout(week_id=weeks['a'].id, name='Day 3', position=2),\n)\n\nworkouts_week_b = dict(\n day_1=Workout(week_id=weeks['b'].id, name='Day 1', position=0),\n day_2=Workout(week_id=weeks['b'].id, name='Day 2', position=1),\n day_3=Workout(week_id=weeks['b'].id, name='Day 3', position=2),\n)\n\nwhatever = {'a': workouts_week_a, 'b': workouts_week_b}\n\n_ = [o.save() for _, o in workouts_week_a.items()]\n_ = [o.save() for _, o in workouts_week_b.items()]\n\n\nbla = {\n 'a': {\n 'day_1': [\n ['bench', 4, 4],\n ['squat', 4, 8],\n ['ohp', 4, 8],\n ['chinup', 4, 8],\n ],\n 'day_2': [\n ['bench', 4, 8],\n ['dl', 4, 4],\n ['ohp', 4, 4],\n ['row', 4, 8],\n ],\n 'day_3': [\n ['bench', 3, 4],\n ['squat', 3, 4],\n ['ohp', 4, 8],\n ['row', 4, 4],\n ]\n },\n 'b': {\n 'day_1': [\n ['bench', 4, 8],\n ['dl', 4, 8],\n ['ohp', 4, 4],\n ['row', 4, 4],\n ],\n 'day_2': [\n ['bench', 4, 4],\n ['squat', 4, 8],\n ['ohp', 4, 8],\n ['chinup', 4, 8],\n ],\n 'day_3': [\n ['bench', 4, 8],\n ['dl', 3, 4],\n ['ohp', 3, 4],\n ['row', 4, 8],\n ]\n }\n}\n\n\nfor week, days in sorted(bla.items(), key=lambda x: x[0]):\n week_obj = weeks[week]\n\n for day, exercise_lists in sorted(days.items(), key=lambda x: x[0]):\n workout_obj = whatever[week][day]\n\n i = 0\n\n for exercise_list in exercise_lists:\n exercise_name, sets, reps = exercise_list\n exercise_type_obj = exercise_types[exercise_name]\n\n kwargs = {\n 'workout_id': workout_obj.id,\n 'exercise_type_id': exercise_type_obj.id,\n 'weight_multiplier': 1,\n 'position': i\n }\n\n if reps == 8:\n kwargs['weight_multiplier'] = 0.9\n\n Exercise(**kwargs, sets=sets, reps=reps).save()\n\n if sets == 3:\n i += 1\n kwargs['is_amrap'] = True\n kwargs['position'] = i\n Exercise(**kwargs).save()\n\n i += 1\n","sub_path":"scripts/populate_database.py","file_name":"populate_database.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"90701484","text":"from instagram_private_api import (\n Client,\n ClientCookieExpiredError,\n ClientLoginRequiredError,\n ClientError,\n ClientLoginError\n)\nfrom colorlog import ColoredFormatter\nimport logging\nimport os\nimport json\n\n\nclass LoggerAdapter(logging.LoggerAdapter):\n def __init__(self, logger, prefix):\n super(LoggerAdapter, self).__init__(logger, {})\n self.prefix = prefix\n\n def process(self, msg, kwargs):\n return '[%s] %s' % (self.prefix, msg), kwargs\n\nClient.login = lambda self: None\n\nclass API(Client):\n def __init__(self,**kwargs):\n super().__init__(**kwargs)\n\n # Setup logging\n self.logger = logging.getLogger(kwargs.get('username',''))\n\n # fh = HTMLFileHandler(title=self._id, file=logs_file, mode='w')\n # fh.setLevel(logging.INFO)\n # fh.setFormatter(file_formatter())\n # self.logger.addHandler(fh)\n if not len(self.logger.handlers):\n ch = logging.StreamHandler()\n ch.setLevel(get_logging_level())\n ch.setFormatter(colred_formatter())\n self.logger.addHandler(ch)\n\n self.logger.setLevel(logging.DEBUG)\n self.logger = LoggerAdapter(self.logger, kwargs['username'])\n\n def login(self):\n return\n\n def do_login(self):\n \"\"\"Login.\"\"\"\n\n prelogin_params = self._call_api(\n 'si/fetch_headers/',\n params='',\n query={'challenge_type': 'signup', 'guid': self.generate_uuid(True)},\n return_response=True)\n\n if not self.csrftoken:\n raise ClientError(\n 'Unable to get csrf from prelogin.',\n error_response=self._read_response(prelogin_params))\n\n login_params = {\n 'device_id': self.device_id,\n 'guid': self.uuid,\n 'adid': self.ad_id,\n 'phone_id': self.phone_id,\n '_csrftoken': self.csrftoken,\n 'username': self.username,\n 'password': self.password,\n 'login_attempt_count': '0',\n }\n\n login_response = self._call_api(\n 'accounts/login/', params=login_params, return_response=True)\n\n if not self.csrftoken:\n raise ClientError(\n 'Unable to get csrf from login.',\n error_response=self._read_response(login_response))\n\n login_json = json.loads(self._read_response(login_response))\n\n if not login_json.get('logged_in_user', {}).get('pk'):\n raise ClientLoginError('Unable to login.')\n\n if self.on_login:\n on_login_callback = self.on_login\n on_login_callback(self)\n\n def send_direct_item(self, users, **options):\n data = {\n 'client_context': self.generate_uuid(),\n 'action': 'send_item'\n }\n\n users = [str(x) for x in users]\n\n text = options.get('text', '')\n\n if options.get('urls'):\n data['link_text'] = text\n data['link_urls'] = json.dumps(options.get('urls'))\n item_type = 'link'\n\n elif options.get('media_id',) and options.get('media_type'):\n data['text'] = text\n data['media_type'] = options.get('media_type', 'photo')\n data['media_id'] = options.get('media_id', '')\n item_type = 'media_share'\n\n elif options.get('hashtag',):\n data['text'] = text\n data['hashtag'] = options.get('hashtag', '')\n item_type = 'hashtag'\n\n elif options.get('profile_user_id'):\n data['text'] = text\n data['profile_user_id'] = options.get('profile_user_id')\n item_type = 'profile'\n\n else:\n data['text'] = text\n item_type = 'text'\n\n url = 'direct_v2/threads/broadcast/{}/'.format(item_type)\n\n data['recipient_users'] = f\"[[{','.join(users)}]]\"\n if options.get('thread_id'):\n data['thread_ids'] = f\"[{options.get('thread_id')}]\"\n data.update(self.authenticated_params)\n return self._call_api(url, params=data, unsigned=True)\n\n\n\n def agree_consent1(self):\n params = {\n '_csrftoken': self.csrftoken,\n '_uid': self.authenticated_user_id,\n '_uuid': self.uuid\n }\n return self._call_api('consent/existing_user_flow/', params=params, )# unsigned=True)\n\n\n def agree_consent2(self):\n params = {\n 'current_screen_key': 'qp_intro',\n 'updates': json.dumps({'existing_user_intro_state': '2'}),\n '_csrftoken': self.csrftoken,\n '_uid': self.authenticated_user_id,\n '_uuid': self.uuid\n }\n return self._call_api('consent/existing_user_flow/', params=params, )# unsigned=True)\n\n\n def agree_consent3(self):\n params = {\n 'current_screen_key': 'tos_and_two_age_button',\n 'updates': json.dumps({'age_consent_state': '2', 'tos_data_policy_consent_state': '2'}),\n '_csrftoken': self.csrftoken,\n '_uid': self.authenticated_user_id,\n '_uuid': self.uuid\n }\n return self._call_api('consent/existing_user_flow/', params=params,)# unsigned=True)\n\n\n\n\ndef get_logging_level():\n levels = dict(\n DEBUG=logging.DEBUG,\n INFO=logging.INFO,\n WARN=logging.WARN,\n ERROR=logging.ERROR,\n CRITICAL=logging.CRITICAL,\n )\n\n return os.environ['LOGGING_LEVEL'] \\\n if 'LOGGING_LEVEL' in os.environ and os.environ['LOGGING_LEVEL'] in levels \\\n else logging.DEBUG if 'DEBUG' in os.environ else 'INFO'\n\ndef colred_formatter():\n format = '%(asctime)s | %(levelname)-8s | %(message)s'\n cformat = '%(log_color)s' + format\n date_format = '%Y-%m-%d %H:%M'\n return ColoredFormatter(cformat, date_format,\n log_colors={'DEBUG': 'reset', 'INFO': 'green',\n 'WARNING': 'yellow', 'ERROR': 'red',\n 'CRITICAL': 'red'})\n","sub_path":"src/instabotnet/api/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":6039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"371478785","text":"import pandas as pd\r\nimport numpy as np\r\nimport xgboost as xgb\r\nfrom sklearn import svm\r\nimport sklearn.preprocessing as ppc\r\nfrom sklearn.ensemble import IsolationForest\r\nfrom sklearn.covariance import EllipticEnvelope\r\n\r\ndef get_merge_data(data1,data2):\r\n\r\n return pd.merge(data1, data2[['shop_id', 'mall_id']], how='left', on='shop_id')\r\n\r\ndef get_wifi_infos(x):\r\n wifi = x.split(';')\r\n info = list(map(lambda x: x.split('|'),wifi))\r\n wifi_info = {}\r\n for i in range(len(info)):\r\n wifi_info[info[i][0]] = int(info[i][1])\r\n return wifi_info\r\n\r\ndef get_test_feature(data,test_data1,columns):\r\n columns = ['row_id', 'user_id', 'mall_id', 'time_stamp', 'longitude', 'latitude',\r\n 'wifi_infos']+ columns\r\n test_data = pd.DataFrame(columns=columns)\r\n test_data[['row_id', 'user_id', 'mall_id', 'time_stamp', 'longitude', 'latitude',\r\n 'wifi_infos']] = test_data1[['row_id', 'user_id', 'mall_id', 'time_stamp', 'longitude', 'latitude',\r\n 'wifi_infos']]\r\n\r\n test_data['wifi_id_signal'] = test_data['wifi_infos'].map(lambda x: get_wifi_infos(x))\r\n d = []\r\n for i, row in test_data.iterrows():\r\n # print(i)\r\n for j in test_data['wifi_id_signal'][i]:\r\n if j in columns:\r\n # print('yes')\r\n row[j] = test_data['wifi_id_signal'][i][j]\r\n else:\r\n continue\r\n d.append(row)\r\n test_data = pd.DataFrame(d)\r\n\r\n return test_data\r\n\r\n\r\ndef predict_AB(train,test,result,num,sshop):\r\n\r\n filter_feature_train = ['user_id', 'time_stamp', 'mall_id', 'wifi_infos','wifi_id_signal','shop_id']\r\n filter_feature_test = ['user_id', 'time_stamp', 'mall_id', 'wifi_infos','wifi_id_signal']\r\n train = train.drop(filter_feature_train,axis=1)\r\n test = test.drop(filter_feature_test,axis=1)\r\n train = train.fillna(-999)\r\n test = test.fillna(-999)\r\n test = test[list(train.columns)].join(test['row_id'])\r\n\r\n # # 存储矩阵\r\n # train.to_csv(r'D:\\刘帅专用\\XGBoost天池\\mall_data_train&test\\train_%d.csv'% num,index=None)\r\n # test.to_csv(r'D:\\刘帅专用\\XGBoost天池\\mall_data_train&test\\test_%d.csv' % num, index=None)\r\n\r\n model = EllipticEnvelope()\r\n model.fit(train)\r\n test['label'] = model.predict(test.drop(['row_id'],axis=1))\r\n\r\n # 标签转化回去\r\n test['shop_id'] = None\r\n print('***************************',len(test))\r\n print(len(test[test['label']==1]))\r\n\r\n print('***************************')\r\n test = test[test['label']==1]\r\n\r\n test['shop_id'][test['label']==1] = sshop #todo\r\n r = test[['row_id', 'shop_id']]\r\n result = pd.concat([result, r])\r\n result['row_id'] = result['row_id'].astype('int')\r\n\r\n return result\r\n\r\n\r\ndef mall_traing(data,shop_list,test_data):\r\n result = pd.DataFrame()\r\n num=0\r\n for shop in shop_list:\r\n num=num+1\r\n #\r\n # if num==2:\r\n # break\r\n print(num)\r\n shop_data = data[data['shop_id'] == shop].reset_index(drop=True)\r\n print(len(shop_data))\r\n shop_data['wifi_id_signal'] = shop_data['wifi_infos'].map(lambda x: get_wifi_infos(x))\r\n d = []\r\n wifi_id_fre = {}#统计wifi频数\r\n columns = []\r\n for i, row in shop_data.iterrows():\r\n # print(i)\r\n for j in shop_data['wifi_id_signal'][i]:\r\n row[j] = shop_data['wifi_id_signal'][i][j]\r\n if j not in columns:\r\n columns.append(j)\r\n # wifi_id_fre[j] = wifi_id_fre.get(j, 0) + 1\r\n d.append(row)\r\n shop_data = pd.DataFrame(d)\r\n\r\n test_data = get_test_feature(shop_data,test_data,columns)\r\n\r\n result = predict_AB(shop_data,test_data,result,num,shop)\r\n # print('result')\r\n # print(result)\r\n # result.to_csv('sub.csv', index=False)\r\n\r\n\r\nif __name__ == '__main__':\r\n shop = pd.read_csv(r'D:\\刘帅专用\\XGBoost天池\\训练数据-ccf_first_round_shop_info.csv')\r\n user = pd.read_csv(r'D:\\刘帅专用\\XGBoost天池\\训练数据-ccf_first_round_user_shop_behavior.csv')\r\n test = pd.read_csv(r'D:\\刘帅专用\\XGBoost天池\\AB榜测试集-evaluation_public.csv')\r\n\r\n data = get_merge_data(user,shop)\r\n data_user = data[data['mall_id']=='m_7800']\r\n data_shop = shop[shop['mall_id']=='m_7800']\r\n data_test = test[test['mall_id']=='m_7800']\r\n\r\n shop_id = list(data_shop['shop_id'].values)\r\n mall_traing(data_user,shop_id,data_test)\r\n # np.save(r'D:\\刘帅专用\\XGBoost天池\\二分类\\shop_id',shop_id)","sub_path":"阿里天池_商铺定位/二分类/1.oneclass.py","file_name":"1.oneclass.py","file_ext":"py","file_size_in_byte":4541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"415154590","text":"#MOD: takes input and reads entry based on input\n\ndef GetDictionary(word, lines):\n i = lines.index(word) + 1\n while True:\n if lines[i] == '*******':\n break\n else:\n i += 1\n return lines[lines.index(word) + 1:i]\n\ndef ReadDictionary():\n with open('/home/pi/Desktop/ConlangDatabase.txt', 'r') as f:\n lines = [line.replace('\\n', '') for line in f.readlines()]\n\n while True:\n word = input('word?: ')\n print('\\n'.join(GetDictionary(word, lines)))\n print(' ')\n break\n ","sub_path":"Old/1.0/language-project-terminal/ModReadDictionary.py","file_name":"ModReadDictionary.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"346526801","text":"\"\"\"\nhttps://leetcode.com/problems/find-k-length-substrings-with-no-repeated-characters/\n\nSliding window to record the frequence of characters.\nTime complexity: O(NK)\n\"\"\"\nclass Solution:\n def numKLenSubstrNoRepeats(self, S: str, K: int) -> int:\n n = len(S)\n if n < K:\n return 0\n if K > 26:\n return 0\n count = 0\n for i in range(n-K+1):\n if len(S[i:i+K]) == len(set(S[i:i+K])):\n count += 1\n return count\n","sub_path":"1100_FindKLengthSubstringsWithNoRepeatedCharacters.py","file_name":"1100_FindKLengthSubstringsWithNoRepeatedCharacters.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"574470912","text":"\nimport torch\nimport torch.nn as nn\neps_l2_norm = 1e-10\n\nclass FRN(nn.Module):\n def __init__(self, num_features, eps=1e-6, is_bias=True, is_scale=True, is_eps_leanable=False):\n \"\"\"\n weight = gamma, bias = beta\n\n beta, gamma:\n Variables of shape [1, 1, 1, C]. if TensorFlow\n Variables of shape [1, C, 1, 1]. if PyTorch\n eps: A scalar constant or learnable variable.\n \"\"\"\n super(FRN, self).__init__()\n\n self.num_features = num_features\n self.init_eps = eps\n self.is_eps_leanable = is_eps_leanable\n self.is_bias = is_bias\n self.is_scale = is_scale\n\n\n self.weight = nn.parameter.Parameter(torch.Tensor(1, num_features, 1, 1), requires_grad=True)\n self.bias = nn.parameter.Parameter(torch.Tensor(1, num_features, 1, 1), requires_grad=True)\n if is_eps_leanable:\n self.eps = nn.parameter.Parameter(torch.Tensor(1), requires_grad=True)\n else:\n self.register_buffer('eps', torch.Tensor([eps]))\n self.reset_parameters()\n\n def reset_parameters(self):\n nn.init.ones_(self.weight)\n nn.init.zeros_(self.bias)\n if self.is_eps_leanable:\n nn.init.constant_(self.eps, self.init_eps)\n\n def extra_repr(self):\n return 'num_features={num_features}, eps={init_eps}'.format(**self.__dict__)\n\n def forward(self, x):\n \"\"\"\n 0, 1, 2, 3 -> (B, H, W, C) in TensorFlow\n 0, 1, 2, 3 -> (B, C, H, W) in PyTorch\n TensorFlow code\n nu2 = tf.reduce_mean(tf.square(x), axis=[1, 2], keepdims=True)\n x = x * tf.rsqrt(nu2 + tf.abs(eps))\n\n # This Code include TLU function max(y, tau)\n return tf.maximum(gamma * x + beta, tau)\n \"\"\"\n # Compute the mean norm of activations per channel.\n nu2 = x.pow(2).mean(dim=[2, 3], keepdim=True)\n\n # Perform FRN.\n x = x * torch.rsqrt(nu2 + self.eps.abs())\n\n # Scale and Bias\n if self.is_scale:\n x = self.weight * x\n if self.is_bias:\n x = x + self.bias\n return x\n\nclass TLU(nn.Module):\n def __init__(self, num_features):\n \"\"\"max(y, tau) = max(y - tau, 0) + tau = ReLU(y - tau) + tau\"\"\"\n super(TLU, self).__init__()\n self.num_features = num_features\n self.tau = nn.parameter.Parameter(torch.Tensor(1, num_features, 1, 1), requires_grad=True)\n self.reset_parameters()\n\n def reset_parameters(self):\n # nn.init.zeros_(self.tau)\n nn.init.constant_(self.tau, -1)\n\n def extra_repr(self):\n return 'num_features={num_features}'.format(**self.__dict__)\n\n def forward(self, x):\n return torch.max(x, self.tau)\n\nclass HyNet(nn.Module):\n \"\"\"\n HyNet model definition.\n The FRN and TLU layer are from the papaer\n `Filter Response Normalization Layer: Eliminating Batch Dependence in the Training of Deep Neural Networks`\n https://github.com/yukkyo/PyTorch-FilterResponseNormalizationLayer\n \"\"\"\n def __init__(self, is_bias=True, is_bias_FRN=True, dim_desc=128, drop_rate=0.3):\n super(HyNet, self).__init__()\n self.dim_desc = dim_desc\n self.drop_rate = drop_rate\n\n self.layer1 = nn.Sequential(\n FRN(1, is_bias=is_bias_FRN),\n TLU(1),\n nn.Conv2d(1, 32, kernel_size=3, padding=1, bias=is_bias),\n FRN(32, is_bias=is_bias_FRN),\n TLU(32),\n )\n\n self.layer2 = nn.Sequential(\n nn.Conv2d(32, 32, kernel_size=3, padding=1, bias=is_bias),\n FRN(32, is_bias=is_bias_FRN),\n TLU(32),\n )\n\n self.layer3 = nn.Sequential(\n nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=is_bias),\n FRN(64, is_bias=is_bias_FRN),\n TLU(64),\n )\n\n self.layer4 = nn.Sequential(\n nn.Conv2d(64, 64, kernel_size=3, padding=1, bias=is_bias),\n FRN(64, is_bias=is_bias_FRN),\n TLU(64),\n )\n self.layer5 = nn.Sequential(\n nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=is_bias),\n FRN(128, is_bias=is_bias_FRN),\n TLU(128),\n )\n\n self.layer6 = nn.Sequential(\n nn.Conv2d(128, 128, kernel_size=3, padding=1, bias=is_bias),\n FRN(128, is_bias=is_bias_FRN),\n TLU(128),\n )\n\n self.layer7 = nn.Sequential(\n nn.Dropout(self.drop_rate),\n nn.Conv2d(128, self.dim_desc, kernel_size=8, bias=False),\n nn.BatchNorm2d(self.dim_desc, affine=False)\n )\n\n self.desc_norm = nn.Sequential(\n nn.LocalResponseNorm(2 * self.dim_desc, alpha=2 * self.dim_desc, beta=0.5, k=0)\n )\n\n return\n\n def forward(self, x):\n for layer in [self.layer1, self.layer2, self.layer3, self.layer4, self.layer5, self.layer6, self.layer7]:\n x = layer(x)\n\n x = self.desc_norm(x + eps_l2_norm)\n x = x.view(x.size(0), -1)\n return x\n\n\n\n\n","sub_path":"cv/local_discriptor/hynet/pytorch/weights/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"223583519","text":"\"\"\"\nThis module contains unit tests of peer_departure().\n\"\"\"\n\nfrom typing import Iterator\nimport pytest\n\nfrom single_run import SingleRun\nfrom node import Peer\nfrom message import Order\nfrom scenario import Scenario\nfrom engine import Engine\nfrom performance import Performance\nfrom ..__init__ import (\n SCENARIO_SAMPLE,\n ENGINE_SAMPLE,\n PERFORMANCE_SAMPLE,\n create_a_test_order,\n create_a_test_peer,\n)\n\n\n@pytest.mark.parametrize(\n \"scenario, engine, performance\",\n [(SCENARIO_SAMPLE, ENGINE_SAMPLE, PERFORMANCE_SAMPLE)],\n)\ndef test_peer_departure__normal(\n scenario: Scenario, engine: Engine, performance: Performance\n) -> None:\n \"\"\"\n This tests peer_departure() in normal case.\n \"\"\"\n\n # Arrange.\n\n # create a single_run instance.\n single_run_instance = SingleRun(scenario, engine, performance)\n\n # create two peers. One is the peer that will depart, the other is its neighbor.\n single_run_instance.peer_arrival(\"normal\", {})\n single_run_instance.peer_arrival(\"normal\", {})\n\n iterator: Iterator[Peer] = iter(single_run_instance.peer_full_set)\n peer: Peer = next(iterator)\n neighbor: Peer = next(iterator)\n\n peer.add_neighbor(neighbor)\n neighbor.add_neighbor(peer)\n\n # Let the peer have one order in pending table and one in storage.\n order_store: Order = create_a_test_order(scenario)\n peer.receive_order_external(order_store)\n peer.store_orders()\n\n order_pending: Order = create_a_test_order(scenario)\n peer.receive_order_external(order_pending)\n\n # Act.\n single_run_instance.peer_departure(peer)\n\n # Assert.\n assert peer not in single_run_instance.peer_full_set\n assert peer not in single_run_instance.peer_type_set_mapping[\"normal\"]\n assert peer not in order_store.holders\n assert peer not in order_pending.hesitators\n assert peer not in neighbor.peer_neighbor_mapping\n\n\n@pytest.mark.parametrize(\n \"scenario, engine, performance\",\n [(SCENARIO_SAMPLE, ENGINE_SAMPLE, PERFORMANCE_SAMPLE)],\n)\ndef test_peer_departure__error(\n scenario: Scenario, engine: Engine, performance: Performance\n) -> None:\n \"\"\"\n This tests peer_departure() when the peer does not exist.\n \"\"\"\n\n # Arrange.\n # create a single_run instance.\n single_run_instance = SingleRun(scenario, engine, performance)\n # create a peer\n peer: Peer = create_a_test_peer(scenario, engine)[0]\n\n # Act and Assert.\n with pytest.raises(ValueError, match=\"No such peer to depart.\"):\n single_run_instance.peer_departure(peer)\n","sub_path":"test/single_and_multi_run/test_peer_departure.py","file_name":"test_peer_departure.py","file_ext":"py","file_size_in_byte":2531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"521735480","text":"import json\nimport re\n\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.http import JsonResponse, HttpResponse\nfrom django.shortcuts import redirect, render\nfrom django.template import RequestContext\nfrom django.views.decorators.csrf import ensure_csrf_cookie\n\nfrom parcel.models import LotQuantiles\nfrom shared import request\n\nfrom .contact import ContactForm\n\n\ndef get_lot_sizes():\n try:\n q = LotQuantiles.objects.all()[0]\n return {\n \"small\": round(q.small_lot * 43560),\n \"medium\": round(q.medium_lot * 43560)\n }\n except IndexError:\n return {\"small\": 5000, \"medium\": 10000}\n\n\nLOT_SIZES = None\n\n\ndef lot_sizes():\n global LOT_SIZES\n if not LOT_SIZES:\n LOT_SIZES = get_lot_sizes()\n return LOT_SIZES\n\n\ndef contact_us(request):\n if request.method == \"POST\":\n form = ContactForm(request.POST)\n if form.is_valid():\n form.send_email()\n return JsonResponse({\n \"title\": \"Email Sent\",\n \"text\": \"Thanks for your feedback!\"\n })\n else:\n return JsonResponse({\"errors\": form.errors}, status=400)\n else:\n return HttpResponse({\n \"bad request method\"\n }, status=405)\n\n\n@ensure_csrf_cookie\ndef index(request):\n return render(request, \"index.djhtml\", {\n \"google_key\": settings.GOOGLE_BROWSER_API_KEY,\n \"production\": settings.IS_PRODUCTION,\n \"lot_sizes\": lot_sizes(),\n \"preload_data\": json.dumps({})\n })\n","sub_path":"server/cornerwise/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"1795093","text":"\"\"\"\n\n\"\"\"\n# Importing the Necessary Modules\nimport sys\nsys.path.append(\"/home/coreys/pyTools/\") #siraf\nimport tiff_stacks_python as ts\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nsns.set_style(\"white\")\n\n# Setting noise and alpha parameters\nsig_vals = [np.sqrt(50.0), np.sqrt(50.0), np.sqrt(2500.0)]\nalpha_vals = [x*5e-13 for x in np.arange(0, 1e10, 1e3)]\nalpha_vals.remove(0)\nnum_views = 3\n\n###############################################################################\n# This section is loading images and computing the MTF and w values\n###############################################################################\nimg_folder = '/home/coreys/Estimation_Data/'\nfile_a = 'Reslice_of_PSF_TopA_VB_Ideal-1.tif'#'psfTop1LS.tif'\nfile_b = 'Reslice_of_PSF_TopB_VB_Ideal-1.tif'#'psfTop2LS.tif'\nfile_c = 'Reslice_of_PSF_BottomA_VB_Ideal-1.tif'#'psfBotLS.tif'\n\n# Importing the PFSs\nview_a = ts.read_stack(img_folder + file_a)\nview_b = ts.read_stack(img_folder + file_b)\nview_c = ts.read_stack(img_folder + file_c)\n\nfft_shape = view_a.size #512 * 512\n\n# scale\nview_a = view_a/view_a.max()\nview_b = view_b/view_b.max()\nview_c = view_c/view_c.max()\n\n#num_pix = fft_shape[0] * fft_shape[1]\n# Calculating the OTFs\notf_vals = [np.fft.fft(view_a.ravel(), n=fft_shape),\n np.fft.fft(view_b.ravel(), n=fft_shape),\n np.fft.fft(view_c.ravel(), n=fft_shape)]\n\nmtf_vals = []\nfor view in range(num_views):\n mtf_vals.append(np.absolute(otf_vals[view]) ** 2)\n###############################################################################\n# compute w_vals values (this is from derivative filter) this will need\n# to be different depending on if the imput is 2 or 3d\n###############################################################################\nif view_a.ndim == 2:\n lap = np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]], dtype=np.float64)\nelif view_a.ndim == 3:\n lap = np.array([[[0., 0., 0.], [0., 1, 0.], [0., 0., 0.]],\n [[0., 1, 0.], [1, -6, 1], [0., 1, 0.]],\n [[0., 0., 0.], [0., 1, 0.], [0., 0., 0.]]],\n dtype=np.float64)\n\nw_vals = (np.absolute(np.fft.fft(lap.ravel(), n=fft_shape)) ** 2)\n\n# # save computed values\n# np.save('/home/coreys/Estimation_Data/view_a_mtf.npy', mtf_vals[0])\n# np.save('/home/coreys/Estimation_Data/view_b_mtf.npy', mtf_vals[1])\n# np.save('/home/coreys/Estimation_Data/view_c_mtf.npy', mtf_vals[2])\n# np.save('/home/coreys/Estimation_Data/w_values.npy', w_vals)\n\n\n###############################################################################\n# This section is loading mtf of the images\n###############################################################################\n# mtf_vals = [] # comment out if not loading in values\n# for idx, view in enumerate(['a', 'b', 'c']):\n# mtf_vals.append(np.load(('/home/coreys/Estimation_Data/view_'+\n# view +'_mtf.npy')))\n\n# w_vals = np.load('/home/coreys/Estimation_Data/w_values.npy')\n\n# comupte lambda values\nlam_list = []\nfor view in range(num_views):\n lam_list.append(((1.0/sig_vals[view] ** 2)) * mtf_vals[view])\n\nlam_vals = lam_list[0] + lam_list[1] + lam_list[2]\nlam_vals2 = lam_list[0] + lam_list[1]\nlam_vals1 = lam_list[0]\n\ncrc3 = []\nvar3 = []\ncrc2 = []\nvar2 = []\ncrc3_d = []\nvar3_d = []\ncrc2_d = []\nvar2_d = []\ncrc1_d = []\nvar1_d = []\n\nfor alpha in alpha_vals:\n print(f'alpha is {alpha:.2E}')\n # crc3.append(np.mean(lam_vals/((lam_vals + alpha))))\n # var3.append(np.mean(lam_vals/((lam_vals + alpha)**2)))\n # crc2.append(np.mean(lam_vals2/((lam_vals2 + alpha))))\n # var2.append(np.mean(lam_vals2/((lam_vals2 + alpha)**2)))\n crc3_d.append(np.mean(lam_vals/((lam_vals + alpha * w_vals))))\n var3_d.append(np.mean(lam_vals/((lam_vals + alpha * w_vals) ** 2)))\n crc2_d.append(np.mean(lam_vals2/((lam_vals2 + alpha * w_vals))))\n var2_d.append(np.mean(lam_vals2/((lam_vals2 + alpha * w_vals) ** 2)))\n crc1_d.append(np.mean(lam_vals1/((lam_vals1 + alpha * w_vals))))\n var1_d.append(np.mean(lam_vals1/((lam_vals1 + alpha * w_vals) ** 2)))\n\nheaders = ['alpha', 'crc 3', 'var 3', 'crc 2', 'var 2', 'crc 1', 'var 1']\ndata = pd.DataFrame(np.column_stack([alpha_vals, crc3_d, var3_d,\n crc2_d, var2_d, crc1_d, var1_d]), columns=headers)\ndata.to_csv(f'noise_{sig_vals[0]:.1f}_'\n f'{sig_vals[2]:.1f}_and_resolution_3views_2D_slice.csv')\n# noise3 = np.sqrt(var3)\n# noise2 = np.sqrt(var2)\nnoise3_d = np.sqrt(var3_d)\nnoise2_d = np.sqrt(var2_d)\nnoise1_d = np.sqrt(var1_d)\n# xlimit = np.max(np.concatenate([noise2, noise3, noise2_d, noise3_d]))\n\nsns.set_context(\"poster\")\nfig, ax1 = plt.subplots(figsize=(9, 6))\n# fig, (ax1, ax2) = plt.subplots(figsize=(9, 6), nrows=1, ncols=2)\nax1.plot(noise3_d, crc3_d, c='k', ls=\"--\", label='3 views')\nax1.plot(noise2_d, crc2_d, c='r', ls=\":\", label='2 views')\n# ax1.plot(noise2_d, crc2_d, c='b', ls=\"-.\", label='1 view')\n# ax2.plot(noise3_d, crc3_d, c='k', ls=\"--\", label='3 views derivative')\n# ax2.plot(noise2_d, crc2_d, c='b', ls=\"-.\", label='2 views derivative')\nax1.set_xlabel('Noise')\nax1.set_ylabel('CRC')\nax1.set_ylim([0, 0.5])\nax1.set_xlim([0, 250])\nax1.legend(loc=4, fontsize='small')\n# ax2.set_yticks([])\n# # ax2.tick_params(axis='y', which='both', left=False, right=False)\n# ax2.set_xlabel('Noise')\n# # ax2.set_ylabel('Resolution')\n# #ax2.set_ylim([0, 0.2])\n# ax2.set_xlim([0, xlimit])\n# ax2.legend(loc=4, fontsize='small')\nfig.tight_layout()\n\nfig.savefig(f'three_view_2d_noise_{sig_vals[0]:.1f}_'\n f'{sig_vals[2]:.1f}_resolution_curves_slice.png',\n dpi=400)\n\nplt.close()\n","sub_path":"sim_noise_v_resolution.py","file_name":"sim_noise_v_resolution.py","file_ext":"py","file_size_in_byte":5627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"233694278","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport itertools \nimport pandas as pd\nimport tensorflow as tf\n\ntf.logging.set_verbosity(tf.logging.INFO) #gotta git all that infos\nCOLUMNS = [\"crim\", \"zn\", \"indus\", \"nox\", \"rm\", \"age\",\n \"dis\", \"tax\", \"ptratio\", \"medv\"] #this is all the data and answers\nFEATURES = [\"crim\", \"zn\", \"indus\", \"nox\", \"rm\",\n \"age\", \"dis\", \"tax\", \"ptratio\"] #This is all the features\nLABEL = \"medv\" #this is what should come out\n\ntraining_set = pd.read_csv(\"boston_train.csv\", skipinitialspace=True,skiprows=1, names=COLUMNS)#parses the CSV\ntest_set = pd.read_csv(\"boston_test.csv\", skipinitialspace = True, skiprows = 1, names = COLUMNS)#the initial row is the identifier, so remove that\nprediction_set = pd.read_csv(\"boston_predict.csv\", skipinitialspace = True, skiprows = 1, names = COLUMNS)\n\nfeature_cols = [tf.feature_column.numeric_column(k) for k in FEATURES] #this makes a special column for each feature, thats why its iterated, used for training\n\nregressor = tf.estimator.DNNRegressor(feature_columns = feature_cols, hidden_units=[10,10],model_dir = \"tmp/bostonModel\") #this makes the regressor instance, makes two hidden layers, and feature columns that has all the features\n\n\n\ndef get_input_fn(data_set, num_epochs=None,shuffle=True):\n return tf.estimator.inputs.pandas_input_fn(\n x=pd.DataFrame({k: data_set[k].values for k in FEATURES}),\n y = pd.Series(data_set[LABEL].values),\n num_epochs=num_epochs,\n shuffle=shuffle) \n'''ok what just happened here? well, we first set the first parameter to all of the features, one data set for each. We then set the second\narguement as the label data. returns a dictionary with paired features with target values\n'''\nregressor.train(input_fn=get_input_fn(training_set), steps = 5000)\n\nev = regressor.evaluate(input_fn=get_input_fn(test_set, num_epochs=1, shuffle=False))\n\nloss_score = ev[\"loss\"]\nprint(\"Loss: {0:f}\".format(loss_score))\n\n\ny = regressor.predict(\n input_fn=get_input_fn(prediction_set, num_epochs=1, shuffle=False))\npredictions = list(p[\"predictions\"] for p in itertools.islice(y,6))\nprint(\"Predictions: {0}\".format(str(predictions)))\n\n","sub_path":"Train.py","file_name":"Train.py","file_ext":"py","file_size_in_byte":2244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"137522703","text":"import os,glob,shutil,sys\n\ntargets='working_dir'\nif os.path.exists(targets):\n\tos.chdir(targets)\nelse:\n\tsys.exit('BYE')\n\n\nsuffixes=['txt','log','py','*']\ndirectories=['textfiles','logs','scripts','others']\n\nfor directory in directories:\n\tos.mkdir(directory)\n\tprint('create a directory')\n\nfor i,suffix in enumerate(suffixes):\n\tfiles=glob.glob('*.' + suffix)\n\tfor file in files:\n\t\tshutil.move(file,directories[i])\n\t\tprint('moving a file [ ', file, \"] to \", directories[i])\n\nprint(\"Done\")\n","sub_path":"kaisyaKensyu/folderMoving.py","file_name":"folderMoving.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"573608684","text":"# -*- encoding: UTF-8 -*-\n# --------------------------\n\n\nif __name__ == '__main__':\n import time\n start_time = time.time()\n # -----------------------------------\n # -----------------------------------\n end_time = time.time()\n duration = end_time - start_time\n hour = int(duration) // 3600\n minutes = int(duration) // 60 - 60 * hour\n seconds = duration % 60\n print('\\nRunning time: {0:d} h {1:d} m {2:.4f} s'.format(hour, minutes, seconds))\n","sub_path":"BasicCodePackage/FileIO.py","file_name":"FileIO.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"180864767","text":"import csv, os, cv2, sys\nimport numpy as np\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Flatten, Dense, Lambda, Cropping2D, Dropout\nfrom keras.layers.convolutional import Convolution2D\nfrom keras.layers.pooling import MaxPooling2D\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\nimport matplotlib.pyplot as plt\n\n# standard driving, keeping close to the center of the lane\ndata_dirs_normal = ['data2_track1/data_{}'.format(i) for i in range(1,16)]\n\n# recovery maneuvers (returning to the center of the lane)\ndata_dirs_recovery = ['data_track1/data_recovery_{}'.format(i) for i in range(1,7)]\n\n# use both datasets for training\ndata_dirs = data_dirs_normal + data_dirs_recovery\n\n# read dataset\nlines = []\nfor data_dir in data_dirs:\n with open(os.path.join(data_dir, 'driving_log.csv')) as csvfile:\n reader = csv.reader(csvfile)\n for line in reader:\n angle = float(line[3])\n\n # eliminate bias towards straight driving\n if not abs(angle) < 0.05 or np.random.random() < 0.5:\n lines.append(line)\n lines[-1].append(data_dir)\n\n# split data into train and validation sets\ntrain_samples, validation_samples = train_test_split(lines, test_size=0.2)\n\n# plot histogram of steering angles to check if dataset contains\n# too many straight segments\nif False:\n plt.hist([float(line[3]) for line in lines])\n plt.xlabel(\"steering angle\")\n plt.ylabel(\"count\")\n plt.show()\n sys.exit(0)\n\n# generator to preprocess the data\ndef generator(samples, batch_size=256):\n num_samples = len(samples)\n while True:\n samples = shuffle(samples)\n\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples[offset:offset + batch_size]\n images = []\n measurements = []\n\n for batch_sample in batch_samples:\n correction_factor = 0.3\n\n for i, correction in enumerate([0, 1, -1]):\n filename = os.path.basename(batch_sample[i])\n data_dir = batch_sample[-1]\n image = cv2.imread(os.path.join(data_dir, 'IMG', filename))\n\n # use also data from left and right cameras by applying\n # correction factor\n angle = float(batch_sample[3]) + correction*correction_factor\n\n # augmentation of data\n flipped = np.random.randint(2)\n if flipped:\n image = np.fliplr(image)\n angle = -angle\n\n images.append(image)\n measurements.append(angle)\n\n X_train = np.array(images)\n y_train = np.array(measurements)\n\n yield shuffle(X_train, y_train)\n\ntrain_generator = generator(train_samples)\nvalidation_generator = generator(validation_samples)\n\n\nmodel_filename = 'model.h5'\n\nif not os.path.exists(model_filename):\n model = Sequential()\n model.add(Lambda(lambda x: x/255. - 0.5, input_shape=(160,320,3)))\n model.add(Cropping2D(cropping=((70,24),(0,0))))\n model.add(Convolution2D(24, 5, 5, subsample=(2,2), activation='relu'))\n model.add(Dropout(0.5))\n model.add(Convolution2D(36, 5, 5, subsample=(2,2), activation='relu'))\n model.add(Dropout(0.5))\n model.add(Convolution2D(48, 5, 5, subsample=(2,2), activation='relu'))\n model.add(Dropout(0.5))\n model.add(Convolution2D(64, 3, 3, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Convolution2D(128, 3, 3, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Flatten())\n model.add(Dense(256, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(64, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(1))\n model.compile(loss='mse', optimizer='adam')\nelse:\n model = load_model(model_filename)\n model.optimizer.lr.assign(0.0001)\n\nmodel.fit_generator(train_generator,\n samples_per_epoch=3*len(train_samples),\n validation_data=validation_generator,\n nb_val_samples=3*len(validation_samples),\n nb_epoch=5)\n\nmodel.save(model_filename)\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"225380905","text":"import sublime, sublime_plugin\nimport subprocess, os, sys\n\nclass GotoFolderCommand(sublime_plugin.ApplicationCommand):\n\tdef __init__(self):\n\t\tself.app_path_mac = None\n\t\tself.folder_list = None\n\t\tself.cache = False\n\n\tdef get_sublime_path(self):\n\t\tif sublime.platform() == 'osx':\n\t\t\tif not self.app_path_mac:\n\t\t\t\tfrom ctypes import cdll, byref, Structure, c_int, c_char_p, c_void_p\n\t\t\t\tfrom ctypes.util import find_library\n\t\t\t\tFoundation = cdll.LoadLibrary(find_library('Foundation'))\n\t\t\t\tCFBundleGetMainBundle = Foundation.CFBundleGetMainBundle\n\t\t\t\tCFBundleGetMainBundle.restype = c_void_p\n\t\t\t\tbundle = CFBundleGetMainBundle()\n\t\t\t\tCFBundleCopyBundleURL = Foundation.CFBundleCopyBundleURL\n\t\t\t\tCFBundleCopyBundleURL.argtypes = [c_void_p]\n\t\t\t\tCFBundleCopyBundleURL.restype = c_void_p\n\t\t\t\turl = CFBundleCopyBundleURL(bundle)\n\t\t\t\tCFURLCopyFileSystemPath = Foundation.CFURLCopyFileSystemPath\n\t\t\t\tCFURLCopyFileSystemPath.argtypes = [c_void_p, c_int]\n\t\t\t\tCFURLCopyFileSystemPath.restype = c_void_p\n\t\t\t\tpath = CFURLCopyFileSystemPath(url, c_int(0))\n\t\t\t\tCFStringGetCStringPtr = Foundation.CFStringGetCStringPtr\n\t\t\t\tCFStringGetCStringPtr.argtypes = [c_void_p, c_int]\n\t\t\t\tCFStringGetCStringPtr.restype = c_char_p\n\t\t\t\tself.app_path_mac = CFStringGetCStringPtr(path, 0)\n\t\t\t\tCFRelease = Foundation.CFRelease\n\t\t\t\tCFRelease.argtypes = [c_void_p]\n\t\t\t\tCFRelease(path)\n\t\t\t\tCFRelease(url)\n\t\t\treturn self.app_path_mac.decode() + '/Contents/SharedSupport/bin/subl'\n\t\telif sublime.platform() == 'linux':\n\t\t\treturn open('/proc/self/cmdline').read().split(chr(0))[0]\n\t\telse:\n\t\t\treturn sys.executable\n\n\tdef sublime_command_line(self, args):\n\t\targs.insert(0, self.get_sublime_path())\n\t\treturn subprocess.Popen(args)\n\n\tdef run(self):\n\t\tif not sublime.active_window():\n\t\t\tsublime.run_command(\"new_window\")\n\t\t\tself.use_active_window = True\n\t\telse:\n\t\t\tself.use_active_window = False\n\t\tif not self.cache or not self.folder_list:\n\t\t\tsettings = sublime.load_settings('GotoFolder.sublime-settings')\n\t\t\tself.cache = settings.get(\"cache\", False);\n\t\t\troot_folders = settings.get(\"root_folders\", [{'folder': sublime.packages_path(), 'alias': 'Plugin'}])\n\t\t\tself.folder_list = [];\n\t\t\tself.folder_info = [];\n\t\t\tfolder_count = 0;\n\t\t\tfor root in root_folders:\n\t\t\t\tif 'alias' not in root:\n\t\t\t\t\troot['alias'] = \"\"\n\t\t\t\telse:\n\t\t\t\t\troot['alias'] += \":\"\n\t\t\t\ttry:\n\t\t\t\t\tfor f in os.listdir(root['folder']):\n\t\t\t\t\t\tif f.startswith(\".\") or (os.path.isfile(root['folder']+\"/\"+f) and not f.endswith(\".sublime-project\")):\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tself.folder_list.append([root['alias']+f])\n\t\t\t\t\t\ta = [root['folder']+\"/\"+f]\n\t\t\t\t\t\tif 'extra' in root:\n\t\t\t\t\t\t\ta += root['extra']\n\t\t\t\t\t\tself.folder_info.append(a)\n\t\t\t\t\t\tfolder_count+=1\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tprint(e, \". Check GotoFolder.sublime-settings file\")\n\t\t\t#print \"GotoFolder Plugin:\", folder_count, \"folders added to the list\"\n\t\tsublime.active_window().show_quick_panel(self.folder_list, self.on_select)\n\n\tdef on_select(self, idx):\n\t\tif idx < 0:\n\t\t\treturn\n\t\t# disabled due to lack of sublime.focus_window API\n\t\t#if self.find_and_focus_folder(folder_list[idx][1]): return\n\t\targs = [\"-n\"] + self.folder_info[idx]\n\t\tif self.use_active_window:\n\t\t\targs[0] = \"-a\"\n\t\tself.sublime_command_line(args)\n\n\tdef find_and_focus_folder(self, folder):\n\t\tfor w in sublime.windows():\n\t\t\tfor f in w.folders():\n\t\t\t\tif f == folder:\n\t\t\t\t\tsublime.focus_window(w)\n\t\t\t\t\t#sublime.set_timeout(partial(ctypes.windll.user32.SetForegroundWindow, window.hwnd(), 0), 500)\n\t\t\t\t\treturn True\n\t\treturn False\n\n\n","sub_path":"Packages/SublimeGotoFolder/GotoFolder.py","file_name":"GotoFolder.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"246691736","text":"#\n# $Id: flowCommands.py,v 1.2 2013/01/21 13:46:51 xantgui Exp $\n#\n# Copyright (c) Ericsson Espana., 2011.\n# All rights reserved.\n#\n# This product or document is proprietary to and embodies the\n# confidential technology of Ericsson Espana.\n# Possession, use, duplication or distribution of this product\n# or document is authorized only pursuant to a valid written\n# license from Ericsson Espana S.A\n#\n\n\"\"\"\nClass to implement sending and checking WAP messages from a yml config file.\n\"\"\"\nimport yaml\nimport re\nimport logging\nimport wapBuilder\n\nfrom mms.iterator import PreviewIterator\n\nFLOW_CLASSES = { \"SEND_REQUEST\" : \"SendGetCommand\", \\\n \"RECV_REQUEST\" : \"ReceiveCommand\", \\\n \"SEND_RESPONSE\" : \"SendReplyCommand\", \\\n \"RECV_RESPONSE\" : \"ReceiveCommand\", \\\n \"SEND_CONNECT\" : \"SendConnectCommand\", \\\n \"RECV_CONNECT\" : \"ReceiveCommand\", \\\n \"SEND_CONNECT_REPLY\" : \"SendConnectReplyCommand\", \\\n \"RECV_CONNECT_REPLY\" : \"ReceiveCommand\", \\\n \"SEND_DISCONNECT\" : \"SendDisconnectCommand\", \\\n \"RECV_DISCONNECT\" : \"ReceiveCommand\", \\\n\n # WTP\n \"SEND_ACK\" : \"SendAckCommand\", \\\n \"RECV_ACK\" : \"ReceiveCommand\", \\\n \"SEND_ABORT\" : \"SendAbortCommand\", \\\n \"RECV_ABORT\" : \"ReceiveCommand\"\n }\n'''\nThis dict links each flow command name in the config file with the class to be created\n'''\n \n \nCHECK_CLASSES = { \"Status\" : \"CheckStatus\", \\\n \"Headers\" : \"CheckHeaders\", \\\n \"Content\" : \"CheckContent\", \\\n \"RequestURI\" : \"CheckUri\", \\\n \"Status\" : \"CheckStatus\", \\\n \"Method\" : \"CheckMethod\" \\\n }\n'''\nThis dict links each checking command in the config file with the class to be created\n'''\n \nSERVER_ALLOWED_COMMANDS = [ \"RECV_REQUEST\", \\\n \"SEND_RESPONSE\", \\\n\n \"RECV_CONNECT\", \\\n \"SEND_CONNECT_REPLY\", \\\n\n \"RECV_DISCONNECT\", \\\n\n \"RECV_ACK\", \\\n \"RECV_ABORT\"\n ]\n'''\nThese are the commands that will be allowed to be sent/received byt the wap server\n'''\n\nCLIENT_ALLOWED_COMMANDS = [ \"SEND_REQUEST\", \\\n \"RECV_RESPONSE\", \\\n\n \"SEND_CONNECT\", \\\n \"RECV_CONNECT_REPLY\", \\\n\n \"SEND_DISCONNECT\", \\\n\n \"SEND_ACK\", \\\n \"SEND_ABORT\"\n ]\n'''\nThese are the commands that will be allowed to be sent/received byt the wap client\n'''\n\ndef create_flow_objects(yml_flow):\n '''\n Function to create flow objects form the config file\n '''\n yml_classes = []\n for flow in yml_flow: \n key = flow.keys()[0]\n value = flow[key]\n new_class = _create_flow_object(key, value)\n yml_classes.append(new_class)\n new_class.set_command_tag(key)\n return yml_classes\n\ndef _create_flow_object(flow_name, config):\n '''\n Function to create a single flow objects form the config file\n '''\n\n if flow_name in FLOW_CLASSES.keys():\n return eval(FLOW_CLASSES[flow_name] + \"(config)\")\n else:\n return None\n\nclass FlowLogger(object):\n '''\n Simple class to create log messages for the child classes\n '''\n def __init__(self):\n '''\n Constructor\n '''\n pass\n # Nothing to do\n \n def _log_error(self, msg):\n \"\"\"\n Log an error messages adding a prefix. The logged string is returned\n for later use\n \"\"\"\n return self._log(msg, \"** Error: \")\n\n def _log(self, msg, prefix = \"\"):\n \"\"\"\n Log an error messages adding a prefix. The logged string is returned\n for later use\n \"\"\"\n msg = \"[\" + self.__class__.__name__ + \"] \" + prefix + msg\n logging.getLogger(\"NSTlogger\").debug(msg)\n return msg\n\nclass FlowCommand(FlowLogger):\n '''\n Base class for all the flow commands in the config file\n '''\n def __init__(self, send, config):\n '''\n Constructor\n @param send: Indicates if the command is a send (True) or a receive (False) command\n @type send: bool\n @param config: configuration for the flow command (read from the config file)\n @type config: dict\n '''\n FlowLogger.__init__(self)\n self._config = None\n self._command_tag = \"\"\n self._send = send\n self.set_config(config)\n \n def __str__(self):\n '''\n String representation of the object\n '''\n return self.get_command_tag() + \": \" + str(self.get_config())\n \n def is_send_command(self):\n '''\n Check if the command is to send (True) or to receive (False)\n @return:\n - True: send command\n - False: receive command\n @rtype: bool\n '''\n return self._send\n \n def get_config(self):\n '''\n Config getter\n @return: config\n @rtype: dict\n '''\n if self._config:\n return self._config\n else:\n return {}\n\n def set_config(self, config):\n '''\n Config setter\n @param config: flow configuration\n @type config: dict\n '''\n self._config = config\n\n def set_command_tag(self, tag):\n '''\n Command tag setter. The command tag is used for logging purposes\n @param tag: tag name\n @type tag: str\n '''\n self._command_tag = tag\n\n def get_command_tag(self):\n '''\n Command tag getter\n @return: command tag\n @rtype: str\n '''\n return self._command_tag\n\n\nclass SendCommand(FlowCommand):\n '''\n Generic send flow command\n '''\n def __init__(self, config):\n '''\n Constructor\n '''\n FlowCommand.__init__(self, True, config)\n\n def compose_packet(self):\n '''\n Default function to create the packet to send. Child classes should implement\n this method properly.\n '''\n return str(self.get_config())\n \n def get_headers(self, config):\n '''\n Function to get headers from config file, if the parameter in the config file\n is a list we convert it to a dicts. This is to mantain compatibility with \n httpServer which uses list instead of a dict\n '''\n headers = {}\n\n if config and \"Headers\" in config:\n # There are two options to write the headers, either a list of dicts\n # (to mantain compatibility with httpServer) or just a dict. If it is a\n # list we convert it to a dict, which is what the WSPLayer function expect\n if isinstance(config[\"Headers\"], list):\n headers = {}\n for item in config[\"Headers\"]:\n headers.update(item)\n else:\n headers = config[\"Headers\"]\n return headers\n\nclass ReceiveCommand(FlowCommand):\n '''\n Generic receive flow command\n '''\n def __init__(self, config):\n '''\n Constructor\n '''\n self._check_classes = {}\n \n FlowCommand.__init__(self, False, config)\n\n def set_config(self, config):\n '''\n Flow command config setter\n '''\n FlowCommand.set_config(self, config)\n self._create_check_classes()\n\n def _create_check_classes(self):\n '''\n Function to create the check classes for the receive flow command\n '''\n if not self._config:\n return \n \n for key in self._config:\n if key in CHECK_CLASSES:\n obj = eval(CHECK_CLASSES[key] + \"(key, self._config[key])\")\n self._check_classes[key] = obj\n else:\n msg = self._log_error(\"Assertion tag '%s' in config file is not valid\" % key)\n assert 0, msg\n \n\n def assert_packet(self, datagram):\n '''\n Function to check if the packet received is correct\n '''\n self._log(\"Decoding datagram...\" + repr(datagram))\n\n config = self.get_config()\n\n errors = []\n ret = True\n wsp_data = None\n wtp_data = None\n\n if len(self._check_classes.values()) > 0:\n try:\n byte_iter = PreviewIterator(datagram)\n wtp_data = wapBuilder.WTPLayer.decode_wtp(byte_iter)\n wsp_data = wapBuilder.WSPLayer.decode_wsp(byte_iter)\n except Exception as ex: \n self._log_error(\"Error decoding datagram: \" + str(ex) )\n ret = False\n \n for obj in self._check_classes.values():\n try:\n status_ok, check_errors = obj.check(wtp_data, wsp_data)\n if not status_ok:\n ret = False\n errors.extend(check_errors)\n except Exception as ex:\n self._log_error(\"Error verifying datagram: \" + str(ex) )\n ret = False\n\n return ret, errors\n\nclass SendConnectCommand(SendCommand):\n '''\n Class to send connect command\n '''\n\n def compose_packet(self):\n '''\n Function to create the packet to send\n '''\n pdu = \"\"\n headers = {}\n self._log(\"composing WAP request\")\n pdu = wapBuilder.WSPLayer.request(\"CONNECT\", \"\", headers, \n wapBuilder.WSPLayer.wapProtocolStack)\n self._log(\"pdu is ready\")\n\n return pdu\n\nclass SendGetCommand(SendCommand):\n '''\n Class to get abort command\n '''\n\n def compose_packet(self):\n '''\n Function to create the packet to send\n '''\n pdu = \"\"\n headers = {}\n self._log(\"composing WAP request\")\n pdu = wapBuilder.WSPLayer.request(\"GET\", self.get_config()[\"RequestURI\"], headers, \n wapBuilder.WSPLayer.wapProtocolStack)\n self._log(\"pdu is ready\")\n\n return pdu\n\nclass SendReplyCommand(SendCommand):\n '''\n Class to send reply command\n '''\n def __init__(self, config):\n '''\n Constructor\n '''\n self._content = \"\"\n self._content_type = \"application/vnd.wap.mms-message\"\n self._status = \"200\"\n self._headers = {}\n SendCommand.__init__(self, config)\n \n def set_config(self, config):\n '''\n Flow command config setter\n '''\n SendCommand.set_config(self, config)\n if config:\n if \"Content\" in config:\n self._content = config[ \"Content\"]\n if \"Content-Type\" in config:\n self._content_type = config[ \"Content-Type\"]\n if \"Status\" in config:\n self._status = str(config[\"Status\"])\n self._headers = self.get_headers(config)\n\n def compose_packet(self):\n '''\n Function to create the packet to send\n '''\n pdu = \"\"\n \n status = 0x20\n if len(self._status) >= 3:\n status = int(self._status[0])*16 + int(self._status[2])\n\n self._log(\"composing WAP request\")\n pdu = wapBuilder.WSPLayer.request(\"REPLY\", \"\", self._headers, wapBuilder.WSPLayer.wapProtocolStack, \n transactionID=wapBuilder.WTPLayer.transactionId, content=self._content, \n content_type=self._content_type, status=status )\n self._log(\"pdu is ready\")\n\n return pdu\n\nclass SendDisconnectCommand(SendCommand):\n '''\n Class to send disconncet command\n '''\n def __init__(self, config):\n '''\n Constructor\n '''\n self._session_id = 1\n SendCommand.__init__(self, config)\n \n def set_config(self, config):\n '''\n Flow command config setter\n '''\n SendCommand.set_config(self, config)\n if config and \"SessionID\" in config:\n self._session_id = config[ \"SessionID\"]\n\n def compose_packet(self):\n '''\n Function to create the packet to send\n '''\n pdu = \"\"\n headers = {}\n self._log(\"composing WAP request\")\n pdu = wapBuilder.WSPLayer.request(\"DISCONNECT\", \"\", headers, \n wapBuilder.WSPLayer.wapProtocolStack, session_id = self._session_id)\n self._log(\"pdu is ready\")\n\n return pdu\n\nclass SendConnectReplyCommand(SendCommand):\n '''\n Class to send connect reply command\n '''\n def __init__(self, config):\n '''\n Constructor\n '''\n self._session_id = 1\n self._headers = {}\n SendCommand.__init__(self, config)\n\n def set_config(self, config):\n '''\n Flow command config setter\n '''\n SendCommand.set_config(self, config)\n if config and \"SessionID\" in config:\n self._session_id = config[\"SessionID\"]\n \n self._headers = self.get_headers(config)\n \n def compose_packet(self):\n '''\n Function to create the packet to send\n '''\n pdu = \"\"\n self._log(\"composing WAP request\")\n pdu = wapBuilder.WSPLayer.request(\"CONNECTREPLY\", \"\", self._headers, wapBuilder.WSPLayer.wapProtocolStack, \n wapBuilder.WTPLayer.transactionId, session_id=self._session_id)\n self._log(\"pdu is ready\")\n\n return pdu\n\nclass SendAckCommand(SendCommand):\n '''\n Class to send ack command\n '''\n\n def compose_packet(self):\n '''\n Function to create the packet to send\n '''\n pdu = \"\"\n self._log(\"composing WAP request\")\n pdu = wapBuilder.WTPLayer.addWTPLayer(\"ack\", wapBuilder.WTPLayer.transactionId)\n self._log(\"pdu is ready\")\n return pdu\n\nclass SendAbortCommand(SendCommand):\n '''\n Class to send abort command\n '''\n\n def compose_packet(self):\n '''\n Function to create the packet to send\n '''\n pdu = \"\"\n self._log(\"composing WAP request\")\n pdu = wapBuilder.WTPLayer.addWTPLayer (\"abort\", wapBuilder.WTPLayer.transactionId)\n self._log(\"pdu is ready\")\n return pdu\n\n\n# ----------------------------------------------------------------------\n# Check classes\n# ----------------------------------------------------------------------\nclass CheckClass(FlowLogger):\n '''\n Generic flow check class\n '''\n def __init__(self, tag_name, config):\n '''\n Constructor\n '''\n FlowLogger.__init__(self)\n \n self._config = None\n self.tag_name = tag_name\n self._objects = []\n \n self.set_config(config)\n \n def __repr__(self):\n '''\n String representation of the object\n '''\n desc = \"Tag Name: \" + self.tag_name + \"\\n\"\n desc += \"Config: \" + repr(self._config)\n \n return desc\n \n def set_config(self, config):\n '''\n General config function\n '''\n if isinstance(config, list):\n self._config = {}\n for item in config:\n if isinstance(item, dict):\n self._config.update(item)\n else:\n self._objects.append(item)\n else:\n self._config = config\n \n def check(self, wtp_data, wsp_data):\n '''\n Default checking function: \n @param wtp_data: wtp_data\n @type wtp_data: WTPData\n @param wsp_data: wsp_data\n @type wsp_data: WSPData\n @return: Status and errors (status, errors)\n - status OK: True\n - status error: False\n - errors: string list with errors\n @rtype: tuple\n '''\n errors = []\n errors.append(self._log_error(\"'check' function not implemented\"))\n return False, errors\n\n def _check_objects(self, wtp_data, wsp_data):\n '''\n Default checking function: \n @param wtp_data: wtp_data\n @type wtp_data: WTPData\n @param wsp_data: wsp_data\n @type wsp_data: WSPData\n @return: Status and errors (status, errors)\n - status OK: True\n - status error: False\n - errors: string list with errors\n @rtype: tuple\n '''\n ret = True\n ret_errors = []\n self._log(\"Checking objects...\")\n for obj in self._objects:\n self._log(\"Checking object: %s\" % obj)\n ok, errors = obj.check(wtp_data, wsp_data)\n ret_errors.extend(errors)\n if not ok:\n ret = ok\n self._log(\"Checking objects finished\")\n return ret, ret_errors\n \nclass CheckHeaders(CheckClass):\n '''\n Header checking class\n '''\n def check(self, wtp_data, wsp_data):\n '''\n Checking function\n '''\n ret = True\n errors = []\n \n if not wsp_data:\n errors.append(self._log_error(\"wsp data not available\"))\n return False, errors\n \n # Verifying regular headers\n for key in self._config:\n h_found = None\n self._log(\"Checking header: '%s'\" % key)\n for header in wsp_data.headers.getAllRawHeaders():\n if header[0] == key:\n h_found = header\n break\n if not h_found:\n errors.append(self._log_error(\"Header not found in datagram: '%s'\" % key))\n ret = False\n else: \n value = h_found[1][0]\n if self._config[key] == None:\n self._log(\"Header found in datagram: '%s'\" % key)\n elif re.match(self._config[key], value) == None:\n errors.append(self._log_error(\"Header mismatch: '%s' not found in '%s'\" % (self._config[key], value)))\n ret = False\n else:\n self._log(\"Header match: '%s' found in '%s'\" % (self._config[key], value))\n \n # Verifying yaml created objects\n obj_ok, obj_errors = self._check_objects(wtp_data, wsp_data)\n errors.extend(obj_errors)\n if not obj_ok:\n ret = False\n\n return ret, errors\n\nclass CheckHasHeader(CheckClass):\n \"\"\"\n Class used to check existance of a Header in a HTTP message.\n HasHeader objects are created in L{nhasheader_constructor}\n when a '!wap.hasheader' tag is found in a YAML file.\n \"\"\"\n def check(self, wtp_data, wsp_data):\n '''\n Checking function\n '''\n ret = False\n errors = []\n \n h_found = self.find_header(wsp_data)\n if h_found:\n self._log(\"Header found: '%s'\" % self._config)\n ret = True\n else:\n errors.append(self._log_error(\"Header NOT found: %s\" % self._config))\n ret = False\n \n return ret, errors \n \n def find_header(self, wsp_data):\n '''\n Function to find a header\n ''' \n if not wsp_data:\n errors.append(self._log_error(\"wsp data not available\"))\n return None\n\n h_found = None\n self._log(\"Looking for header: '%s'\" % self._config)\n for header in wsp_data.headers.getAllRawHeaders():\n if header[0] == self._config:\n h_found = header\n break\n \n return h_found\n\nclass CheckNotHasHeader(CheckHasHeader):\n \"\"\"\n Class used to check non-existance of a Header in a HTTP message.\n NotHasHeader objects are created in L{nhasheader_constructor} when a\n '!wap.nhasheader' tag is found in a YAML file.\n \"\"\"\n def check(self, wtp_data, wsp_data):\n '''\n Checking function\n '''\n '''\n Checking function\n '''\n ret = False\n errors = []\n \n h_found = self.find_header(wsp_data)\n if not h_found:\n self._log(\"Header not found (ok): '%s'\" % self._config)\n ret = True, []\n else:\n errors.append(self._log_error(\"Header found but it should not exist: %s\" % self._config))\n ret = False\n \n return ret, errors\n\n \nclass CheckContent(CheckClass):\n '''\n Content checking class\n '''\n def check(self, wtp_data, wsp_data):\n '''\n Checking function\n '''\n ret = False\n errors = []\n \n if not wsp_data:\n errors.append(self._log_error(\"wsp data not available\"))\n return False, errors\n \n if str(self._config) not in str(wsp_data.data):\n errors.append(self._log_error(\"Content '%s' NOT found in datagram\" % str(self._config)))\n ret = False\n else:\n self._log(\"Content '%s' found in datagram\" % str(self._config))\n ret = True\n \n return ret, errors\n\nclass CheckStatus(CheckClass):\n '''\n Status checking class\n '''\n def check(self, wtp_data, wsp_data):\n '''\n Checking function\n '''\n ret = False\n errors = []\n \n if not wsp_data:\n errors.append(self._log_error(\"wsp data not available\"))\n return False, errors\n\n if str(self._config) != str(wsp_data.code):\n errors.append(self._log_error(\"Status expected: '%s', found '%s'\" % (str(self._config), str(wsp_data.code))))\n ret = False\n else:\n self._log(\"Status OK: '%s'\" % str(self._config))\n ret = True\n \n return ret, errors \n\nclass CheckUri(CheckClass):\n '''\n Uri checking class\n '''\n def check(self, wtp_data, wsp_data):\n '''\n Checking function\n '''\n ret = False\n errors = []\n if not wsp_data:\n errors.append(self._log_error(\"wsp data not available\"))\n return False, errors\n \n if re.match(self._config, wsp_data.uri) == None:\n errors.append(self._log_error(\"String '%s' NOT found in uri '%s'\" % (str(self._config), wsp_data.uri)))\n ret = False\n else:\n self._log(\"String '%s' found in uri '%s'\" % (str(self._config), wsp_data.uri))\n ret = True\n \n return ret, errors\n\nclass CheckMethod(CheckClass):\n '''\n Method checking class\n '''\n def check(self, wtp_data, wsp_data):\n '''\n Checking function\n '''\n ret = False\n errors = []\n \n if not wsp_data:\n errors.append(self._log_error(\"wsp data not available\"))\n return False, errors\n \n if self._config.upper() != wsp_data.pduTypeName.upper():\n errors.append(self._log_error(\"Unexpected method '%s'. Expected '%s'\" % (str(self._config), wsp_data.pduTypeName)))\n ret = False\n else:\n self._log(\"Expected method ok: '%s'\" % str(self._config))\n ret = True\n \n return ret, errors\n \n \n# ----------------------------------------------------------------------\n# Yaml functions\n# ----------------------------------------------------------------------\ndef hasheader_constructor(loader, node):\n \"\"\"\n Called when a YAML loader finds a '!hasheader_constructor' tag.\n @param loader: loader to use\n @type loader: YAMLLoader\n @param node: node to use\n @type node: YAMLNode\n @return: a ExistsMIB\n \"\"\"\n if type(node) == yaml.nodes.ScalarNode:\n value = loader.construct_scalar(node)\n elif type(node) == yaml.nodes.SequenceNode:\n value = loader.construct_sequence(node)\n return CheckHasHeader(\"!wap.hasheader\", value)\n\ndef nhasheader_constructor(loader, node):\n \"\"\"@param loader: loader to use\n @type loader: YAMLLoader\n @param node: node to use\n @type node: YAMLNode\n @return: a NotExistsMIB\n Called when a YAML loader finds a '!nhasheader_constructor' tag.\"\"\"\n if type(node) == yaml.nodes.ScalarNode:\n value = loader.construct_scalar(node)\n elif type(node) == yaml.nodes.SequenceNode:\n value = loader.construct_sequence(node)\n return CheckNotHasHeader(\"!wap.nhasheader\", value)\n\nyaml.add_constructor(\"!wap.hasheader\", hasheader_constructor)\nyaml.add_constructor(\"!wap.nhasheader\", nhasheader_constructor)\n","sub_path":"sds/back_test/ref/wap/flowCommands.py","file_name":"flowCommands.py","file_ext":"py","file_size_in_byte":24801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"467263681","text":"import requests\n\nurl = 'https://www.baidu.com/s'\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36'\n}\nparams = {\n 'wd': 'ip'\n}\nproxy={\n 'http':'183.240.203.136:8118'\n}\nresponse = requests.get(url=url, params=params, headers=headers,proxies=proxy)\ncontent = response.text\nwith open('daili.html', 'w', encoding='utf-8') as fp:\n fp.write(content)\n","sub_path":"requests/004_proxy.py","file_name":"004_proxy.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"418746891","text":"import abc\n\n__author__ = 'bborel'\n__title__ = \"PCAMAP Base\"\n__version__ = '2.0.0'\n\n\nclass PCAMapBase(object):\n __metaclass__ = abc.ABCMeta\n\n @abc.abstractmethod\n def __init__(self, mode_mgr, ud, **kwargs):\n self._mode_mgr = mode_mgr\n self._ud = ud\n\n # Properties -------------------------------------------------------------------------------------------------------\n # No user properties\n\n # Methods ----------------------------------------------------------------------------------------------------------\n @abc.abstractmethod\n def read(self, device_instance, slot_number=None, **kwargs):\n raise NotImplementedError(\"Need 'read' method implementation.\")\n\n @abc.abstractmethod\n def write(self, device_instance, set_params, slot_number=None, **kwargs):\n raise NotImplementedError(\"Need 'write' method implementation.\")\n","sub_path":"libs/bases/pcamap_base.py","file_name":"pcamap_base.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"296237330","text":"import re, webbrowser, json, trello, requests, ssl\n\n# Trello API Key, Token, and Board Names\nApiKey = ''\ntoken = ''\nboardName =''\n\n# Variables to find lists variables\nlists = []\nday1 = {}\nnameListDay1 = []\nsslContext = ssl.SSLContext()\n\nextension = 'detail/recent-activity/shares/' #add this to go to specific linkedIn page to show their posts\nlinkedInURLsDay1 = ['www.google.com']\n\n# get all the boards from my account\nboards = requests.get('https://api.trello.com/1/members/me/boards?fields=name,url&key={}&token={}'.format(ApiKey, token))\nboards = json.loads(boards.content)\n\n# find the right board\nfor board in boards:\n if board[\"name\"] == boardName:\n boardID = board[\"id\"]\n boardReq = board\n break\n\n# get all lists from board and get the id for the lists\ngetLists = trello.Boards(ApiKey, token).get_list(boardID)\nfor list in getLists:\n lists.append({\"id\": list[\"id\"], \"name\": list[\"name\"]})\n\n# setting days to the id and name of each list from lists\nday1 = lists[0]\n\n# get list of cards names in list I want\ncardList = trello.Lists(ApiKey, token).get_card(day1[\"id\"])\nfor card in cardList:\n nameListDay1.append(card[\"name\"])\n\n# append the posts extension to URL\nfor name in nameListDay1:\n URLStart = re.search(\"https://+\", name) # find linkedIn URL by searching for the start point of https://\n if URLStart:\n linkedInURLsDay1.append(name[URLStart.start():len(name)])\n\n# Opens new tab for all linkedIn URLs\nfor URL in linkedInURLsDay1:\n webbrowser.open(URL, new=1)\n\n","sub_path":"1.4 View-Day-1-Connected.py","file_name":"1.4 View-Day-1-Connected.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"223365915","text":"# 计算0-100之间的所有偶数累计求和结果\n# 定义最终结果\nresult = 0\n# 计数器\ni = 0\n# 开始循环确认要计算的数字\nwhile i <= 100:\n # 判断变量i中的数值,是否是一个偶数\n # 偶数 i % 2 == 0 奇数 i % 2 != 0\n if i % 2 == 0:\n print(i)\n # 当i这个变量是偶数时,才进行累加操作\n result += i\n# result += i\n i += 1\nprint(\"0-100之间偶数的和 = %d\" % result)\n","sub_path":"Python基础学习/test_19_偶数累计求和.py","file_name":"test_19_偶数累计求和.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"126868170","text":"def Hash(x):\n val=0\n hashed = list()\n for i in range(len(x)):\n val += ord(x[i])\n for i in range(7,12):\n hashed.append(val%i)\n print(\"\".join(str(x) for x in hashed))\n \ndef main():\n x = input(\"Enter string: \")\n Hash(x)\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"December-19/python_raf1800.py","file_name":"python_raf1800.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"197019541","text":"'''\r\nCreated on Sun Dec 29 15:07:26 2019\r\n\r\n@author: hl3797\r\n'''\r\n# PROGRAMMING ASSIGNMENT 05\r\n# Filename: 'exercise1.py'\r\n#\r\n# Write the code for function diamond.\r\n# The function diamond:\r\n# • takes one parameter N (type int), its value must be odd and in the range [3, 99]\r\n# • it draws a square shape made of integer values and spaces:\r\n# - integer values are always printed with 2 digits (for example, value 7 is printed 07)\r\n# - every line consists of integer values from 1 up to N , where some values have to be\r\n# replaced by spaces instead\r\n# - the first and last row are full (no space)\r\n# - the middle row is empty except for values 1 and N ,\r\n# - each row from the FIrst one to the middle one is increasingly empty from its center\r\n# - each row from the middle one to the last one is increasingly full to its center\r\n\r\ndef main():\r\n #try to draw some diamonds by calling the function diamond\r\n print('Calling: diamond(5)')\r\n diamond(5)\r\n\r\n #empty line\r\n print()\r\n\r\n print('Calling: diamond(15)')\r\n diamond(15)\r\n\r\n\r\ndef diamond(N):\r\n #WRITE YOUR CODE HERE\r\n\r\n # Compute the scale\r\n key = (N + 1) // 2\r\n\r\n for i in range(1, N + 1):\r\n # Initialize variables and compute the numbers\r\n num = 1\r\n line = ''\r\n blank_count = N - 2 - 2 * abs(key - i)\r\n num_count = (N - blank_count) // 2\r\n\r\n # Generate the output of one line\r\n for i in range(num_count):\r\n line += '%02d' % num\r\n num = num + 1\r\n for i in range(blank_count):\r\n line += ' '\r\n num = num + 1\r\n for i in range(num_count):\r\n # Handle the exception of first and last lines\r\n if num <= N:\r\n line += '%02d' % num\r\n num = num + 1\r\n\r\n # Output\r\n print(line)\r\n\r\n#Call the main() function\r\nmain()\r\n","sub_path":"ICP exercise and assignment/A05/Sample Solutions/A05_e1.py","file_name":"A05_e1.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"386427847","text":"# -*- coding: utf-8 -*-\n\nfrom datetime import date, timedelta, datetime\nfrom django import template\nfrom django.views.generic.date_based import archive_index\nfrom easy_news.models import News\n\nregister = template.Library()\n\n@register.inclusion_tag('easy_news/show_news.html')\ndef show_news(num_latest=5):\n object_list = News.objects.filter(show=True).filter(date__lte=datetime.now()).order_by('-date')[:num_latest]\n return locals()\n\ndef get_last_day_of_month(year, month):\n if (month == 12):\n year += 1\n month = 1\n else:\n month += 1\n return date(year, month, 1) - timedelta(1)\n\n@register.inclusion_tag('easy_news/calendar.html')\ndef calendar(year=None, month=None):\n if not year:\n year = date.today().year\n if not month:\n month = date.today().month\n\n object_list = News.objects.filter(date__year=year, date__month=month)\n\n first_day_of_month = date(year, month, 1)\n last_day_of_month = get_last_day_of_month(year, month)\n first_day_of_calendar = first_day_of_month - timedelta(first_day_of_month.weekday())\n last_day_of_calendar = last_day_of_month + timedelta(7 - last_day_of_month.weekday())\n\n month_cal = []\n week = []\n week_headers = []\n\n i = 0\n day = first_day_of_calendar\n while day <= last_day_of_calendar:\n if i < 7:\n week_headers.append(day)\n cal_day = {}\n cal_day['day'] = day\n cal_day['news'] = False\n for object in object_list:\n if day >= object.date and day <= object.date:\n cal_day['news'] = object\n if day.month == month:\n cal_day['in_month'] = True\n else:\n cal_day['in_month'] = False\n week.append(cal_day)\n if day.weekday() == 6:\n month_cal.append(week)\n week = []\n i += 1\n day += timedelta(1)\n\n return {'calendar': month_cal, 'headers': week_headers}\n","sub_path":"kat/kat_news/templatetags/easy_news_tags.py","file_name":"easy_news_tags.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"9903146","text":"import numpy as np\n\ndef norm_cumsum(weights):\n\t# normalised cumulative sum of a numpy 1D array\n\tweights /= sum(weights)\n\tweights = weights.cumsum()\n\tweights[-1] = 1.\n\treturn weights\n\n\ndef multinomial_resample(weights,rs=None):\n\tN = len(weights)\n\tif rs is None: rs = np.random.random(N)\n\n\tcumsum = norm_cumsum(weights)\n\tJ = np.searchsorted(cumsum, rs)\n\treturn J\n\ndef probablistic_resample(weights, M, rs=None):\n\tN = len(weights)\n\tif rs is None: rs = np.random.random(M)\n\tJ = np.arange(N)\n\n\tcumsum = norm_cumsum(weights)\n\tfor j in range(M):\n\t\ti = 0\n\t\twhile cumsum[i]= np.max(energy) / 5)\n indices = librosa.core.frames_to_samples(frames)[1]\n audio = audio[indices[0]:indices[-1]] if indices.size else audio[0:0]\n\n return audio, sr\n\nfilename = 'F:/项目/花城音乐项目/样式数据/ALL/旋律/1.31MP3/旋律1.100分.wav'\n#y, sr = load_and_trim('F:/项目/花城音乐项目/样式数据/ALL/旋律/1.31MP3/旋律1.100分.wav')\ny, sr = load_and_trim(filename)\nhop_length = 1048\n#chromagram = librosa.feature.chroma_cqt(y, sr=sr, hop_length=hop_length)\nchromagram = librosa.feature.chroma_cqt(y, sr=sr)\n# chromagram[11,:] = 1\nplt.figure(figsize=(15, 5))\n\n# 原始音色图\n# librosa.display.specshow(chromagram, x_axis='time', y_axis='chroma', cmap='coolwarm')\n# plt.colorbar()\n# plt.show()\n\nc_max = np.argmax(chromagram,axis=0)\nprint(c_max.shape[0])\nprint(c_max)\nc_max_diff = np.diff(c_max) # 一阶差分\nprint(np.diff(c_max))\nprint(c_max_diff.shape)\n\nimg = np.zeros(chromagram.shape,dtype=np.float32)\nw,h = chromagram.shape\nfor x in range(len(c_max_diff)):\n #img.item(x, c_max[x], 0)\n if x > 0 and (c_max_diff[x] == 1 or c_max_diff[x] == -1):\n c_max[x] = c_max[x-1]\n\nfor x in range(h):\n #img.item(x, c_max[x], 0)\n img.itemset((c_max[x],x), 0.5)\n img.itemset((c_max[x],x), 0.5)\n img.itemset((c_max[x],x), 0.5)\n\n# 最强音色图\n# librosa.display.specshow(img, x_axis='time', cmap='coolwarm')\n\n# 音频时长\ntime = librosa.get_duration(y)\nprint(\"time is {}\".format(time))\n# 节拍点\nonsets_frames = librosa.onset.onset_detect(y)\nprint(onsets_frames)\n\n# 节拍时间点\nonstm = librosa.frames_to_time(onsets_frames, sr=sr)\nprint(onstm)\n#plt.rcParams['figure.figsize'] = (2.0, 2.0) # 设置figure_size尺寸\n#plt.rcParams['savefig.dpi'] = 28 #图片像素\n#plt.rcParams['figure.dpi'] = 28 #分辨率\n#librosa.display.specshow(librosa.amplitude_to_db(D))\n#plt.vlines(onstm, 0, sr, color='r', linestyle='dashed')\n#plt.colorbar()\n\ncode = '[500,500,1000;500,500,1000;500,500,750,250;2000]'\npitch_code = '[3,3,3,3,3,3,3,5,1,2,3]'\npitch_v = get_chroma_pitch(pitch_code)\nonsets_base_frames = onsets_base_frames(code,h)\nonsets_base_frames[-1] = onsets_base_frames[-1]-1\nprint(onsets_base_frames)\nprint(np.diff(onsets_base_frames))\nprint(pitch_v)\nv0 = 0\nfor i,v in enumerate(onsets_base_frames[1:]):\n print(\"v0,v is {},{},{}\".format(v0,v,pitch_v[i]))\n if v == 337:\n print('=====')\n for f in range(v0,v):\n if img.item(pitch_v[i],f) == 0.5:\n img.itemset((pitch_v[i],f), 1)\n img.itemset((pitch_v[i],f), 1)\n img.itemset((pitch_v[i],f), 1)\n else:\n img.itemset((pitch_v[i], f), 0.8)\n img.itemset((pitch_v[i], f), 0.8)\n img.itemset((pitch_v[i], f), 0.8)\n v0 = v\n\nstart_point = 0.02\nds = onsets_base(code,time,start_point)\nprint(\"ds is {}\".format(ds))\nplt.vlines(ds, 0, sr, color='b', linestyle='solid')\nlibrosa.display.specshow(img, x_axis='time', cmap='coolwarm')\n#librosa.display.specshow(chromagram, x_axis='time', cmap='coolwarm')\nplt.show()\n","sub_path":"raw_feature/chroma_cqt_onsets_v2.py","file_name":"chroma_cqt_onsets_v2.py","file_ext":"py","file_size_in_byte":3394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"576531190","text":"import unittest\n\nfrom .base import CensysAPIBase, CensysIndex, CensysException\n\n\nclass CensysCertificates(CensysIndex):\n\n INDEX_NAME = \"certificates\"\n MAX_PER_BULK_REQUEST = 50\n\n def __init__(self, *args, **kwargs):\n CensysIndex.__init__(self, *args, **kwargs)\n self.bulk_path = \"/bulk/{}\".format(self.INDEX_NAME)\n\n def bulk(self, fingerprints):\n result = dict()\n start = 0\n end = self.MAX_PER_BULK_REQUEST\n while start < len(fingerprints):\n data = {\n \"fingerprints\": fingerprints[start:end]\n }\n result.update(self._post(self.bulk_path,data=data))\n start = end\n end += self.MAX_PER_BULK_REQUEST\n\n return result\n\n\nclass CensysCertificatesTests(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls._api = CensysCertificates()\n\n def testGet(self):\n queriedFp = \"fce621c0dc1c666d03d660472f636ce91e66e96460545f0da7eb1a24873e2f70\"\n res = self._api.view(queriedFp)\n self.assertIsInstance(res, dict)\n self.assertEqual(res[\"parsed\"][\"fingerprint_sha256\"], queriedFp)\n \n\n def testSearch(self):\n # searching for something that won't change hopefully\n x = self._api.search(\"fce621c0dc1c666d03d660472f636ce91e66e96460545f0da7eb1a24873e2f70\", \n fields=[\"parsed.subject_dn\",\n \"parsed.fingerprint_sha256\"],\n max_records=1)\n result = list(x)\n self.assertEqual(len(result), 1)\n self.assertIn(\"parsed.subject_dn\", result[0])\n self.assertIn(\"parsed.fingerprint_sha256\", result[0])\n\n def testBulk(self):\n x = self._api.bulk([\"fce621c0dc1c666d03d660472f636ce91e66e96460545f0da7eb1a24873e2f70\"])\n\n self.assertEqual(len(x.keys()), 1)\n self.assertIn(\"fce621c0dc1c666d03d660472f636ce91e66e96460545f0da7eb1a24873e2f70\", x)\n\n # def testMultiplePages(self):\n # q = \"parsed.extensions.basic_constraints.is_ca: true AND parsed.signature.self_signed: false\"\n # x = self._api.search(q, page=1)\n # y = self._api.search(q, page=2)\n # self.assertNotEqual(list(x), list(y))\n\n # def testReport(self):\n # print self._api.report(\"*\", \"parsed.subject_key_info.key_algorithm.name\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"censys/certificates.py","file_name":"certificates.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"355592544","text":"import os\nimport torch\nimport imageio\nimport numpy as np\nimport time\nimport argparse\n\nfrom mayavi import mlab\nfrom dist_chamfer_3D import chamfer_3DDist\nfrom one_nearest_neighbor_acc import NNA\n\n# HOME PATH\nHOME_PATH = '/home/user/'\n#HOME_PATH = '/home/porous/tensorbox/'\n\n# paths to input BEV and FOV images\n# DATASET SPLITS\nKITTI_TEST_SPLIT_DIR = os.path.join(HOME_PATH, 'work/master_thesis/code/split_datasets/output/global_dataset_splits/kitti_training_files_test.txt')\nLYFT_TEST_SPLIT_DIR = os.path.join(HOME_PATH, 'work/master_thesis/code/split_datasets/output/global_dataset_splits/lyft_valid_full_test.txt')\nAUDI_TEST_SPLIT_DIR = os.path.join(HOME_PATH, 'work/master_thesis/code/split_datasets/output/global_dataset_splits/audi_valid_full_test.txt')\n\n# BEV\nBEV_DIR_KITTI = os.path.join(HOME_PATH, 'work/master_thesis/datasets/bev_images/kitti/training')\nBEV_DIR_LYFT = os.path.join(HOME_PATH, 'work/master_thesis/datasets/bev_images/lyft_kitti')\nBEV_DIR_LYFT2KITTI = os.path.join(HOME_PATH, 'work/master_thesis/datasets/bev_images/lyft2kitti')\nBEV_DIR_AUDI = os.path.join(HOME_PATH, 'work/master_thesis/datasets/bev_images/audi')\nBEV_DIR_AUDI2KITTI = os.path.join(HOME_PATH, 'work/master_thesis/datasets/bev_images/audi2kitti')\n\n# FOV\nFOV_DIR_KITTI = os.path.join(HOME_PATH, 'work/master_thesis/code/yolov3/kitti/images')\nFOV_DIR_KITTI_CROPPED = os.path.join(HOME_PATH, 'work/master_thesis/code/yolov3/kitti/images_cropped')\nFOV_DIR_LYFT = os.path.join(HOME_PATH, 'work/master_thesis/code/yolov3/lyft/images')\nFOV_DIR_LYFT2KITTI = os.path.join(HOME_PATH, 'work/master_thesis/code/yolov3/lyft2kitti/images')\nFOV_DIR_AUDI = os.path.join(HOME_PATH, 'work/master_thesis/code/yolov3/audi/images')\nFOV_DIR_AUDI2KITTI = os.path.join(HOME_PATH, 'work/master_thesis/code/yolov3/audi2kitti/images')\n\n\ndef get_dataset_files(dataset, type):\n file_list_path = None\n images_dir_fov = None\n images_dir_bev = None\n images_dir = None\n transformation = None\n file_ending = None\n if dataset == 'kitti':\n file_list_path = KITTI_TEST_SPLIT_DIR\n images_dir_fov = FOV_DIR_KITTI\n images_dir_bev = BEV_DIR_KITTI\n file_ending = '.png'\n elif dataset == 'kitti_cropped':\n file_list_path = KITTI_TEST_SPLIT_DIR\n images_dir_fov = FOV_DIR_KITTI_CROPPED\n images_dir_bev = BEV_DIR_KITTI\n file_ending = '.png'\n elif dataset == 'lyft':\n file_list_path = LYFT_TEST_SPLIT_DIR\n images_dir_fov = FOV_DIR_LYFT\n images_dir_bev = BEV_DIR_LYFT\n file_ending = '.png'\n elif dataset == 'lyft2kitti2':\n file_list_path = LYFT_TEST_SPLIT_DIR\n images_dir_fov = FOV_DIR_LYFT2KITTI\n images_dir_bev = BEV_DIR_LYFT2KITTI\n file_ending = '.npy.png'\n elif dataset == 'audi':\n file_list_path = AUDI_TEST_SPLIT_DIR\n images_dir_fov = FOV_DIR_AUDI\n images_dir_bev = BEV_DIR_AUDI\n file_ending = '.png'\n elif dataset == 'audi2kitti':\n file_list_path = AUDI_TEST_SPLIT_DIR\n images_dir_fov = FOV_DIR_AUDI2KITTI\n images_dir_bev = BEV_DIR_AUDI2KITTI\n file_ending = '.npy.png'\n else:\n print(\"Error: unknown dataset '%s'\" % dataset)\n exit()\n\n # select type\n if type == 'bev':\n images_dir = images_dir_bev\n transformation = bev_to_pointcloud\n elif type == 'fov':\n images_dir = images_dir_fov\n transformation = fov_to_pointcloud\n else:\n print(\"Error: Unknown type '%s'\" % type)\n exit()\n return file_list_path, images_dir, transformation, file_ending\n\n\ndef get_images_list(file_list_path):\n return open(file_list_path, 'r').read().splitlines()\n\n\ndef mean_filter(img, filter_size):\n y_times = int(img.shape[0] / filter_size)\n x_times = int(img.shape[1] / filter_size)\n img_filtered = np.zeros((y_times, x_times))\n for y in range(y_times):\n index_y = y * filter_size\n for x in range(x_times):\n index_x = x * filter_size\n img_filtered[y, x] = np.mean(img[index_y:index_y + filter_size, index_x:index_x + filter_size])\n return img_filtered\n\n\ndef fov_to_pointcloud(fov_img):\n # extract mean values of every nxn subarray to undo pixel augmentation\n n = 4\n fov_img_filtered = mean_filter(fov_img, n)\n\n num_points = np.count_nonzero(fov_img_filtered)\n # extract values for each dimension\n x, y = np.nonzero(fov_img_filtered > 0)\n # Audi's FOV got cut horizontally, thats why we have to align it to compared KITTI-coordinates by an x shift\n z = fov_img_filtered[fov_img_filtered > 0] / 256 * 800\n # save to pointcloud\n fov_pc = np.zeros(shape=(3, num_points))\n fov_pc[0, :] = x\n fov_pc[1, :] = y\n fov_pc[2, :] = z\n #print(\"X: min: %s, max: %s\" % (np.amin(x), np.amax(x)))\n #print(\"Y: min: %s, max: %s\" % (np.amin(y), np.amax(y)))\n #print(\"Z: min: %s, max: %s\" % (np.amin(z), np.amax(z)))\n\n return fov_pc\n\n\ndef bev_to_pointcloud(bev_img_rgb):\n bev_img = bev_img_rgb[:, :, 1] # extract height values\n num_points = np.count_nonzero(bev_img)\n # extract values for each dimension\n z, y = np.nonzero(bev_img > 0)\n x = bev_img[bev_img > 0] / 256 * 50\n # save to pointcloud\n bev_pc = np.zeros(shape=(3, num_points))\n bev_pc[0, :] = x\n bev_pc[1, :] = y\n bev_pc[2, :] = z\n #print(\"X: min: %s, max: %s\" % (np.amin(x), np.amax(x)))\n #print(\"Y: min: %s, max: %s\" % (np.amin(y), np.amax(y)))\n #print(\"Z: min: %s, max: %s\" % (np.amin(z), np.amax(z)))\n return bev_pc\n\n\ndef visualize_pointcloud(pointcloud):\n mlab.figure()\n x = pointcloud[1, :]\n y = pointcloud[0, :]\n z = pointcloud[2, :]\n colors = 1.0 * (x + y) / (max(x) + max(y))\n nodes = mlab.points3d(x, y, z, scale_factor=0.5)\n nodes.glyph.scale_mode = 'scale_by_vector'\n nodes.mlab_source.dataset.point_data.scalars = colors\n mlab.show()\n\n\ndef print_statistics(num_points_list):\n num_points_list_np = np.asarray(num_points_list)\n print(\"TOTAL: \", len(num_points_list))\n print(\"MIN: \", np.amin(num_points_list_np))\n print(\"MAX: \", np.amax(num_points_list_np))\n print(\"MEAN: \", np.mean(num_points_list_np))\n\n\ndef compare_pointcloud_domains(a, b):\n chamfer_dist = chamfer_3DDist()\n #a = None # deine generierten Punktwolken als torch tensor mit shape = (anzahl der punktwolken, anzahl der Punkte, dimension(3))\n #b = None # orginal Punktwolken als torch tensor mit shape = (anzahl der punktwolken, anzahl der Punkte, dimension(3))\n return NNA(a, b, chamfer_dist) # output ist dann ein Wert theoretisch zwischen 0 und 1, praktisch aber zwischen 0.5 und 1. Wobei näher an 0.5 besser ist. Gibt im grunde an, wie viel prozent werden ihrer eigenen Gruppe wieder zugeordnet.\n\n\ndef main(dataset, type, optional_output_path):\n #dataset = 'kitti' # kitti, lyft, audi, lyft2kitti2, audi2kitti\n #type = 'fov' # bev, fov\n print(\"Comparing %s images of %s dataset:\" % (type, dataset))\n file_list_path, images_dir, transformation, file_ending = get_dataset_files(dataset, type)\n images_list = get_images_list(file_list_path)\n num_points_list = []\n pc_domain1_tensor_list, pc_domain2_tensor_list = [], []\n\n # if parameter 'optional_output_path' is set, then overwrite default path of input images\n if optional_output_path is not None:\n images_dir = optional_output_path\n\n # exit program, if CUDA isn't available since chamfer distance function requires this\n if torch.cuda.is_available():\n device = torch.device(\"cuda\")\n else:\n print(\"ERROR: CUDA is not available\")\n exit()\n\n # load FOV images of chosen dataset and reproject them into 3D pointclouds\n for image_filename in images_list:#[:2]:\n # load image\n #image_filename = images_list[0]\n #image_filename = '000000'\n #image_filename = '20181016125231_lidar_frontcenter_000056118'\n image_path = os.path.join(images_dir, image_filename) + file_ending\n #print(\"IMAGE_PATH: \", image_path)\n img = imageio.imread(image_path)\n\n # transform image to pointcloud\n pointcloud = transformation(img)\n\n # if pointcloud has no points, then skip to next\n if pointcloud.shape[1] > 0:\n # add number of points in pointcloud to list\n num_points_list.append(pointcloud.shape[1])\n\n # transform pointcloud to tensor and add it to domain1 list\n #print(\"TYPE: \", pointcloud.dtype)\n #print(\"SIZE: \", pointcloud.shape)\n #if pointcloud.dtype != np.float64:\n # print(\"DIFFERENT DTYPE: \", pointcloud.dtype)\n # exit()\n pointcloud_tensor = torch.empty(1, pointcloud.shape[1], 3)#, dtype=torch.float64)\n pointcloud_tensor[0, :, :] = torch.from_numpy(np.swapaxes(pointcloud, 0, 1)) # also swap axes of numpy array to fit tensor's shape\n pointcloud_tensor = pointcloud_tensor.to(device) # transform tensor to cuda tensor\n pc_domain1_tensor_list.append(pointcloud_tensor)\n\n # visualize created pointcloud\n #visualize_pointcloud(pointcloud)\n #exit()\n\n # print min, max and mean number of reprojected pointclouds\n #print_statistics(num_points_list)\n\n # load KITTI FOV images and reproject them into 3D pointclouds\n if not dataset.startswith('audi'):\n file_list_kitti_path, images_kitti_dir, transformation_kitti, file_ending_kitti = get_dataset_files('kitti', type)\n else:\n # take cropped images, if audi or audi2kitti is selected\n file_list_kitti_path, images_kitti_dir, transformation_kitti, file_ending_kitti = get_dataset_files('kitti_cropped', type)\n images_list_kitti = get_images_list(file_list_kitti_path)\n for image_filename in images_list_kitti:#[:2]:\n image_path_kitti = os.path.join(images_kitti_dir, image_filename) + file_ending_kitti\n img_kitti = imageio.imread(image_path_kitti)\n pointcloud_kitti = transformation_kitti(img_kitti)\n\n # if pointcloud has no points, then skip to next\n if pointcloud_kitti.shape[1] > 0:\n # transform pointcloud to tensor and add it to domain2 list\n pointcloud_kitti_tensor = torch.empty(1, pointcloud_kitti.shape[1], 3, dtype=torch.float)\n pointcloud_kitti_tensor[0, :, :] = torch.from_numpy(np.swapaxes(pointcloud_kitti, 0, 1)) # also swap axes of numpy array to fit tensor's shape\n pointcloud_kitti_tensor = pointcloud_kitti_tensor.to(device) # transform tensor to cuda tensor\n pc_domain2_tensor_list.append(pointcloud_kitti_tensor)\n\n # compare point cloud domains by one-nearest-neighbor method with chanfer distance\n start = time.process_time()\n nna_result = compare_pointcloud_domains(pc_domain1_tensor_list, pc_domain2_tensor_list)\n print(\"Time needed to compare %s pointclouds (%s: %s, KITTI: %s): %s min\" % (type, dataset, len(images_list), len(images_list_kitti), (time.process_time() - start)/60))\n\n print(\"NNA RESULT: %s\\n\" % nna_result)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--dataset', type=str, default=None, help=\"Dataset of validation pointclouds, which should be compared with KITTI validation pointclouds ('kitti', 'lyft', 'lyft2kitti', 'audi', 'audi2kitti'\")\n parser.add_argument('--type', type=str, default=None, help=\"'bev' or 'fov'\")\n parser.add_argument('--optional_output_path', type=str, default=None, help=\"optional alternative path for input images\")\n opt = parser.parse_args()\n print(opt)\n main(opt.dataset, opt.type, opt.optional_output_path)\n","sub_path":"compare_pointclouds.py","file_name":"compare_pointclouds.py","file_ext":"py","file_size_in_byte":11610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"608090946","text":"\"\"\"Changed File file \n\nRevision ID: 7ea710fe5e78\nRevises: 22627e9d9e06\nCreate Date: 2020-07-19 10:45:39.859518\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '7ea710fe5e78'\ndown_revision = '22627e9d9e06'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('files', sa.Column('file', sa.LargeBinary(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('files', 'file')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/7ea710fe5e78_changed_file_file.py","file_name":"7ea710fe5e78_changed_file_file.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"524834312","text":"# -*- coding: utf-8 -*-\n\nimport csv\nimport glob\nimport logging\n\nfrom django.core.management.base import BaseCommand\n\nfrom sepomex.models import MXEstado, MXMunicipio\nfrom sepomex.settings import FIELDNAMES\n\nlog = logging.getLogger('sepomex')\n\n\nfiles = glob.glob('data/municipalities/*txt')\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n municipalities = []\n for name in files:\n with open(name, encoding='latin-1') as municipalities_file:\n reader = csv.DictReader(municipalities_file,\n delimiter='|',\n fieldnames=FIELDNAMES)\n municipality = next(reader)\n state = MXEstado.objects.get(id=municipality['c_estado'])\n\n municipalities.append(\n MXMunicipio(nombre=municipality['D_mnpio'],\n clave=municipality['c_mnpio'],\n mx_estado=state\n )\n )\n\n MXMunicipio.objects.bulk_create(municipalities)\n\n log.info(u'{} municipios creados!'.format(len(municipalities)))\n","sub_path":"sepomex/management/commands/loadmxmunicipalities.py","file_name":"loadmxmunicipalities.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"294994439","text":"'''\n'''\nimport time\nimport datetime\nimport re\nimport pygame\n\n\ndef setAlarm():\n print(\"Hello, what time would you like the alarm to sound? Please input in this format\\ne.g. 7:45pm\\n\")\n time = input(\"Time: \")\n\n splitTime = re.compile(r'(\\d+?)(:)(\\d+?)(pm|am)') #split up time inputted for manipulation\n timeRe = splitTime.search(time)\n\n hour = int(timeRe.group(1))\n minutes = int(timeRe.group(3))\n dayOfTime = timeRe.group(4).lower() #set pm or am to lowercase for ease\n\n #errorChecking for proper time format\n if hour > 12 or hour < 1:\n print(\"Please input your time properly, in 12 hour time\")\n setAlarm()\n\n if minutes > 59 or minutes < 0:\n print(\"Please input your time properly\")\n setAlarm()\n\n\n #if time of day is pm, then reassign all values from 1pm - 11:59pm as 13, 14, 15, etc 24 hour.\n if dayOfTime == \"pm\" and hour != 12:\n convertedHour = hour + 12\n\n else:\n convertedHour = hour\n\n if dayOfTime == \"am\" and hour == 12:\n convertedHour = 24\n\n finalTime = str(convertedHour) + \":\" + str(minutes)\n print(finalTime)\n return finalTime\n\n\n\ndef clockCheck():\n #get the hour and time from setAlarm\n splitTime = re.compile(r'(\\d+?)(:)(\\d+)')\n timeRe = splitTime.search(setAlarm())\n alarmHour = int(timeRe.group(1))\n alarmMinute = int(timeRe.group(3))\n\n #get the live time\n now = datetime.datetime.now()\n currentHour = now.hour\n currentMinute = now.minute\n currentSecond = now.second\n\n\n while True:\n if currentHour != alarmHour:\n time.sleep(60-currentSecond) #if this isn't done, the alarm could be off by a couple seconds. Line's up things\n time.sleep((60*60) - (60*(currentMinute-1))) #this sleeps the program until the next hour is hit and reruns a check\n now = datetime.datetime.now()\n currentHour = now.hour\n elif currentMinute != alarmMinute:\n time.sleep(60-currentSecond) #sleep until the next minute and rerun the check\n now = datetime.datetime.now()\n currentMinute = now.minute\n currentSecond = now.second\n else:\n break\n alarmSound()\n\n\ndef alarmSound():\n import pygame\n pygame.mixer.init()\n pygame.mixer.music.load(\"/Users/michaelpresman/PycharmProjects/AlarmClock/sound.wav\")\n pygame.mixer.music.play(0)\n while pygame.mixer.music.get_busy():\n pygame.time.Clock().tick(10)\n\ndef main():\n clockCheck()\n\nmain()","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"173936309","text":"# Import libraries\nfrom pyathena import connect\nfrom pyathena.pandas.cursor import PandasCursor\nfrom pyathena.pandas.util import as_pandas\nimport boto3\nfrom botocore.client import ClientError\nimport pandas as pd\n\ns3 = boto3.resource('s3')\nclient = boto3.client(\"sts\")\naccount_id = client.get_caller_identity()[\"Account\"]\nmy_session = boto3.session.Session()\nregion = my_session.region_name\nathena_query_results_bucket = 'aws-athena-query-results-'+account_id+'-'+region\n\ntry:\n s3.meta.client.head_bucket(Bucket=athena_query_results_bucket)\nexcept ClientError:\n bucket = s3.create_bucket(Bucket=athena_query_results_bucket)\n print('Creating bucket '+athena_query_results_bucket)\ncursor = connect(s3_staging_dir='s3://'+athena_query_results_bucket+'/athena/temp').cursor(PandasCursor)\n\n# The above code comes directly from aline-awsathena.ipynb in the MIMIC-III starter code\n\ndef loinc_values(lab_item_ids) -> pd.DataFrame:\n statement = \"\"\"\n SELECT \n lab_events.itemid lab_item_id, \n lab_events.value\n FROM mimiciii.labevents lab_events\n WHERE B.itemid IN ({});\n \"\"\".format(str(lab_item_ids)[1:-1])\n df = cursor.execute(statement).as_pandas()\n return df","sub_path":"dataproc/embeddings.py","file_name":"embeddings.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"567566241","text":"\nimport unittest\n\nimport threading\nimport time\n\n\nfrom py3irc.mypyirc.bridgebot import *\nfrom py3irc.mypyirc.ircdefine import SEP\n\n\nclass MyPyIrcBotConnTestCase(unittest.TestCase):\n\tdef test_connection(self):\n\t\tcanal = \"#unittest\"\n\t\tself.bot = MyPyIrcBot(\"localhost\", 6667, \"unittestbot\", [canal])\n\t\t\n\t\tt = threading.Thread(target=self.bot.start)\n\t\tt.setDaemon(True)\n\t\tt.start()\n\t\t\n\t\tself.bot.wait_connection(5)\n\t\tself.assertTrue(self.bot.e_welcome.is_set())\n\n\tdef tearDown(self):\n\t\tself.bot.stop()\n\t\t\n\n\n\nclass MyPyIrcBotParseTestCase(unittest.TestCase):\n\tdef setUp(self):\n\t\tself.bot = BridgeBot(\"localhost\", 6667, \"unittestbot\", \"unittest\", None, None)\n\n\tdef test_get_protocol(self):\n\t\tstr_protocol = \"\"\"\n\t\t\t#define SEP\t\t'#'\n\t\t\t/**\n\t\t\t\tUn commentaire\n\t\t\t\t@param a\n\t\t\t\t@param b\n\t\t\t*/\n\t\t\t#define Q_PING\t\t\t0\n\t\t\t\n\t\t\t/**\n\t\t\t\tUn commentaire\n\t\t\t*/\n\t\t\t#define Q2_PING2\t\t\t42\n\t\t\"\"\"\n\t\tsep,commands = self.bot.get_protocol(str_protocol, \"Q_\")\n\t\tself.assertEqual(sep,'#')\n\t\tself.assertEqual(len(commands), 1)\n\t\tcmd = commands[0]\n\t\tself.assertEqual(cmd['id'], 0)\n\t\tself.assertEqual(cmd['name'], \"PING\")\n\t\tself.assertEqual(cmd['params'], ['a', 'b'])\n\t\tself.assertIsNotNone(cmd['doc'])\n\n\tdef test_get_protocol2(self):\n\t\tstr_protocol = \"\"\n\t\tself.assertRaises(ProtocolException, self.bot.get_protocol, str_protocol, \"Q_\")\n\t\t\n\n","sub_path":"unittests/py3irc_test/mypy3irc/bridgebot_test.py","file_name":"bridgebot_test.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"401426102","text":"\n\n\"\"\"O(NlogN) 解法\n約数をテーブルに保存していく\n\"\"\"\nN = int(input())\ntable = [0] * (N + 1)\nfor i in range(1, N + 1):\n for j in range(i, N + 1, i):\n table[j] += 1\nans = 0\nfor i in range(N):\n i += 1\n ans += i * table[i]\nprint(ans)\n\n\n\"\"\" O(N) 解法\nhttps://www.youtube.com/watch?v=v8ppNGf49Nk&t=7059s\n\"\"\"\ndef f(n):\n return n * (n+1) // 2\n\nN = int(input())\nans = 0\nfor i in range(N):\n i += 1\n ans += i * f(N//i)\nprint(ans)\n","sub_path":"abc/172/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"187842758","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: ./pyas2/migrations/0017_auto_20170404_0730.py\n# Compiled at: 2017-08-17 00:05:08\nfrom __future__ import unicode_literals\nfrom django.db import migrations, models\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('pyas2', '0016_auto_20161004_0543')]\n operations = [\n migrations.AlterField(model_name=b'partner', name=b'mdn', field=models.BooleanField(default=False, verbose_name=b'Request MDN'))]","sub_path":"pycfiles/pyas2lib-1.3.1-py3-none-any/0017_auto_20170404_0730.py","file_name":"0017_auto_20170404_0730.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"103307633","text":"# -*- coding: utf-8 -*-\n\nfrom sys import argv\n\nscript, user_name = argv # pylint: disable=unbalanced-tuple-unpacking \nprompt = '>'\n\nprint('Привет %s, Я - сценарий %r.' % (user_name, script))\nprint('Я хочу задать тебе несколько вопросов.')\nlikes = input('%s Я тебе нравлюсь, %s? ' % (prompt, user_name))\nlives = input('%s Где Вы живете, %s? ' % (prompt, user_name))\ncomputer = input('%s На каком кампьютере Вы работаете, %s? ' %\n (prompt, user_name))\n\nprint(\"\"\"\nИ так, Вы ответила %r на вопрос, нравлюсь ли я Вам.\nВы живете в %r. Не представляю где это.\nИ у Вас есть компьютер %r. Прекрасно!\n\"\"\" % (likes, lives, computer))\n","sub_path":"ex14.py","file_name":"ex14.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"4401071","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n10001st prime\n \nProblem 7\nBy listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.\n\nWhat is the 10 001st prime number?\n\nWe do this by making a \"sieve or Erasthones\"\n\"\"\"\nimport numpy as np\n\nN=2000000\nprimes_list = np.arange(N+1) # a list with the i-th entry equal to i.\n\nprimes_list[1]=0\n\n# to test if a number is prime, you only need to test for divisors up to \n# the square root...\nmax_test = int(N**(0.5)) \n\nfor i in range(2,max_test):\n #print(i,primes_list)\n if primes_list[i] != 0: # then i is prime. Need to eliminate multiples...\n for j in range(2,N//i+1):\n primes_list[j*i]=0 \n\n# this gets rid of the zero elements...\nprimes_list = primes_list[primes_list != 0] \n\nprint(primes_list[10000])\n\n","sub_path":"Project Euler/PE-007.py","file_name":"PE-007.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"259244074","text":"import torch\nfrom torchvision import datasets, transforms\nimport torchvision.models as models\n\nfrom KD_Lib.Quantization import Dynamic_Quantizer, Static_Quantizer, QAT_Quantizer\nfrom KD_Lib.models import ResNet18\n\n\ntrain_loader = torch.utils.data.DataLoader(\n datasets.MNIST(\n \"mnist_data\",\n train=True,\n download=True,\n transform=transforms.Compose(\n [transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]\n ),\n ),\n batch_size=4,\n shuffle=True,\n)\n\ntest_loader = torch.utils.data.DataLoader(\n datasets.MNIST(\n \"mnist_data\",\n train=False,\n transform=transforms.Compose(\n [transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]\n ),\n ),\n batch_size=4,\n shuffle=True,\n)\n\n\ndef test_dynamic_quantization():\n\n model_params = [4, 4, 8, 4, 4]\n model = ResNet18(model_params, 1, 10, True)\n quantizer = Dynamic_Quantizer(model, test_loader, {torch.nn.Linear})\n quantized_model = quantizer.quantize()\n quantizer.get_model_sizes()\n quantizer.get_performance_statistics()\n\n del model, quantizer, quantized_model\n\n\ndef test_static_quantization():\n\n model = models.quantization.resnet18(quantize=False)\n model.fc.out_features = 10\n quantizer = Static_Quantizer(model, train_loader, test_loader)\n quantized_model = quantizer.quantize(1)\n quantizer.get_model_sizes()\n quantizer.get_performance_statistics()\n\n del model, quantizer, quantized_model\n\n\ndef test_qat_quantization():\n\n model = models.quantization.resnet18(quantize=False)\n model.fc.out_features = 10\n optimizer = torch.optim.Adam(model.parameters())\n quantizer = QAT_Quantizer(model, train_loader, test_loader, optimizer)\n quantized_model = quantizer.quantize(1, 1, 1, 1)\n quantizer.get_model_sizes()\n quantizer.get_performance_statistics()\n\n del model, quantizer, quantized_model\n","sub_path":"tests/test_quantization.py","file_name":"test_quantization.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"622742979","text":"import json\nfrom .. import define\nfrom .. import interface\nfrom .. import mm_pb2\nfrom .. import Util\nfrom bs4 import BeautifulSoup\nfrom .logger_wrapper import logger\nfrom .tip_bot import tips\nfrom urllib.parse import urlencode\n\n# 图灵机器人接口\n# TULING_HOST = 'openapi.tuling123.com'\n# TULING_API = 'http://openapi.tuling123.com/openapi/api/v2'\n# 图灵机器人key\n# TULING_KEY = '460a124248234351b2095b57b88cffd2' # 460a124248234351b2095b57b88cffd2\n\n# 通过抓取网页体验地址得到聊天的接口\nTULING_HOST = 'biz.turingos.cn'\nTULING_API = 'http://biz.turingos.cn/apirobot/dialog/homepage/chat' # http://biz.turingos.cn/chat 体验地址\n\n# 图灵机器人\ndef tuling_robot(msg):\n # 本条消息是否回复\n need_reply = False\n # 消息内容预处理\n send_to_tuling_content = msg.raw.content\n reply_prefix = ''\n reply_at_wxid = ''\n # 群聊消息:只回复@自己的消息/消息内容过滤掉sender_wxid\n if msg.from_id.id.endswith('@chatroom'):\n # 首先判断本条群聊消息是否at我:\n try:\n soup = BeautifulSoup(msg.ex_info,'html.parser')\n at_user_list = soup.msgsource.atuserlist.contents[0].split(',')\n if Util.wxid in at_user_list: # 群聊中有@我的消息\n # 群聊消息以'sender_wxid:\\n'起始\n send_to_tuling_content = msg.raw.content[msg.raw.content.find('\\n') + 1:]\n # 解析@我的人的昵称\n reply_nick_name = Util.find_str(msg.xmlContent, ' 1:\n multi_msg = True\n\n # 自动回消息\n if (multi_msg):\n send_multi_msg(robot_ret['data'], msg, reply_prefix, reply_at_wxid)\n else:\n send_msg(message, msg, reply_prefix, reply_at_wxid)\n\n except Exception as e:\n logger.info('tuling api 调用异常!', 1)\n print(e)\n\n return\n\ndef send_msg(message, msg, reply_prefix, reply_at_wxid):\n if reply_prefix and reply_at_wxid:\n # 消息前缀: @somebody 并at发消息人\n message = (reply_prefix + ' ' + message)\n interface.new_send_msg(msg.from_id.id, message.encode(encoding=\"utf-8\"), [reply_at_wxid])\n else:\n interface.new_send_msg(msg.from_id.id, message.encode(encoding=\"utf-8\"))\n\ndef send_multi_msg(data, msg, reply_prefix, reply_at_wxid):\n for result in data['results']:\n if result['resultType'] == 'text':\n send_msg(result['values']['text'], msg, reply_prefix, reply_at_wxid)\n elif result['resultType'] == 'voice':\n intent = data['intent']\n parameters = intent['parameters']\n\n title = '请点击查看'\n desc = ''\n if intent['code'] == 200101: # 唱歌\n title = parameters['name']\n desc = parameters['singer']\n elif intent['code'] == 200701: # 跳舞\n title = parameters['song']\n desc = parameters['singer']\n elif intent['code'] == 200201: # 故事\n title = parameters['name']\n desc = parameters['author']\n\n interface.send_app_msg(msg.from_id.id, title, desc, result['values']['voice'], thumb_url='')\n\n","sub_path":"microchat/plugin/tuling_robot.py","file_name":"tuling_robot.py","file_ext":"py","file_size_in_byte":5622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"568396329","text":"import numpy as np\nimport torch\nfrom torch import nn as nn\n\nfrom rlkit.policies.base import Policy\nfrom rlkit.torch.core import eval_np\nimport rlkit.torch.pytorch_util as ptu\nfrom rlkit.torch.distributions.tanh_normal import TanhNormal\n\nclass TanhGaussianPolicy(Policy, nn.Module):\n \"\"\"\n Here, mean and log_std are the mean and log_std of the Gaussian that is\n sampled from.\n\n If deterministic is True, action = tanh(mean).\n \"\"\"\n def __init__(\n self,\n module,\n return_raw_action=False,\n log_std_max = 2,\n log_std_min = -20,\n ):\n super().__init__()\n self.module = module\n self.return_raw_action = return_raw_action\n self.log_std_max = log_std_max\n self.log_std_min = log_std_min\n\n def get_action(self, obs_np, deterministic=False):\n if self.return_raw_action:\n actions, raw_actions = self.get_actions(obs_np[None], deterministic=deterministic)\n return actions[0, :], {'raw_action':raw_actions[0,:]}\n else:\n actions = self.get_actions(obs_np[None], deterministic=deterministic)\n return actions[0, :], {}\n\n def get_actions(self, obs_np, deterministic=False):\n if self.return_raw_action:\n with torch.no_grad():\n actions, info = self.forward(torch.tensor(obs_np).float().to(ptu.device), deterministic=deterministic,return_info=True)\n raw_actions = info['preactivation']\n return np.array(actions.cpu()), np.array(raw_actions.cpu())\n else:\n return eval_np(self, obs_np, deterministic=deterministic)\n\n def forward(\n self,\n obs,\n reparameterize=True,\n deterministic=False,\n return_info=False,\n ):\n \"\"\"\n :param obs: Observation\n :param deterministic: If True, do not sample\n :param return_info: If True, return info\n \"\"\"\n mean, log_std = self.module(obs)\n log_std = torch.clamp(log_std, self.log_std_min, self.log_std_max)\n std = torch.exp(log_std)\n\n log_prob = None\n entropy = None\n pre_tanh_value = None\n\n tanh_normal = TanhNormal(mean, std)\n if deterministic:\n pre_tanh_value = mean\n action = torch.tanh(mean)\n else:\n # if return_log_prob:\n if reparameterize is True:\n action, pre_tanh_value = tanh_normal.rsample(\n return_pretanh_value=True\n )\n else:\n action, pre_tanh_value = tanh_normal.sample(\n return_pretanh_value=True\n )\n if return_info:\n log_prob = tanh_normal.log_prob(\n action,\n pre_tanh_value=pre_tanh_value\n )\n log_prob = log_prob.sum(dim=-1, keepdim=True)\n\n info = dict(\n mean=mean,log_std=log_std,log_prob=log_prob,entropy=entropy,\n preactivation=pre_tanh_value\n )\n\n if return_info:\n return action, info\n else:\n return action\n\n def log_prob(\n self,\n obs,\n action,\n raw_action=None\n ):\n \"\"\"\n :param obs: Observation\n :param action: Action\n \"\"\"\n mean, log_std = self.module(obs)\n log_std = torch.clamp(log_std, self.log_std_min, self.log_std_max)\n std = torch.exp(log_std)\n\n pre_tanh_value = raw_action\n\n tanh_normal = TanhNormal(mean, std)\n log_prob = tanh_normal.log_prob(\n action,\n pre_tanh_value=pre_tanh_value\n )\n log_prob = log_prob.sum(dim=-1, keepdim=True)\n\n return log_prob\n\n def get_distribution(self, obs):\n mean, log_std = self.module(obs)\n log_std = torch.clamp(log_std, self.log_std_min, self.log_std_max)\n std = torch.exp(log_std)\n return TanhNormal(mean, std)\n","sub_path":"rlkit/torch/policies/tanh_gaussian_policy.py","file_name":"tanh_gaussian_policy.py","file_ext":"py","file_size_in_byte":3981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"540046816","text":"import math,random;\n\nrunning = True;\n\n# Function to check if string can be converted to integer\ndef isInt(i):\n '''\n This function checks that 'i' can be converted to integer, by using try/except method,\n if value of 'i' can be converted to integer then True is returned, if not False is returned.\n\n Arguments: Function accepts any type of variable, in any format.\n\n Output: Function returns True/False, if conversion to integer has been sucessful/unsucessful.\n '''\n try:\n int(i);\n return True;\n except ValueError:\n return False;\n\nwhile running:\n choice = raw_input(\"\\nWhich tickable do you wanna see? \");\n\n if(not isInt(choice)):\n print(\"Please enter natural value\");\n else:\n int_choice = abs(int(choice));\n # 1st step tickable\n if(int_choice == 1):\n print(\"\\nPrinting simple message:\\nHello World!!\");\n # 2nd step tickable\n elif(int_choice == 2):\n print(\"\\nThere's no tickable number 2\");\n # 3rd step tickable\n elif(int_choice == 3):\n print(\"\\nDefining different data types, and printing them out\");\n\n num1 = 23\n print(\"Printing integer value stored in variable num1: \" + str(num1));\n\n num2 = 23.5\n print(\"Printing float value stored in variable num2: \" + str(num2));\n\n str1 = \"Hello world\";\n print(\"Printing string value stored in string str1: \"+ str1);\n # 4th step\n elif(int_choice == 4):\n print(\"\\n4th step is not a tickable\");\n # 5th step\n elif(int_choice == 5):\n print(\"\\nAssinging varable num to value of 5.2, then adding 7,\\nthen multiplying it by 300, then dividing by 4, and then cubing it\");\n num = 5.2;\n num += 7;\n num *= 300;\n num /= 4;\n num = num**3;\n print(\"Ans = \"+str(num));\n # 6h step\n elif(int_choice == 6):\n print(\"\\nManipulating strings\");\n\n str1 = \"This is a string that I will learn to manipulate\";\n str2 = \", string manipulation is very useful.\";\n\n # Combining strings\n string = str1 + str2;\n\n print(\"Combined string is: '\" + string + \"'.\\nIt's length is \" + str(len(string)) +\" characaters.\"\n +\"\\nCharacter at position 0 is \"+string[0]\n +\"\\nThe last character at position -1 is \" + string[-1]\n +\"\\nString of character between 3:7 is '\" + string[3:7] +\"'\");\n # 7th step\n elif(int_choice == 7):\n print(\"\\nThere's no tickable thing for step 7, but it's all about changing between diferent variable types\");\n # 8th step\n elif(int_choice == 8):\n print(\"\\nStep 8 doesn't have tickable thing, but it's about if statements\");\n # 9th step\n elif(int_choice == 9):\n print(\"\\nUsing raw_input function\");\n\n inLoop = True;\n while inLoop:\n userInput = raw_input(\"\\nPlease enter a string which is no more than 10 characters long (counting spaces)\"\n +\"\\nenter 'q' to stop: \");\n if(userInput == 'q'):\n break;\n elif(len(userInput)>10):\n print(userInput + \" is more than 10 characters, try again\");\n else:\n print(userInput + \" is less than 10 character long. 'q' to stop\");\n # 10th step\n elif(int_choice == 10):\n print(\"\\nThere's no tickable for step 10. For loop is introduced\");\n # 11th step\n elif(int_choice == 11):\n print(\"\\nPrinting sum of first integers less than 1000 that are not divisible by 3\"\n +\"\\nI did not use the example code given\");\n \n tmpSum = 0;\n for i in range(0,1000):\n if( i%3 != 0):\n tmpSum += i;\n print(\"Sum is = \" + str(tmpSum));\n # 12th step\n elif(int_choice == 12):\n print(\"\\n12th step is not a tickable. Introduction of while loop\");\n # 13th step\n elif(int_choice == 13):\n print(\"\\nFinding value of N, for when sum of i**2 is > 20'000\");\n\n tmpSum = 0;\n i = 0;\n limit = 20000;\n while(tmpSum <= limit):\n if(tmpSum + i**2 > limit):\n break;\n else:\n tmpSum += i**2;\n i += 1;\n print(\"Value of N is \" + str(i));\n # 14th step\n elif(int_choice == 14):\n print(\"\\nChecking the sequence, starting at x0 = 1\");\n\n kValue = int(raw_input(\"Enter value of K: \"));\n steps = int(raw_input(\"Number of itterations: \")); \n\n kTmp = kValue;\n xTmp = 1;\n\n for i in range(1, steps+1):\n xTmp = 0.5 * ( xTmp + (kTmp)/xTmp);\n print(\"K = \" + str(kTmp/xTmp) + \", sqrt(K) = \"+ str(math.sqrt(kValue)) + \"; itteration: \" + str(i));\n\n # 15 step\n elif(int_choice == 15):\n print(\"\\nSimple too high / too low game\");\n \n lowerBound = input(\"Please enter lower bound: \");\n upperBound = input(\"Please enter upper bound: \");\n\n rangeN = upperBound - lowerBound;\n\n if(rangeN <= 5):\n difficulty = \"easy\";\n elif(rangeN <= 20):\n difficulty = \"normal\";\n elif(rangeN <= 50):\n difficulty = \"hard\";\n elif(rangeN > 50):\n difficulty = \"impossible\";\n \n print(\"Can choose between \" + str(rangeN) + \" numbers. Difficulty = \" + difficulty);\n\n chosenNum = random.randint(lowerBound,upperBound);\n\n tries = 1;\n \n gotItRight = False;\n while(not gotItRight):\n guess = input(\"I think the number is = \");\n\n if( (guess > upperBound) or (guess < lowerBound)):\n print(\"Your guess isn't even the range you specified! [\" +str(lowerBound) +\",\"+str(upperBound)+\"]\");\n elif(guess > chosenNum):\n print(\"Too high!\");\n elif(guess < chosenNum):\n print(\"Too low!\");\n elif(guess == chosenNum):\n print(\"You did it!! It took you \" + str(tries) + \" tries!\");\n break;\n tries += 1;\n \n \n \n \n \n","sub_path":"week2.py","file_name":"week2.py","file_ext":"py","file_size_in_byte":6648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"274868308","text":"import Tkinter\n\n\n\ndef printGrid(matrix):\n\troot = Tkinter.Tk()\n\tcanvas = Tkinter.Canvas(root)\n\tcanvas.pack()\n\n\n\n\n\tfor x in range(0,100):\n\t\tfor y in range(0,100):\n\t\t\tif (x % 20 == 0) and (y % 20==0):\n\t\t\t\tcanvas.create_rectangle(x,y,x+20,y+20, fill=\"yellow\")\n\n\n\n\troot.mainloop()\n\nprintGrid(None)","sub_path":"1 - CA/Test 1 - original differentiation/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"372404760","text":"\"\"\"\nTODO:\n - Create Algorithm Class with methods : input, output (path), run\n - Create 3 algorithms A-star, BFS, UCS that inherit from Algorithm Class\n - Use Environment Class to draw and check the valid moves.\n\"\"\"\nfrom __future__ import print_function\nfrom environment import Environment\nfrom object import Polygon\nimport numpy as np\nimport heapq\n\nWMAX = 1e3\ndx = [-1, 0, 1, 1, 1, 0, -1, -1]\ndy = [1, 1, 1, 0, -1, -1, -1, 0]\n\nclass Algorithm():\n def __init__(self, xmax, ymax, start_point, end_point, polygon_list):\n self.E = Environment(xmax, ymax, start_point, end_point, polygon_list)\n self.start_point = start_point\n self.end_point = end_point\n self.path = []\n self.fre = {}\n self.trace = {}\n\n def output(self):\n pass\n\n def run(self):\n pass\n\n def imitate_environment(self):\n self.path = self.output()\n self.E.draw_environment()\n if (len(self.path) != 0):\n self.E.draw_path(self.path)\n self.E.end_draw()\n\nclass UCS(Algorithm):\n def __init__(self, xmax, ymax, start_point, end_point, polygon_list):\n super().__init__(xmax, ymax, start_point, end_point, polygon_list)\n self.d = {}\n for i in range(xmax + 1):\n for j in range(ymax + 1):\n self.d[(i, j)] = WMAX\n self.fre[(i, j)] = 1\n self.trace[(i, j)] = -1\n\n self.d[self.start_point] = 0\n\n def output(self):\n if (self.trace[self.end_point] == -1):\n print(\"There is no path from {} to {}\".format(self.start_point, self.end_point))\n return []\n else:\n print('Path from {} to {}:'.format(self.start_point, self.end_point))\n trace_path = []\n while (self.start_point != self.end_point):\n trace_path.append(self.end_point)\n self.end_point = self.trace[self.end_point]\n\n trace_path.append(self.start_point)\n # trace_path = reversed(trace_path)\n for p in trace_path:\n print(p)\n # print(trace_path)\n return np.array(trace_path)\n\n def run(self):\n print(\"UCS Algorithm:\\n\")\n pq = []\n heapq.heappush(pq, (0, self.start_point))\n while len(pq) > 0:\n w, p = heapq.heappop(pq)\n\n print(\"Choose \", p)\n print(\"Cost at choose point: \", self.d[p])\n\n if (self.fre[p] == 0): continue\n if (p == self.end_point): break\n\n px, py = p\n for i in range(8):\n next_p = (px + dx[i], py + dy[i])\n w_move = 1\n if ((i == 0) | (i == 2) | (i == 4) | (i == 6)): #cross move\n w_move = 1.5\n if ((self.E.is_valid_point(next_p) == True) & (self.E.is_valid_move(p, next_p))):\n if ((self.fre[next_p] == 1) & (self.d[next_p] > self.d[p] + w)):\n self.d[next_p] = self.d[p] + w_move\n heapq.heappush(pq, (self.d[next_p], next_p))\n self.trace[next_p] = p\n self.cost = self.d[self.end_point]\n print(\"Total Cost: \", self.cost)\n self.imitate_environment()\n\nif __name__ == '__main__':\n xmax, ymax = 22, 18\n start_point, end_point = (10, 1), (19, 16)\n polygon_point_list = np.array([[[4, 4], [5, 9], [8, 10], [9, 5]]\n , [[8, 12], [8, 17], [13, 12]]\n , [[11, 1], [11, 6], [14, 6], [14, 1]]\n , [[15, 11], [12, 9], [15, 6], [19, 10]]])\n\n polygon_list_object = np.array([])\n\n for polygon_coord in polygon_point_list:\n print(polygon_coord)\n P = Polygon(polygon_coord)\n polygon_list_object = np.append(polygon_list_object, [P])\n\n UCSAlgo = UCS(xmax, ymax, start_point, end_point, polygon_list_object)\n UCSAlgo.run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"433635414","text":"# -*- coding:utf-8 -*-\nfrom mako import runtime, filters, cache\nUNDEFINED = runtime.UNDEFINED\nSTOP_RENDERING = runtime.STOP_RENDERING\n__M_dict_builtin = dict\n__M_locals_builtin = locals\n_magic_number = 10\n_modified_time = 1463637607.393917\n_enable_loop = True\n_template_filename = 'G:/public_html/iutvalence-python-mangacollection/View/template/genre_list.html'\n_template_uri = 'genre_list.html'\n_source_encoding = 'utf-8'\n_exports = ['container']\n\n\ndef _mako_get_namespace(context, name):\n try:\n return context.namespaces[(__name__, name)]\n except KeyError:\n _mako_generate_namespaces(context)\n return context.namespaces[(__name__, name)]\ndef _mako_generate_namespaces(context):\n pass\ndef _mako_inherit(template, context):\n _mako_generate_namespaces(context)\n return runtime._inherit_from(context, 'base.html', _template_uri)\ndef render_body(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n __M_locals = __M_dict_builtin(pageargs=pageargs)\n def container():\n return render_container(context._locals(__M_locals))\n genres = context.get('genres', UNDEFINED)\n __M_writer = context.writer()\n __M_writer('\\r\\n')\n if 'parent' not in context._data or not hasattr(context._data['parent'], 'container'):\n context['self'].container(**pageargs)\n \n\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\ndef render_container(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n def container():\n return render_container(context)\n genres = context.get('genres', UNDEFINED)\n __M_writer = context.writer()\n __M_writer('\\r\\n
\\r\\n
\\r\\n
\\r\\n
\\r\\n')\n for genre in genres:\n __M_writer('
\\r\\n

')\n __M_writer(str(genre.genre))\n __M_writer('

\\r\\n

\\r\\n

\\r\\n
\\r\\n')\n __M_writer('
\\r\\n
\\r\\n
\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\n\"\"\"\n__M_BEGIN_METADATA\n{\"filename\": \"G:/public_html/iutvalence-python-mangacollection/View/template/genre_list.html\", \"line_map\": {\"35\": 2, \"52\": 3, \"53\": 8, \"54\": 9, \"55\": 10, \"56\": 10, \"57\": 15, \"27\": 0, \"45\": 3, \"63\": 57}, \"uri\": \"genre_list.html\", \"source_encoding\": \"utf-8\"}\n__M_END_METADATA\n\"\"\"\n","sub_path":"View/tmp/mako_modules/genre_list.html.py","file_name":"genre_list.html.py","file_ext":"py","file_size_in_byte":2657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"5777431","text":"import pandas as pd\n\n\ndef get_df(filepath, filetype='infer', index=None):\n if filetype == 'infer':\n filetype = filepath.split('.')[-1]\n\n # Read in file as DataFrame\n if filetype == 'csv':\n df = pd.read_csv(filepath)\n elif filetype == 'pickle' or filetype == 'pkl':\n df = pd.read_pickle(filepath)\n else:\n print(f\"Error, filetype {filetype} not understood.\")\n return -1\n\n # Set index\n if index:\n df = df.set_index(index)\n df.sort_index(ascending=True, inplace=True)\n\n return df\n\ndef concat_dfs(df1, df2, how='inner'):\n # Assumes DataFrames have the same index\n concatenated_df = pd.merge(df1, df2, how=how)\n\n return concatenated_df\n\ndef truncate_year_range(df, year_range):\n # Assumes 'df' indexed by Date\n return df[df['DecimalDate'].between(year_range[0], year_range[1])].copy()\n \ndef get_correlation(df, columns):\n # Pearson correlation coefficient\n corr_df = df[columns].copy()\n \n return corr_df.corr(method='pearson')\n","sub_path":"sadtools/utilities/dataframeUtilities.py","file_name":"dataframeUtilities.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"462890196","text":"import time\n\nimport dedupe\nimport pandas as pd\nimport recordlinkage as rl\nimport lightgbm as lgb\nimport numpy as np\n\nfrom clean_datasets_2 import clean_laptops_dataset as clean_x2\nfrom clean_datasets_3 import clean_laptops_dataset as clean_x3\nfrom record_linkage_dedupe_trainer_x4 import clean_products_dataset_dedupe as clean_x4_dedupe\nfrom record_linkage_dedupe_trainer_x4 import clean_products_dataset_rf as clean_x4_rf\n\nLOCAL = False\nNUM_CORES = 77\n\npartition_threshold = {\n 'x2': 0.3,\n 'x3': 0.3,\n 'x4': 0.37,\n}\n\n\ndef deduper_eval(dataset_type: str, dataset):\n # Create deduper model\n with open('../../trained_models/deduper/sub_5/trained_{}_settings.json'.format(dataset_type), 'rb') as fin:\n deduper = dedupe.StaticDedupe(fin, num_cores=8)\n\n # Prepare the data\n if dataset_type in ['x2', 'x3']:\n cols = [\n 'instance_id',\n 'brand',\n 'model_name',\n # 'model_number',\n 'cpu_brand',\n 'cpu_model',\n 'cpu_type',\n 'ram_capacity',\n 'hdd_capacity',\n 'ssd_capacity',\n 'title',\n 'screen_size',\n 'model']\n else:\n cols = ['name', 'brand', 'size', 'product_type']\n to_dedupe = dataset[cols]\n to_dedupe_dict = to_dedupe.to_dict(orient='index')\n\n # Cluster (prediction stage)\n clustered_dupes = deduper.partition(to_dedupe_dict, partition_threshold[dataset_type])\n print('# duplicate sets', len(clustered_dupes))\n\n # Save the result\n res = []\n for el in clustered_dupes:\n for i in range(len(el[0])):\n for j in range(i + 1, len(el[0])):\n res.append((el[0][i], el[0][j]))\n\n res_df = pd.DataFrame(res)\n res_df.columns = ['left_instance_id', 'right_instance_id']\n return res_df\n\n\ndef eval_lightgbm_dedupe(dataset_type: str, dataset_rf, dataset_dedupe):\n # Create deduper model\n with open('../../trained_models/combined_2/trained_{}_settings.json'.format(dataset_type), 'rb') as fin:\n deduper = dedupe.StaticDedupe(fin, num_cores=NUM_CORES)\n\n cols = ['name', 'brand', 'size', 'product_type']\n\n to_dedupe = dataset_dedupe[cols]\n to_dedupe_dict = to_dedupe.to_dict(orient='index')\n\n # Cluster (prediction stage)\n clustered_dupes = deduper.partition(to_dedupe_dict, partition_threshold[dataset_type])\n print('# duplicate sets', len(clustered_dupes))\n\n # Create the record linkage model\n # Indexer\n indexer = rl.Index()\n indexer.add(rl.index.Block('product_type'))\n indexer.add(rl.index.Block('brand'))\n indexer.add(rl.index.Block('size'))\n candidate_links = indexer.index(dataset_rf)\n\n # Comparing\n compare_cl = rl.Compare(n_jobs=-1)\n compare_cl.exact('brand', 'brand')\n compare_cl.exact('product_type', 'product_type')\n compare_cl.exact('size', 'size')\n compare_cl.string('name', 'name', method='qgram')\n compare_cl.string('name', 'name', method='damerau_levenshtein')\n compare_cl.string('name', 'name', method='levenshtein')\n compare_cl.string('name', 'name', method='jarowinkler')\n compare_cl.string('name', 'name', method='smith_waterman')\n compare_cl.string('name', 'name', method='lcs')\n # compare_cl.string('price', 'price')\n\n # Features\n features = compare_cl.compute(candidate_links, dataset_rf)\n\n # Add dedupe features\n features['xy_same_entity'] = pd.Series(np.zeros(len(features)))\n features.xy_same_entity = 0.0\n\n # Save the result\n for el in clustered_dupes:\n for i in range(len(el[0])):\n for j in range(i + 1, len(el[0])):\n k = (el[0][i], el[0][j])\n r_k = (el[0][j], el[0][i])\n p = el[1][i] * el[1][j]\n\n if k in features.index:\n features.loc[k, 'xy_same_entity'] = p\n\n if r_k in features.index:\n features.loc[r_k, 'xy_same_entity'] = p\n\n # Now load the lightgbm\n bst = lgb.Booster(model_file='../../trained_models/combined_2/x4_lgb_classifier.txt')\n\n # Predict\n confs = bst.predict(features)\n features['label'] = confs\n\n # Save the csv file\n # Now export the left and right instance ids\n # Save the result\n res = []\n for i in range(len(confs)):\n record = features.iloc[i]\n label = record.label\n if label > 0.5:\n res.append(record.name)\n\n res_df = pd.DataFrame(res)\n res_df.columns = ['left_instance_id', 'right_instance_id']\n\n return res_df\n\n\nif __name__ == '__main__':\n start_time = time.time()\n print(\"Start\")\n # Read the datasets\n s_x2 = pd.read_csv('../../data/sigmod/X2.csv')\n s_x3 = pd.read_csv('../../data/sigmod/X3.csv')\n s_x4 = pd.read_csv('../../data/sigmod/X4.csv')\n\n #\n # Reverse the shuffling effect\n #\n # Detect which one is x4\n rem = []\n if len(s_x2.columns) == 5:\n x4 = s_x2\n rem.extend([s_x3, s_x4])\n elif len(s_x3.columns) == 5:\n x4 = s_x3\n rem.extend([s_x2, s_x4])\n else:\n x4 = s_x4\n rem.extend([s_x2, s_x3])\n\n # Determine x2 and x3\n output = pd.DataFrame(columns=['left_instance_id', 'right_instance_id'])\n if not LOCAL:\n if len(rem[0]) > len(rem[1]):\n x3 = rem[0]\n x2 = rem[1]\n else:\n x3 = rem[1]\n x2 = rem[0]\n else:\n x2 = s_x2\n x3 = s_x3\n x4 = s_x4\n\n # Now, we evaluate based on the trained models\n print(\"Cleaning X2 dataset\")\n x2 = clean_x2(x2)\n print(\"Evaluating X2 dataset\")\n output = output.append(deduper_eval('x2', x2))\n\n print(\"Cleaning X3 dataset\")\n x3 = clean_x3(x3)\n print(\"Evaluating X3 dataset\")\n output = output.append(deduper_eval('x3', x3))\n\n print(\"Cleaning X4 dataset\")\n x4_rf = clean_x4_rf(x4)\n x4_dedupe = clean_x4_dedupe(x4)\n\n # Split by brand, size, type\n print(\"Evaluating X4 dataset\")\n output = output.append(eval_lightgbm_dedupe('x4', dataset_rf=x4_rf, dataset_dedupe=x4_dedupe))\n\n output.to_csv('output.csv', index=False)\n print(\"Total elapsed time: {}\".format(time.time() - start_time))\n","sub_path":"src/record_linkage/eval_all.py","file_name":"eval_all.py","file_ext":"py","file_size_in_byte":6125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"632100222","text":"import math\r\nimport numpy as np\r\nimport random\r\nimport time\r\nimport mss\r\nfrom tkinter import *\r\nfrom tkinter import font\r\nimport IPython\r\n\r\nfrom random import randint\r\n\r\n\r\nclass MinesweeperEnv(object):\r\n def __init__(self, ROWS = 10, COLS = 10, SIZEOFSQ = 100, MINES_MIN = 13, MINES_MAX=15, display = False, \r\n #rewards = {\"win\" : 2, \"loss\" : -2, \"progress\" : 1, \"noprogress\" : -1, \"YOLO\" : -1} # Intially, when not learned\r\n #rewards = {\"win\" : 2, \"loss\" : -10, \"progress\" : 1, \"noprogress\" : -1, \"YOLO\" : -1} # Intially, when not learned\r\n #rewards = {\"win\" : 2, \"loss\" : -10, \"progress\" : 1, \"noprogress\" : -1, \"YOLO\" : -1} # For later, when learned game\r\n #rewards = {\"win\" : 10, \"loss\" : -1, \"progress\" : 0.9, \"noprogress\" : -0.3, \"YOLO\" : -0.3} # This is Jacob\r\n rewards = {\"win\" : 1, \"loss\" : -1, \"progress\" : 0.9, \"noprogress\" : -0.3, \"YOLO\" : -0.3} # This is Jacob\r\n ):\r\n \"\"\" Initialize Minesweeper\r\n Rows, Cols: int - Number of rows and cols on the board\r\n SIZEOFSQ: pixels - Determines the size of the window, reduce to get smaller window\r\n Mines: integer - Number of mines generated on the board\r\n display: bool - chooses weather to display the game with pygame\r\n \"\"\"\r\n\r\n self.ROWS = ROWS\r\n self.COLS = COLS\r\n self.FULL = False\r\n self.MINES_MIN = MINES_MIN \r\n self.MINES_MAX = MINES_MAX \r\n self.MINES = 0\r\n\r\n self.display = display\r\n self.rewards = rewards\r\n\r\n self.grid = np.zeros((self.ROWS, self.COLS), dtype=object)\r\n self.state = np.zeros((self.ROWS, self.COLS), dtype=object)\r\n self.state_float = np.zeros((self.ROWS, self.COLS), dtype=float)\r\n self.state_last = np.copy(self.state)\r\n\r\n self.nbMatrix = np.zeros((ROWS, COLS), dtype=object)\r\n\r\n self.computeNeighbors() #Fills out the nbMatrix\r\n\r\n self.won = 0\r\n self.lost = 0\r\n if display: #Load pygame stuff\r\n\r\n #Scale to resolutions\r\n with mss.mss() as sct:\r\n img = np.array(sct.grab(sct.monitors[1]))\r\n self.SIZEOFSQ = int(SIZEOFSQ * img.shape[1] / 3840)\r\n SIZEOFSQ = self.SIZEOFSQ\r\n\r\n self.root = Tk()\r\n self.C = Canvas(self.root, bg=\"white\", height= COLS * SIZEOFSQ - 1, width = ROWS * SIZEOFSQ - 1)\r\n\r\n\r\n\r\n self.initGame()\r\n\r\n if display:\r\n self.drawState()\r\n\r\n\r\n def drawState(self):\r\n c1 = \"#0285DF\"\r\n c2 = \"#0491DF\" \r\n #Draw checked pattern\r\n for row in range(self.ROWS):\r\n for col in range(self.COLS):\r\n if self.checkpattern(col, row):\r\n c = c1\r\n else:\r\n c = c2\r\n\r\n self.C.create_rectangle(col*self.SIZEOFSQ,row*self.SIZEOFSQ, col*self.SIZEOFSQ + self.SIZEOFSQ ,row*self.SIZEOFSQ + self.SIZEOFSQ, fill=c, width=0)\r\n\r\n #Draw state\r\n for row in range(self.ROWS):\r\n for col in range(self.COLS):\r\n cell = self.state[row][col]\r\n if cell == 'E' or cell != 'U':\r\n if self.checkpattern(col,row):\r\n c = \"#F2F4F7\"\r\n else:\r\n c = \"#F7F9FC\"\r\n\r\n self.C.create_rectangle(col*self.SIZEOFSQ,row*self.SIZEOFSQ, col*self.SIZEOFSQ + self.SIZEOFSQ ,row*self.SIZEOFSQ + self.SIZEOFSQ, fill=c, width=0)\r\n \r\n if cell != 'U' and cell !='E': \r\n if cell == 1:\r\n c2 = \"#00CC00\"\r\n elif cell == 2:\r\n c2 = \"#FFCC00\"\r\n elif cell == 3:\r\n c2 = \"#CC0000\"\r\n elif cell == 4:\r\n c2 = \"#003399\"\r\n elif cell == 5:\r\n c2 = \"#FF6600\"\r\n elif cell == 6:\r\n c2 = \"#FF6600\"\r\n elif cell == 'flag':\r\n c2 = \"#FF0000\"\r\n\r\n\r\n #num = np.random.randint(len(font.families()))\r\n #print(\"({},{}) : {}\".format(row,col,num))\r\n f = self.C.create_text(col*self.SIZEOFSQ + int(0.5*self.SIZEOFSQ),row*self.SIZEOFSQ + int(0.5*self.SIZEOFSQ), \\\r\n font=('Nimbus Sans L', 24, \"bold\"), fill = c2) #101 pretty good font\r\n self.C.itemconfigure(f, text=str(cell))\r\n\r\n self.C.pack()\r\n #self.root.mainloop()\r\n\r\n\r\n def initGame(self):\r\n self.grid = self.initBoard(startcol = 2, startrow = 2)\r\n self.state = np.ones((self.ROWS, self.COLS), dtype=object) * 'U'\r\n self.state_last = np.copy(self.state)\r\n\r\n\r\n self.action((2,2)) #Hack alert, to start off with non empty board. Can be removed but then agent has to learn\r\n #what to do when the board starts out empty. \r\n\r\n def initBoard(self, startcol, startrow):\r\n \"\"\" Initializes the board \"\"\"\r\n\r\n COLS = self.COLS\r\n ROWS = self.ROWS\r\n grid = np.zeros((self.ROWS, self.COLS), dtype=object)\r\n #mines = self.MINES\r\n self.MINES = randint(self.MINES_MIN, self.MINES_MAX)\r\n mines = self.MINES\r\n\r\n #print(\"Initializing board with mines\")\r\n #print(mines)\r\n\r\n\r\n #Randomly place bombs\r\n while mines > 0:\r\n (row, col) = (random.randint(0, ROWS-1), random.randint(0, COLS-1))\r\n #if (col,row) not in findNeighbors(startcol, startrow, grid) and grid[col][row] != 'B' and (col, row) not in (startcol, startrow):\r\n if (row,col) not in self.nbMatrix[startrow, startcol] and (row,col) != (startrow, startcol) and grid[row][col] != 'B':\r\n #print(\"Placing bombs\")\r\n grid[row][col] = 'B'\r\n mines = mines - 1\r\n\r\n #Get rest of board when bombs have been placed\r\n for col in range(COLS):\r\n for row in range(ROWS):\r\n if grid[row][col] != 'B':\r\n totMines = self.sumMines(col, row, grid)\r\n if totMines > 0:\r\n grid[row][col] = totMines\r\n else:\r\n grid[row][col] = 'E'\r\n\r\n\r\n return grid\r\n\r\n def computeNeighbors(self):\r\n \"\"\" Computes the neighbor matrix for quick lookups\"\"\"\r\n\r\n for row in range(self.ROWS):\r\n for col in range(self.COLS):\r\n self.nbMatrix[row][col] = self.findNeighbors(row, col)\r\n\r\n\r\n\r\n def findNeighbors(self, rowin, colin):\r\n \"\"\" Takes col, row and grid as input and returns as list of neighbors\r\n \"\"\"\r\n COLS = self.grid.shape[1]\r\n ROWS = self.grid.shape[0]\r\n neighbors = []\r\n for col in range(colin-1, colin+2):\r\n for row in range(rowin-1, rowin+2):\r\n if (-1 < rowin < ROWS and \r\n -1 < colin < COLS and \r\n (rowin != row or colin != col) and\r\n (0 <= col < COLS) and\r\n (0 <= row < ROWS)):\r\n neighbors.append((row,col))\r\n\r\n return neighbors\r\n\r\n\r\n def sumMines(self, col, row, grid):\r\n \"\"\" Finds amount of mines adjacent to a field.\r\n \"\"\"\r\n mines = 0\r\n neighbors = self.nbMatrix[row, col]\r\n for n in neighbors:\r\n if grid[n[0],n[1]] == 'B':\r\n mines = mines + 1\r\n return mines\r\n\r\n\r\n def printState(self):\r\n \"\"\"Prints the current state\"\"\"\r\n grid = self.state\r\n COLS = grid.shape[1]\r\n ROWS = grid.shape[0]\r\n for row in range(0,ROWS):\r\n print(' ')\r\n for col in range(0,COLS):\r\n print(grid[row][col], end=' ')\r\n\r\n\r\n def printBoard(self):\r\n \"\"\"Prints the board \"\"\"\r\n grid = self.grid\r\n COLS = grid.shape[1]\r\n ROWS = grid.shape[0]\r\n for row in range(0,ROWS):\r\n print(' ')\r\n for col in range(0,COLS):\r\n print(grid[row][col], end=' ')\r\n\r\n\r\n def reveal(self, col, row, checked, press = \"LM\"):\r\n \"\"\"Finds out which values to show in the state when a square is pressed\r\n Checked : np.array((row,col)) to check which squares has already been checked\r\n If the field is not a bomb we want to reveal it, if the field is empty\r\n we want to find it's neighbors and reveal them too if they are not a bomb. \r\n \"\"\"\r\n if press == \"LM\":\r\n if checked[row][col] != 0:\r\n return\r\n checked[row][col] = checked[row][col] + 1\r\n if self.grid[row][col] != 'B':\r\n\r\n #Reveal to state space\r\n self.state[row][col] = self.grid[row][col]\r\n\r\n if self.grid[row][col] == 'E':\r\n neighbors = self.findNeighbors(row, col)\r\n for n in neighbors:\r\n if not checked[n[0],n[1]]: \r\n self.reveal(n[1], n[0], checked)\r\n \r\n elif press == \"RM\":\r\n #Draw flag, not used for agent\r\n pass\r\n\r\n\r\n\r\n def action(self, a):\r\n \"\"\" External action, taken by human or agent\r\n row,col: integer - where the agent want to press\r\n \"\"\"\r\n\r\n #print(\"Taking action\")\r\n \r\n #If press a bomb game over, start new game and return bad reward, -10 in this case\r\n row, col = a[0], a[1]\r\n if self.grid[row][col] == \"B\":\r\n self.lost += 1\r\n #self.initGame()\r\n if self.display:\r\n print(\"Lost game\")\r\n return({\"s\" : np.copy(self.state), \"r\" : self.rewards['loss'], \"d\" : True})\r\n\r\n #Take action and reveal new state\r\n self.reveal(col, row , np.zeros_like(self.grid))\r\n if self.display == True:\r\n self.drawState()\r\n\r\n #Winning condition\r\n if np.sum(self.state == \"U\") == self.MINES:\r\n self.won += 1\r\n #self.initGame()\r\n if self.display:\r\n print(\"Won game\")\r\n return({\"s\" : np.copy(self.state), \"r\" : self.rewards['win'], \"d\" : True})\r\n\r\n #Get the reward for the given action\r\n reward = self.compute_reward(a)\r\n\r\n #return the state and the reward\r\n return({\"s\" : np.copy(self.state), \"r\" : reward, \"d\" : False})\r\n\r\n\r\n def compute_reward(self, a):\r\n \"\"\"Computes the reward for a given action\"\"\"\r\n\r\n #Reward = 1 if we get less unknowns, 0 otherwise \r\n if (np.sum(self.state_last == 'U') - np.sum(self.state == 'U')) > 0:\r\n reward = self.rewards['progress']\r\n else:\r\n reward = self.rewards['noprogress']\r\n\r\n #YOLO -> it it clicks on a random field with unknown neighbors\r\n tot = 0\r\n for n in self.nbMatrix[a[0],a[1]]:\r\n if self.state_last[n[0],n[1]] == 'U':\r\n tot += 1\r\n if tot == len(self.nbMatrix[a[0],a[1]]):\r\n reward = self.rewards['YOLO']\r\n\r\n\r\n self.state_last = np.copy(self.state)\r\n return(reward)\r\n \r\n\r\n\r\n def checkpattern(self, col, row):\r\n #Function to construct the checked pattern in pygame\r\n if row % 2:\r\n if col % 2: #If unequal\r\n return True\r\n else: #if equal\r\n return False\r\n else: \r\n if col % 2: #If unequal\r\n return False\r\n else: #if equal\r\n return True\r\n\r\n def initPattern(self):\r\n #Initialize pattern:\r\n\r\n c1 = \"#0285DF\"\r\n c2 = \"#0491DF\" \r\n rects = []\r\n for row in range(self.ROWS):\r\n for col in range(self.COLS):\r\n if self.checkpattern(col, row):\r\n c = c1\r\n else:\r\n c = c2\r\n\r\n self.C.create_rectangle(col*self.SIZEOFSQ,row*self.SIZEOFSQ, col*self.SIZEOFSQ + self.SIZEOFSQ ,row*self.SIZEOFSQ + self.SIZEOFSQ, fill=c)\r\n self.C.pack()\r\n self.root.mainloop()\r\n\r\n\r\n def stateConverter(self, state):\r\n \"\"\" Converts 2d state to one-hot encoded 3d state\r\n input: state (rows x cols)\r\n output: state3d (row x cols x 10) (if full)\r\n (row x cols x 2) (if not full)\r\n \"\"\"\r\n rows, cols = state.shape\r\n if self.FULL:\r\n res = np.zeros((rows,cols,10), dtype = int)\r\n for i in range(0,8):\r\n res[:,:,i] = state == i+1 #1-7\r\n res[:,:,8] = state == 'U'\r\n res[:,:,9] = state == 'E'\r\n \r\n return(res)\r\n else:\r\n #res = np.ones((rows, cols, 2)) * -1\r\n #filtr = ~np.logical_or(state == \"U\", state == \"E\") #Not U or E\r\n #res[filtr,0] = state[filtr] / 10\r\n #res[state == \"U\", 1] = 1\r\n\r\n res = np.zeros((rows, cols, 2))\r\n filtr = ~np.logical_or(state == \"U\", state == \"E\") #Not U or E\r\n res[filtr,0] = state[filtr]\r\n res[state == \"U\", 1] = 1\r\n return(res)\r\n\r\n\r\n def get_state(self):\r\n\r\n for row in range(self.ROWS):\r\n for col in range(self.COLS):\r\n field = self.state[row][col]\r\n if type(field) == int:\r\n self.state_float[row][col]= field*20\r\n elif field == 'U':\r\n self.state_float[row][col] = -ord('U')/2\r\n else:\r\n self.state_float[row][col] = -ord('E')/4\r\n\r\n return np.copy(self.state_float)/200\r\n\r\n\r\n # Wrap to openai gym API\r\n def step(self, a):\r\n a = np.unravel_index(a, (self.ROWS,self.COLS))\r\n d = self.action(a)\r\n #d[\"s\"] = np.reshape(self.stateConverter(d[\"s\"]),(self.ROWS*self.COLS*2))\r\n\r\n # For 6x6x2\r\n d[\"s\"] = self.stateConverter(d[\"s\"])\r\n # For 6x6x1\r\n #d[\"s\"] = self.get_state()\r\n return d[\"s\"], d[\"r\"], d[\"d\"], None\r\n\r\n def reset(self):\r\n self.initGame()\r\n\r\n # For 6x6x2\r\n return self.stateConverter(self.state)\r\n # For 6x6x1\r\n #return self.get_state()\r\n\r\n\r\n\r\n # def step(self, a):\r\n # a = np.unravel_index(a, (self.ROWS,self.COLS))\r\n # d = self.action(a)\r\n # d[\"s\"] = self.get_state()\r\n # return d[\"s\"], d[\"r\"], d[\"d\"], None\r\n\r\n # def reset(self):\r\n # self.initGame()\r\n # return self.get_state()","sub_path":"q_learning/backup_output_net1_discount_0_batch_400_random_mines/minesweeper_env.py","file_name":"minesweeper_env.py","file_ext":"py","file_size_in_byte":14608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"182958716","text":"from dtk.utils.analyzers import TimeseriesAnalyzer\nfrom dtk.utils.analyzers import VectorSpeciesAnalyzer\nfrom dtk.utils.builders.sweep import GenericSweepBuilder\nfrom dtk.utils.core.DTKConfigBuilder import DTKConfigBuilder\nfrom dtk.vector.study_sites import configure_site\nfrom simtools.Analysis.AnalyzeManager import AnalyzeManager\nfrom simtools.ExperimentManager.ExperimentManagerFactory import ExperimentManagerFactory\nfrom simtools.SetupParser import SetupParser\n\n# This block will be used unless overridden on the command-line\nSetupParser.default_block = 'HPC'\n\ncb = DTKConfigBuilder.from_defaults('VECTOR_SIM')\nconfigure_site(cb, 'Namawala')\ncb.set_param('Simulation_Duration',365)\n\n\nanalyzers = (TimeseriesAnalyzer(),\n VectorSpeciesAnalyzer())\n\n\nbuilder = GenericSweepBuilder.from_dict({'Run_Number': range(5)})\n\nrun_sim_args = {\n 'exp_name': 'testrunandanalyze',\n 'exp_builder': builder,\n 'config_builder':cb\n}\n\nif __name__ == \"__main__\":\n SetupParser.init(selected_block=SetupParser.default_block)\n exp_manager = ExperimentManagerFactory.from_cb(config_builder=cb)\n exp_manager.run_simulations(**run_sim_args)\n exp_manager.wait_for_finished(verbose=True)\n\n am = AnalyzeManager(exp_manager.experiment)\n for a in analyzers:\n am.add_analyzer(a)\n am.analyze()\n","sub_path":"examples/Analysis/example_run_and_analyze.py","file_name":"example_run_and_analyze.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"60115754","text":"\"\"\"\nEach line in the sketch.txt file corresponds to a certain pattern:\nCharacter: Dialog\n ^ --> Delimiter.\n\nWe can use this delimiter to split the contents of each line to obtain the character name or dialog separately.\n\"\"\"\nimport os\n\nos.chdir('/home/somu/Programming/python/HeadFirstPython')\n\n\n# The following if suite is required only if the `IOError` Exception generated by the missing data file isn't handled.\n\"\"\"\nif not os.path.exists('sketch.txt'): # Checks if a file called `sketch.txt` exists in the current directory.\n print(\"The data file sketch.txt doesn't exist! Exiting...\")\n exit(1)\n\"\"\"\ntry:\n data = open('sketch.txt')\n\n diaCount=0\n transcript=\"\"\n for each_line in data:\n\n # The following `if` suite should only be used when not using exception handling. Else, this stays commented.\n \"\"\"\n if each_line.find(':') == -1: # Returns a -1 when it can't find a `:` in the string, otherwise the index of `:`.\n print(\"This line doesn't have a `:` - skipping split.\")\n continue\n \"\"\"\n\n lineArr = each_line.split(':') # The split method returns a list comprised of the substrings, which we assign\n # to lineArr.\n i = 0\n for each_word in lineArr:\n print(\"Arg[\", i, \"]= \", each_word,\" \", sep=\"\", end=\"\")\n i += 1\n\n # Multiple assignment\n try:\n \"\"\"\n Create an immutable list, or a tuple. This is why it's enclosed in `()`s. The size and contents of such a \n list is always fixed and cannot be changed, unlike lists created with `[]`s, i.e., mutable lists. The \n left side of the expression is called the *target identifier*. \n \"\"\"\n (role, dialog) = each_line.split(\":\", 1)\n except ValueError:\n \"\"\"\n Instead of continuing, if we wanted to simply _do nothing_ then we could write `pass` here, instead of \n continue.\n \"\"\"\n continue\n\n \"\"\"\n Python makes it possible to assign the members of a list to multiple, individual variable using the above syntax \n This is called multiple assignment. \n \n We could use : `(role, dialog) = each_line.split(\":\")` however, since the data file contains multiple lines \n where the subsequent ':'s after the first one aren't used as a delimiter, split would break the line into \n more than two elements for the list, and try to assign them, but find only two variables. This would cause a\n ValueError - which indicates that there's something wrong with the data! This is an Exception/Runtime Error!\n \n To solve this, we use a `maxsplit` argument which is provided in the documentation for the split() BIF. Using \n this sets a maximum number of splits possible for the function. We set it to one since only the first `:` \n matters. \n \n This leads to another value error, since there are multiple lines with just `(pause)` which don't conform to our \n standard. We now have two choices: Added extra logic for the errors, or simply deal with errors if and when \n they occur. If we choose the first, we can use the BIF find() for the string to determine if the line \n contains a ':'. However, this method isn't future-proof, since the data format may change at any time, which\n will require the code to be re-written appropriately. Thus, error handling would be a better solution here. \n \n In python, the try keyword remains the same, but `catch` is replaced with `except`, followed by an optional \n exception name. Note, however, that ignoring the exception name can lead to silently ignoring unexpected\n errors and thus the wrong output. \n \"\"\"\n if role == \"Man\":\n diaCount += 1\n transcript = transcript + dialog # String concatenation can be done with a + operator just like in Java.\n\n print(\"\\n\\nThe character 'Man' had\", diaCount, \"dialogues, which are:\", transcript)\n data.close()\nexcept IOError:\n print(\"The file `sketch.txt` wasn't found! \")","sub_path":"HeadFirstPython/stringProcessing.py","file_name":"stringProcessing.py","file_ext":"py","file_size_in_byte":4257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"399538785","text":"import numpy as np\r\n\r\nfrom src.utils.Constants import ROBOT_RADIUS, EPSILON, DRAW\r\n\r\nimport pygame\r\n\r\nline_color = (0, 128, 255)\r\n\r\n\r\nclass Line:\r\n \"\"\"\r\n Author Frederic Abraham\r\n \"\"\"\r\n def __init__(self, start_x: float, start_y: float, end_x: float, end_y: float):\r\n self.start_x: float = start_x\r\n self.start_y: float = start_y\r\n self.end_x: float = end_x\r\n self.end_y: float = end_y\r\n\r\n self.start = np.array([start_x, start_y]).reshape((2, 1))\r\n self.end = np.array([end_x, end_y]).reshape((2, 1))\r\n\r\n self.vec = np.array(self.end - self.start).reshape((2, 1))\r\n self.nvec = (self.vec / np.linalg.norm(self.vec)).reshape((2, 1))\r\n\r\n self.col_start: np.ndarray = self.start + (self.nvec * -1) * ROBOT_RADIUS\r\n self.col_end: np.ndarray = self.end + self.nvec * ROBOT_RADIUS\r\n\r\n self.col_start_x: float = self.col_start[0].item()\r\n self.col_start_y: float = self.col_start[1].item()\r\n self.col_end_x: float = self.col_end[0].item()\r\n self.col_end_y: float = self.col_end[1].item()\r\n\r\n self.length = np.linalg.norm(self.vec)\r\n self.angle = self.compute_slope()\r\n\r\n if DRAW:\r\n self.pyStart = pygame.Vector2(self.start[0], self.start[1])\r\n self.pyEnd = pygame.Vector2(self.end[0], self.end[1])\r\n\r\n def is_on(self, point):\r\n crossproduct = (point[1].item() - self.col_start_y) * (self.col_end_x - self.col_start_x) - (\r\n point[0].item() - self.col_start_x) * (self.col_end_y - self.col_start_y)\r\n\r\n # compare versus epsilon for floating point values, or != 0 if using integers\r\n if abs(crossproduct) > EPSILON:\r\n return False\r\n\r\n dotproduct = (point[0].item() - self.col_start_x) * (self.col_end_x - self.col_start_x) + (\r\n point[1].item() - self.col_start_y) * (self.col_end_y - self.col_start_y)\r\n if dotproduct < 0:\r\n return False\r\n\r\n squaredlengthba = (self.col_end_x - self.col_start_x) * (self.col_end_x - self.col_start_x) + (\r\n self.col_end_y - self.col_start_y) * (self.col_end_y - self.col_start_y)\r\n if dotproduct > squaredlengthba:\r\n return False\r\n\r\n return True\r\n\r\n def is_on_1(self, point):\r\n crossproduct = (point[1].item() - self.start_y) * (self.end_x - self.start_x) - (\r\n point[0].item() - self.start_x) * (self.end_y - self.start_y)\r\n\r\n # compare versus epsilon for floating point values, or != 0 if using integers\r\n if abs(crossproduct) > EPSILON:\r\n return False\r\n\r\n dotproduct = (point[0].item() - self.start_x) * (self.end_x - self.start_x) + (\r\n point[1].item() - self.start_y) * (self.end_y - self.start_y)\r\n if dotproduct < 0:\r\n return False\r\n\r\n squaredlengthba = (self.end_x - self.start_x) * (self.end_x - self.start_x) + (self.end_y - self.start_y) * (\r\n self.end_y - self.start_y)\r\n if dotproduct > squaredlengthba:\r\n return False\r\n\r\n return True\r\n\r\n def __str__(self):\r\n return f'({self.start_x}, {self.start_y}) ({self.end_x}, {self.end_y})'\r\n\r\n def draw(self, screen):\r\n pygame.draw.line(screen, line_color, self.pyStart, self.pyEnd, 2)\r\n\r\n def compute_slope(self):\r\n return (self.start[1] - self.end[1]) / (self.start[0] - self.end[0]) if (self.start[0] - self.end[\r\n 0]) != 0 else np.inf\r\n\r\n def get_vec_towards_point(self, pos):\r\n ep = np.linalg.norm(pos - self.end)\r\n es = np.linalg.norm(pos - self.start)\r\n\r\n if ep > es:\r\n return np.array(self.end - self.start).reshape((2, 1))\r\n else:\r\n return np.array(self.start - self.end).reshape((2, 1))\r\n","sub_path":"03_Genetic_Algorithm/src/simulator/Line.py","file_name":"Line.py","file_ext":"py","file_size_in_byte":3800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"15302412","text":"import docker\nimport logging\nimport pk_config\n\ndef query_list_of_ready_nodes(endpoint):\n log=logging.getLogger('pk_docker')\n ready_nodes=[]\n if pk_config.simulate():\n return None\n client = docker.APIClient(endpoint)\n try:\n nodes = client.nodes(filters={'role': 'worker'})\n for n in nodes:\n if n.get('Status',dict).get('State','')=='ready':\n a = {}\n a['CreatedAt']=n.get('CreatedAt','')\n a['Addr']=n.get('Status',dict()).get('Addr','')\n ready_nodes.append(a.copy())\n return ready_nodes\n except Exception as e:\n log.exception('(Q) Query of docker nodes failed.')\n return None\n\ndef scale_docker_service(endpoint,service_name,replicas):\n log=logging.getLogger('pk_docker')\n log.info('(S) => m_container_count: {0}'.format(replicas))\n if pk_config.simulate():\n return\n client = docker.APIClient(endpoint)\n try: \n version = client.inspect_service(service_name)['Version']['Index']\n ret = client.update_service(\n service_name,\n version,\n mode={'Replicated': {'Replicas': replicas}},\n fetch_current_spec=True)\n except Exception as e:\n log.exception('(S) Scaling of docker service \"{0}\" failed:'.format(service_name))\n return\n\ndef query_service_network(endpoint, stack_name, service_name):\n id = None\n log=logging.getLogger('pk_docker')\n client = docker.DockerClient(base_url=endpoint)\n full_service_name = stack_name + \"_\" + service_name\n if pk_config.simulate():\n return None\n service_list = client.services.list()\n i = 0\n while i < len(service_list) and service_list[i].name != full_service_name:\n i += 1\n if i < len(service_list) and service_list[i].name == full_service_name:\n if len(service_list[i].attrs.get(\"Spec\").get(\"TaskTemplate\").get(\"Networks\")) == 1:\n id = service_list[i].attrs.get(\"Spec\").get(\"TaskTemplate\").get(\"Networks\")[0].get(\"Target\")\n log.debug('Docker service \"{0}\" in stack \"{1}\" is connected to network \"{2}\" with id \"{3}\".'\n\t\t .format(service_name, stack_name, client.networks.get(id).name),str(id))\n else:\n log.warning('Docker service \"{0}\" is connected to more than one network.'.format(full_service_name))\n else:\n log.warning('Docker service \"{0}\" is not found in stack \"{1}\".'.format(service_name,stack_name))\n return id\n\n\ndef attach_container_to_network(endpoint, container, network_id):\n log=logging.getLogger('pk_docker')\n client = docker.DockerClient(base_url=endpoint)\n network = client.networks.get(network_id)\n if client.containers.get(container).status == \"running\":\n network.connect(container)\n log.info('Container \"{0}\" is connected to network \"{1}\".'.format(container, network.name))\n else:\n log.info('Container \"{0}\" cannot be connected to network \"{1}\" as it is not running.'\n\t .format(container,network.name))\n return\n\ndef detach_container_from_network(endpoint, container, network_id):\n log=logging.getLogger('pk_docker')\n client = docker.DockerClient(base_url=client_address, version=client_version)\n network = client.networks.get(network_id)\n if client.containers.get(container).status == \"running\":\n network.disconnect(container)\n log.info('Container \"{0}\" is disconnected from network \"{1}\".'.format(container, network.name))\n else:\n log.info('Container \"{0}\" cannot be disconnected from network \"{1}\" as it is not running.'\n\t .format(container,network.name))\n return\n \n\n\n","sub_path":"handle_docker.py","file_name":"handle_docker.py","file_ext":"py","file_size_in_byte":3393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"44741402","text":"import data_preprocess as dp\nimport numpy as np\nimport pandas as pd\nimport scoring as score\nimport normal_run as nr\nimport ranking_subset_run as rsr\nimport sfs_run as sfs_r\nimport boost_bag_run as bbr\nimport featureselection as fselect\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import LinearSVC, SVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom xgboost import XGBClassifier\nfrom sklearn.naive_bayes import GaussianNB, BernoulliNB\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.ensemble import BaggingClassifier\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.experimental import enable_iterative_imputer\nfrom sklearn.impute import IterativeImputer\nimport statsmodels.api as sm\n\n####### main ####\ndef runSKFold(n_seed, splits, data):\n \n '''\n splitting the data into n_seed of splits folds cross validarion\n Args:\n n_seed(int): number of cross-validation\n splits(int): number of folds in each cross validation\n \n Returns:\n List: data for each of n_seed * splits folds\n '''\n runs = []\n\n X = np.array(data.drop('HPYLORI',axis=1))\n y = np.array(data.HPYLORI)\n\n for seed in range(n_seed):\n skf = StratifiedKFold(n_splits=splits, random_state=seed, shuffle=True)\n for train, test in skf.split(X, y):\n X_train, X_test = X[train], X[test]\n X_train, X_test = dp.impute(X_train), dp.impute(X_test)\n y_train, y_test = y[train], y[test]\n arr = [X_train, X_test, y_train, y_test]\n runs.append(arr)\n return runs\n\ndef stats(data, column, file_to_write):\n \n '''\n reporting p-values and odds ratio for multivariate logistic regression\n \n '''\n endog = data[column]\n features = data.drop(columns=[column],axis=1).columns\n exog = sm.add_constant(data.loc[:,features])\n \n \n \n logit = sm.Logit(endog,exog)\n result = logit.fit()#maxiter=10000,skip_hessian=True,disp=0,method='bfgs'\n\n p_values = result.pvalues.to_frame()\n p_values.columns = [''] * len(p_values.columns)\n\n CI = result.conf_int(alpha = 0.05)\n CI = np.exp(CI)\n CI.columns = [''] * len(CI.columns)\n\n coeff = np.exp(result.params.to_frame())\n coeff.columns = [''] * len(coeff.columns)\n\n file_to_write.write('pvalues:')\n file_to_write.write(p_values.to_string()+'\\n')\n\n file_to_write.write('CI 95%:')\n file_to_write.write(CI.to_string()+'\\n')\n file_to_write.write('odds ratio:')\n file_to_write.write(coeff.to_string()+'\\n')\n \n\n\ndef univariate_stats(data,column, file_to_write):\n '''\n reporting p-values and odds ration for univariate logistic regression\n '''\n \n file_to_write.write('univariate wise: \\n')\n columns = data.drop(columns = [column]).columns\n columns = [['ADD'],['AnyAllr'],['AnyPars3'],['CookArea'],['DEWORM'],['GCOW'],['HCIGR6A'],['GCAT_1','GCAT_2'],['GDOG_1.0','GDOG_2.0'],['GELEC_1.0','GELEC_2.0'],['GFLOOR6A_1.0','GFLOOR6A_2.0','GFLOOR6A_9.0'],['GWASTE_1.0','GWASTE_2.0','GWASTE_3.0'],['AgeGroups_1.0','AgeGroups_2.0'],['FamilyGrouped_1.0','FamilyGrouped_2.0'],['ToiletType_1.0','ToiletType_2.0'],['WaterSource_1.0','WaterSource_2.0']]\n \n for col in columns:\n endog = data[column]\n\n exog = sm.add_constant(data.loc[:,col])\n \n \n \n logit = sm.Logit(endog,exog)\n result = logit.fit()#maxiter=10000,skip_hessian=True,disp=0,method='bfgs'\n p_values = result.pvalues.to_frame()\n p_values.columns = [''] * len(p_values.columns)\n\n CI = result.conf_int(alpha = 0.05)\n CI = np.exp(CI)\n CI.columns = [''] * len(CI.columns)\n\n coeff = np.exp(result.params.to_frame())\n coeff.columns = [''] * len(coeff.columns)\n\n file_to_write.write('pvalues: \\n')\n file_to_write.write(p_values.to_string()+'\\n')\n\n file_to_write.write('CI 95%:\\n')\n file_to_write.write(CI.to_string()+'\\n')\n file_to_write.write('odds ratio: \\n')\n file_to_write.write(coeff.to_string()+'\\n')\n \n \ndef impute(data):\n '''\n imputing the data\n '''\n \n columns = data.columns\n imputed_data = []\n for i in range(5):\n imputer = IterativeImputer(sample_posterior=True, random_state=i, verbose=1)\n imputed_data.append(imputer.fit_transform(data))\n returned_data = np.round(np.mean(imputed_data,axis = 0))\n return_data = pd.DataFrame(data = returned_data, columns=columns)\n\n return return_data\n\n\n\ndef gen_stats(data, target):\n '''\n generating baseline accuracy and f1 score and multivariate and univariate\n '''\n \n data1 = impute(data)\n\n stats_file1 = open('multivariate.txt','w')\n\n stats(data1,target,stats_file1)\n stats_file1.close()\n \n stats_file2 = open('univariate.txt','w')\n univariate_stats(data1,target,stats_file2)\n stats_file2.close()\n\n\n# # # ######## baseline accuracy ##########\n f = open('research_result.txt','w')\n rate = sum(data1[target])/data1.shape[0]\n rate2 = 1-rate\n f.write('base line accuracy is '+str( max(rate,1-rate))+'\\n')\n f1 = 2*rate/(1+rate)\n f.write('base line f1 value is '+str(f1))\n f.close()","sub_path":"uni_multiStats.py","file_name":"uni_multiStats.py","file_ext":"py","file_size_in_byte":5205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"653481104","text":"# Frog River\n#\n# A small frog wants to get to the other side of a river. The frog is initially\n# located on one bank of the river (position 0) and wants to get to the opposite\n# bank (position X+1). Leaves fall from a tree onto the surface of the river.\n\n# You are given an array A consisting of N integers representing the falling\n# leaves. A[K] represents the position where one leaf falls at time K, measured\n# in seconds.\n\n# The goal is to find the earliest time when the frog can jump to the other side\n# of the river. The frog can cross only when leaves appear at every position across\n# the river from 1 to X (that is, we want to find the earliest moment when all\n# the positions from 1 to X are covered by leaves). You may assume that the speed\n# of the current in the river is negligibly small, i.e. the leaves do not change\n# their positions once they fall in the river.\n\n# For example, you are given integer X = 5 and array A such that:\n\n# A[0] = 1\n# A[1] = 3\n# A[2] = 1\n# A[3] = 4\n# A[4] = 2\n# A[5] = 3\n# A[6] = 5\n# A[7] = 4\n# In second 6, a leaf falls into position 5. This is the earliest time when leaves\n# appear in every position across the river.\n\n# Write a function:\n\n# class Solution { public int solution(int X, int[] A); }\n\n# that, given a non-empty array A consisting of N integers and integer X, returns\n# the earliest time when the frog can jump to the other side of the river.\n\n# If the frog is never able to jump to the other side of the river, the function\n# should return −1.\n\n# For example, given X = 5 and array A such that:\n\n# A[0] = 1\n# A[1] = 3\n# A[2] = 1\n# A[3] = 4\n# A[4] = 2\n# A[5] = 3\n# A[6] = 5\n# A[7] = 4\n# the function should return 6, as explained above.\n\n# Write an efficient algorithm for the following assumptions:\n\n# N and X are integers within the range [1..100,000];\n# each element of array A is an integer within the range [1..X].\n\n\n# ========== solution ==================\n\n# you can write to stdout for debugging purposes, e.g.\n# print(\"this is a debug message\")\n\n# conditions\n# - return -1 if position not found / cannot cross the river\n\n# brainstorming solution\ndef solution(X, A):\n # 1. put all elements in a set\n N = len(A)\n positions_set = set(range(1,X+1))\n index = 0\n\n # 2. for each element and index in array\n while index < N:\n # 3. if element is in set, remove\n if A[index] in positions_set:\n positions_set.remove(A[index])\n # 4. if length == 0, return index\n\n if len(positions_set) == 0:\n return index\n index += 1\n return -1\n\n# time complexity O(N), spatial complexity O(10\n\nif __name__ == '__main__':\n A_case_1 = [1,3,1,4,2,3,5,4]\n X_case_1 = 5\n\n A_case_2 = []\n X_case_2 = -1\n\n A_case_3 = [1,3,1,4,2,3,5,4]\n X_case_3 = 10\n\n expected_1 = 6\n expected_2 = -1\n expected_3 = -1\n\n solution_1 = solution(A_case_1, X_case_1)\n solution_2 = solution(A_case_2, X_case_2)\n solution_3 = solution(A_case_3, X_case_3)\n\n assert expected_1 == solution_1\n assert expected_2 == solution_2\n assert expected_3 == solution_3\n","sub_path":"codility_practice/counting_elements/frog_river_02.py","file_name":"frog_river_02.py","file_ext":"py","file_size_in_byte":3132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"377195880","text":"#\n# Jasy - Web Tooling Framework\n# Copyright 2013-2014 Sebastian Werner\n#\n\nimport copy\nimport re\n\nimport jasy.style.parse.Node as Node\nimport jasy.style.process.Operation as Operation\nimport jasy.style.Util as Util\nimport jasy.core.Console as Console\n\n\nclass ExecuterError(Exception):\n\n def __init__(self, message, node):\n Exception.__init__(self, \"Variable Error: %s for node type=%s in %s at line %s!\" % (message, node.type, node.getFileName(), node.line))\n\n\ndef process(tree, profile):\n __recurser(tree, tree.scope, {}, profile)\n\n\n\n\n\n#\n# Implementation\n#\n\nRE_INLINE_VARIABLE = re.compile(\"\\$\\{([a-zA-Z0-9\\-_\\.]+)\\}\")\n\n\ndef __recurser(node, scope, values, profile):\n # Replace variable with actual value\n if node.type == \"variable\" and not (node.parent.type == \"assign\" and node.parent[0] is node):\n name = node.name\n if name not in values:\n raise ExecuterError(\"Could not resolve variable %s! Missing value!\" % name, node)\n\n value = values[name]\n if value is None:\n raise ExecuterError(\"Could not resolve variable %s! Value is none!\" % name, node)\n\n Console.debug(\"Resolving variable: %s at line %s with %s from %s\", name, node.line, values[name].type, values[name].line)\n node.parent.replace(node, copy.deepcopy(values[name]))\n\n\n # Decide which sub tree of an if-condition is relevant based on current variable situation\n elif node.type == \"if\":\n\n Console.debug(\"Processing if-condition at %s\", node.line)\n\n # Pre-process condition\n # We manually process each child in for if-types\n __recurser(node.condition, scope, values, profile)\n\n # Cast condition to Python boolean type\n resultValue = Operation.castToBool(node.condition)\n\n # Process relevant part of the sub tree\n if resultValue is True:\n # Fix missing processing of result node\n __recurser(node.thenPart, scope, values, profile)\n\n # Finally replace if-node with result node\n node.parent.replace(node, node.thenPart)\n\n elif resultValue is False and hasattr(node, \"elsePart\"):\n # Fix missing processing of result node\n __recurser(node.elsePart, scope, values, profile)\n\n # Finally replace if-node with result node\n node.parent.replace(node, node.elsePart)\n\n else:\n # Cleanup original if-node\n node.parent.remove(node)\n\n # Nothing to do here as content is already processed\n return\n\n\n # Update scope of new block starts\n if hasattr(node, \"scope\"):\n relation = getattr(node, \"rel\", None)\n\n # Conditional blocks are not exactly blocks in this variable resolution engine\n if not relation in (\"thenPart\", \"elsePart\"):\n scope = node.scope\n values = copy.copy(values)\n node.values = values\n\n # Reset all local variables to None\n # which enforces not to keep values from outer scope\n for name in scope.modified:\n values[name] = None\n\n\n # Process children / content\n for child in list(node):\n # Ignore non-children... through possible interactive structure changes\n if child and child.parent is node:\n __recurser(child, scope, values, profile)\n\n\n # Update values of variables\n # This happens after processing children to possibly reduce child structure to an easy to assign (aka preprocessed value)\n if (node.type == \"declaration\" and hasattr(node, \"initializer\")) or node.type == \"assign\":\n\n if node.type == \"declaration\":\n name = node.name\n init = node.initializer\n Console.debug(\"Found declaration of %s at line %s\", name, node.line)\n\n else:\n name = node[0].name\n init = node[1]\n Console.debug(\"Found assignment of %s at line %s\", name, node.line)\n\n # Modify value instead of replace when assign operator is set\n if hasattr(node, \"assignOp\") and node.assignOp is not None:\n if name not in values:\n raise ExecuterError(\"Assign operator is not supported as left hand variable is missing: %s\" % name, node)\n\n repl = Operation.compute(node, values[name], init, node.assignOp)\n if repl is not None:\n values[name] = repl\n\n else:\n # Update internal variable mapping\n # Console.debug(\"Update value of %s to %s\" % (name, init))\n values[name] = init\n\n # Remove declaration node from tree\n node.parent.remove(node)\n\n\n # Support for variables inside property names or selectors\n elif node.type in (\"property\", \"selector\") and getattr(node, \"dynamic\", False):\n def replacer(matchObj):\n name = matchObj.group(1)\n\n if name not in values:\n raise ExecuterError(\"Could not resolve variable %s! Missing value!\" % name, node)\n\n value = values[name]\n if value is None:\n raise ExecuterError(\"Could not resolve variable %s! Value is none!\" % name, node)\n\n if value.type == \"identifier\":\n return value.value\n elif value.type == \"string\":\n return value.value\n elif value.type == \"number\":\n return \"%s%s\" % (value.value, getattr(value, \"unit\", \"\"))\n else:\n raise ExecuterError(\"Could not replace property inline variable with value of type: %s\" % value.type, node)\n\n # Fix all selectors\n if node.type == \"selector\":\n selectors = node.name\n for pos, selector in enumerate(selectors):\n selectors[pos] = RE_INLINE_VARIABLE.sub(replacer, selector)\n\n else:\n node.name = RE_INLINE_VARIABLE.sub(replacer, node.name)\n\n\n # Execute system commands\n elif node.type == \"command\":\n repl = Util.executeCommand(node, profile)\n if not repl is node:\n node.parent.replace(node, repl)\n\n\n # Support typical operators\n elif node.type in Util.ALL_OPERATORS:\n repl = Operation.compute(node)\n if repl is not None:\n node.parent.replace(node, repl)\n","sub_path":"jasy/style/process/Executer.py","file_name":"Executer.py","file_ext":"py","file_size_in_byte":6215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"63208540","text":"import torch\r\nimport torch.nn as nn\r\nfrom models.layers.graphconv import GraphConv\r\n\r\n\r\nclass GCN(nn.Module):\r\n def __init__(self,\r\n input_dim,\r\n num_hidden,\r\n num_classes,\r\n num_layers,\r\n activation=torch.relu,\r\n dropout=0.):\r\n super(GCN, self).__init__()\r\n self.layers = nn.ModuleList()\r\n # input layer\r\n self.layers.append(GraphConv(input_dim, num_hidden, activation=activation))\r\n # hidden layers\r\n for i in range(num_layers - 1):\r\n self.layers.append(GraphConv(num_hidden, num_hidden, activation=activation))\r\n # output layer\r\n self.layers.append(GraphConv(num_hidden, num_classes))\r\n self.dropout = nn.Dropout(p=dropout)\r\n\r\n def forward(self, graph, features):\r\n\r\n h = features\r\n for i, layer in enumerate(self.layers):\r\n if i != 0:\r\n h = self.dropout(h)\r\n h = layer(graph, h)\r\n return h\r\n","sub_path":"models/GCN.py","file_name":"GCN.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"131202125","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2001-2014 Andreas Lang-Nevyjel, init.at\n#\n# Send feedback to: \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 Version 2 as\n# published by the Free Software Foundation.\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, write to the Free Software\n# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n#\n\"\"\" monitors postgres performance values \"\"\"\n\nfrom ConfigParser import SafeConfigParser\nfrom initat.host_monitoring.hm_classes import hm_module\nimport logging_tools\nimport os\nimport process_tools\nimport time\ntry:\n import psycopg2\nexcept:\n psycopg2 = None\n\nCONFIG_DIR = \"/etc/sysconfig/host-monitoring.d/\"\nCONFIG_FILE = \"database.config\"\nSECTION = \"postgres\"\n\nDEFAULTS = {\n \"HOST\": \"\",\n \"PORT\": \"5432\",\n \"USER\": \"postgres\",\n \"PASSWORD\": \"\",\n \"DATABASE\": \"template1\"\n}\n\n# Key used in srv_com dictionary like objects\nKEY = \"postgres\"\n\n\nclass pg_stat(object):\n def __init__(self, name, mv):\n self.name = name\n self.top_key = \"db.postgres.{}\".format(self.name)\n self._keys = set()\n self._init_keys(mv)\n self.last_ts = None\n\n def _key(self, key):\n _key = \"{}.{}\".format(self.top_key, key)\n if _key not in self._keys:\n self._keys.add(_key)\n return _key\n\n def _init_keys(self, mv):\n mv.register_entry(self._key(\"backends\"), 0, \"number of backends for $3\")\n mv.register_entry(self._key(\"xact_commit\"), 0., \"number of transactions committed in $3\", \"1/s\"),\n mv.register_entry(self._key(\"xact_rollback\"), 0., \"number of transactions rolled back in $3\", \"1/s\"),\n mv.register_entry(self._key(\"blks_read\"), 0., \"number of blocks read in $3\", \"1/s\"),\n mv.register_entry(self._key(\"blks_hit\"), 0., \"number of blocks found in buffer in $3\", \"1/s\"),\n mv.register_entry(self._key(\"tup_returned\"), 0., \"number of rows returned by queries in $3\", \"1/s\"),\n mv.register_entry(self._key(\"tup_fetched\"), 0., \"number of rows fetched by queries in $3\", \"1/s\"),\n mv.register_entry(self._key(\"tup_inserted\"), 0., \"number of rows inserted by queries in $3\", \"1/s\"),\n mv.register_entry(self._key(\"tup_updated\"), 0., \"number of rows updated by queries in $3\", \"1/s\"),\n mv.register_entry(self._key(\"tup_deleted\"), 0., \"number of rows deleted by queries in $3\", \"1/s\"),\n mv.register_entry(self._key(\"blk_read_time\"), 0., \"time spent reading data in $3\", \"s\"),\n mv.register_entry(self._key(\"blk_write_time\"), 0., \"time spent writing data in $3\", \"s\"),\n\n def feed(self, line, mv):\n cur_time = time.time()\n if self.last_ts:\n diff_time = max(1, abs(cur_time - self.last_ts))\n mv[self._key(\"backends\")] = line[\"numbackends\"]\n for key in [\n \"xact_commit\", \"xact_rollback\", \"blks_read\", \"blks_hit\",\n \"tup_returned\", \"tup_fetched\", \"tup_inserted\", \"tup_updated\", \"tup_deleted\"\n ]:\n if key in line and key in self.last_line:\n mv[self._key(key)] = (line[key] - self.last_line[key]) / diff_time\n for key in [\"blk_read_time\", \"blk_write_time\"]:\n if key in line and key in self.last_line:\n mv[self._key(key)] = (line[key] - self.last_line[key]) / (1000. * diff_time)\n self.last_ts = cur_time\n self.last_line = line\n\n def remove(self, mv):\n for key in self._keys:\n mv.unregister_entry(key)\n\n\nclass _general(hm_module):\n def init_module(self):\n self.enabled = True\n if psycopg2:\n self.read_config()\n else:\n self.log(\"disabled postgres monitoring because no psycopg2 module available\")\n self.enabled = False\n # pprint.pprint(self.query(\"SELECT * FROM pg_stat_activity;\"))\n\n def read_config(self):\n self.config = {}\n parser = SafeConfigParser()\n if os.path.isfile(os.path.join(CONFIG_DIR, CONFIG_FILE)):\n try:\n parser.read(os.path.join(CONFIG_DIR, CONFIG_FILE))\n self.config[\"host\"] = parser.get(SECTION, \"HOST\")\n self.config[\"port\"] = parser.get(SECTION, \"PORT\")\n self.config[\"user\"] = parser.get(SECTION, \"USER\")\n self.config[\"password\"] = parser.get(SECTION, \"PASSWORD\")\n self.config[\"database\"] = parser.get(SECTION, \"DATABASE\")\n # Access via UNIX socket\n if not self.config[\"host\"]:\n del self.config[\"host\"]\n except:\n self.log(\"disabled postgres monitoring because error parsing config file: %s\" % (\n process_tools.get_except_info()))\n self.enabled = False\n else:\n self.log(\"disabled postgres monitoring because no config-file found\")\n self.enabled = False\n # self.config[\"password\"] = \"dd\"\n\n def query(self, sql):\n try:\n cursor = psycopg2.connect(**self.config).cursor()\n except:\n self.log(\"cannot connect to database: %s\" % (process_tools.get_except_info()), logging_tools.LOG_LEVEL_ERROR)\n _res = None\n else:\n try:\n cursor.execute(sql)\n except:\n self.log(\"cannot execute query '%s': %s\" % (\n sql,\n process_tools.get_except_info()), logging_tools.LOG_LEVEL_ERROR)\n _res = None\n else:\n headers = [_entry.name for _entry in cursor.description]\n _res = [{key: value for key, value in zip(headers, row)} for row in cursor.fetchall()]\n cursor.close()\n return _res\n\n def init_machine_vector(self, mv):\n self.databases = {}\n\n def update_machine_vector(self, mv):\n if not self.enabled:\n return\n res = self.query(\"SELECT * FROM pg_stat_database;\")\n if res is not None:\n touched = set()\n for line in res:\n db_name = line[\"datname\"]\n if db_name not in self.databases:\n self.log(\"adding mv for database {}\".format(db_name))\n self.databases[db_name] = pg_stat(db_name, mv)\n self.databases[db_name].feed(line, mv)\n touched.add(db_name)\n to_remove = set(self.databases.keys()) - touched\n for rem_db in to_remove:\n self.log(\"remove mv for database {}\".format(rem_db))\n self.databases[rem_db].remove(mv)\n del self.databases[rem_db]\n","sub_path":"initat/host_monitoring/modules/postgresql_mod.py","file_name":"postgresql_mod.py","file_ext":"py","file_size_in_byte":7011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"202466602","text":"#\n# Copyright (C) 2016 The Android Open Source Project\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\"\"\"Unittests for timer.py\"\"\"\n\n\nimport unittest\n\nfrom core import timer\nfrom test import stubs\n\n\nclass TimerTest(unittest.TestCase):\n\n def setUp(self):\n self.stub_time = stubs.StubTime()\n\n timer.time = self.stub_time\n\n def RunningTimerWithTime(self, time):\n \"\"\"Returns a timer running with a given amount of time already on it.\n\n The timer will have been started at stub_time = 0.\n \"\"\"\n self.stub_time.current_time = 0\n t = timer.Timer('event')\n t.Start()\n self.stub_time.current_time = time\n # Confirm that this is indeed a running timer with the desired time.\n self.assertTrue(t.IsRunning())\n self.assertAlmostEqual(t.Read(), time)\n return t\n\n def StoppedTimerWithTime(self, time):\n \"\"\"Returns a timer stopped with a given amount of time already on it.\"\"\"\n t = self.RunningTimerWithTime(time)\n t.Stop()\n # Confirm that this is indeed a stopped timer with the desired time.\n self.assertFalse(t.IsRunning())\n self.assertAlmostEqual(t.Read(), time)\n return t\n\n def test_init(self):\n # Time at init shouldn't matter.\n self.stub_time.current_time = 123.45\n t = timer.Timer('event')\n self.assertFalse(t.IsRunning())\n self.assertAlmostEqual(t.Read(), 0)\n\n def test_stopped_read(self):\n t = self.StoppedTimerWithTime(12.3)\n self.assertAlmostEqual(t.Read(), 12.3)\n # Reading shouldn't change running state.\n self.assertFalse(t.IsRunning())\n\n # Even if time is progressed, it should still read the same value.\n self.stub_time.current_time = 45.6\n self.assertAlmostEqual(t.Read(), 12.3)\n\n def test_stopped_start(self):\n t = self.StoppedTimerWithTime(12.3)\n t.Start()\n self.assertTrue(t.IsRunning())\n # Should not reset time.\n self.assertAlmostEqual(t.Read(), 12.3)\n\n def test_stopped_reset(self):\n t = self.StoppedTimerWithTime(12.3)\n t.Reset()\n # Reset should stop and set to 0.\n self.assertFalse(t.IsRunning())\n self.assertAlmostEqual(t.Read(), 0)\n\n def test_stopped_stop(self):\n t = self.StoppedTimerWithTime(12.3)\n t.Stop()\n # Stop should have no further effect.\n self.assertFalse(t.IsRunning())\n self.assertAlmostEqual(t.Read(), 12.3)\n\n def test_running_read(self):\n t = self.RunningTimerWithTime(12.3)\n self.assertAlmostEqual(t.Read(), 12.3)\n # Read should not change running state.\n self.assertTrue(t.IsRunning())\n\n # If time is progressed, it should read the appropriate value.\n self.stub_time.current_time = 45.6\n self.assertAlmostEqual(t.Read(), 45.6)\n\n def test_running_start(self):\n t = self.RunningTimerWithTime(12.3)\n t.Start()\n # Should have no effect.\n self.assertTrue(t.IsRunning())\n self.assertAlmostEqual(t.Read(), 12.3)\n\n def test_running_reset(self):\n t = self.RunningTimerWithTime(12.3)\n t.Reset()\n # Reset should stop and set to 0.\n self.assertFalse(t.IsRunning())\n self.assertAlmostEqual(t.Read(), 0)\n\n def test_running_stop(self):\n t = self.RunningTimerWithTime(12.3)\n t.Stop()\n # Stop should stop but maintain time.\n self.assertFalse(t.IsRunning())\n self.assertAlmostEqual(t.Read(), 12.3)\n\n def test_combined_read(self):\n t = self.StoppedTimerWithTime(12.3)\n self.stub_time.current_time = 20\n t.Start()\n self.stub_time.current_time = 45.6\n expected_read_time = 12.3 + (45.6 - 20)\n # When a timer has been previously stopped, current running time should\n # be additive.\n self.assertAlmostEqual(t.Read(), expected_read_time)\n # Stopping again shouldn't overwrite this number.\n t.Stop()\n self.stub_time.current_time = 56.7\n self.assertAlmostEqual(t.Read(), expected_read_time)\n","sub_path":"cli/lib/core/timer_unittest.py","file_name":"timer_unittest.py","file_ext":"py","file_size_in_byte":4601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"259229223","text":"import numpy as np\nfrom scipy.sparse import csc_matrix\nfrom sparsesvd import sparsesvd\nimport psycopg2\n\nconn = psycopg2.connect(\"dbname='rateme' user='rateme' host='localhost' password='1'\")\n\ncur = conn.cursor()\ncur.execute(\"\"\"SELECT * from rateme_rating\"\"\")\nrows = cur.fetchall()\n\nusers = []\nusers_set = set()\ncards = []\ncards_set = set()\n\nfor row in rows:\n # (66870, 432, 'neutral', 1545)\n rating_id, user_id, rating_val, card_id = row\n\n user_id = int(user_id)\n card_id = int(card_id)\n \n if user_id not in users_set:\n users.append(user_id)\n users_set.add(user_id)\n \n if card_id not in cards_set:\n cards.append(card_id)\n cards_set.add(card_id)\n\nnum_users = len(users)\nnum_cards = len(cards)\n\nprint(\"There are \" + str(num_users) + \" users and \" + str(num_cards) + \" cards\")\n\n# Rows: users, Columns: cards\n# I.e. users x cards\n\nmatrix = csc_matrix((num_users, num_cards), dtype=np.int8).toarray()\n\nfor row in rows:\n # (66870, 432, 'neutral', 1545)\n rating_id, user_id, rating_val, card_id = row\n\n \n","sub_path":"make_matrix-dict.py","file_name":"make_matrix-dict.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"465130642","text":"from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.db.utils import IntegrityError\n\nfrom thesis.models import Thesis\nfrom teacher.models import Teacher\nfrom message.models import Message\n\nfrom .models import Collection\n\ndef collect(request, object_id):\n user = request.user\n if user.is_authenticated and user.person == 'student':\n try:\n ct = request.GET.get('content_type')\n model = ContentType.objects.get(model=ct).model_class()\n content_object = model.objects.get(pk=object_id)\n Collection.objects.create(content_object=content_object, student = user.student)\n messages.success(request, '收藏成功!')\n except IntegrityError:\n if ct == 'thesis':\n messages.error(request, '你已经收藏过此题!')\n else:\n messages.error(request,'你已经收藏过此教师')\n return redirect(request.META.get('HTTP_REFERER','/')) \n else:\n return redirect('/')\n\ndef cancel_collect(request, ct, object_id):\n user = request.user\n if user.is_authenticated and user.person =='student':\n content_type = ContentType.objects.get(model=ct)\n student = user.student\n collect = Collection.objects.get(content_type=content_type, object_id=object_id,\\\n student=student)\n collect.delete()\n messages.success(request, '取消收藏成功')\n return redirect(request.META.get('HTTP_REFERER','/'))\n else:\n return redirect('/')\n\ndef student_collection(request):\n user = request.user\n if user.is_authenticated and user.person =='student':\n student = user.student\n thesis_collections = Thesis.objects.filter(collection__student=student,\\\n is_choiced=False)\n teacher_collections = Teacher.objects.filter(collection__student=student, \\\n rest_number__gt=0)\n invalid_theses = Thesis.objects.filter(collection__student=student,\\\n is_choiced=True)\n invalid_teachers = Teacher.objects.filter(collection__student=student, \\\n rest_number=0)\n context = {}\n context['thesis_collections'] = thesis_collections\n context['teacher_collections'] = teacher_collections\n context['invalid_theses'] = invalid_theses\n context['invalid_teachers'] = invalid_teachers\n return render(request, 'student/student_collection.html', context)\n else:\n return redirect('/')\n ","sub_path":"student/student_collection_views.py","file_name":"student_collection_views.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"379365611","text":"\r\nfrom django.core.exceptions import ImproperlyConfigured\r\nfrom django.http import request\r\nfrom django.http.response import HttpResponse\r\nfrom django.shortcuts import redirect, render,HttpResponseRedirect\r\nfrom django.urls import reverse,reverse_lazy\r\nfrom .forms import CreateNewUser\r\nfrom django.contrib.auth import authenticate,login,logout\r\nfrom .models import UserProfile,Follow \r\nfrom django.contrib.auth.forms import AuthenticationForm\r\nfrom .forms import EditProfile\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom post.forms import PostForm\r\nfrom django.contrib.auth.models import User\r\n\r\n# Create your views here.\r\n\r\n\r\ndef sign_up(request):\r\n\r\n form = CreateNewUser\r\n registered= False\r\n if request.method == 'POST':\r\n form = CreateNewUser(data = request.POST)\r\n if form.is_valid():\r\n user = form.save()\r\n registered= True\r\n user_profile = UserProfile(user=user)\r\n user_profile.save()\r\n return redirect('app_login:login')\r\n context = {'form':form}\r\n return render(request,'app_login/sign_up.html',context) \r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\ndef login_page(request):\r\n form = AuthenticationForm\r\n if request.method == 'POST':\r\n form= AuthenticationForm(data = request.POST)\r\n if form.is_valid():\r\n username = form.cleaned_data.get('username')\r\n password = form.cleaned_data.get('password')\r\n user = authenticate(request,username=username,password=password)\r\n if user is not None:\r\n login(request,user)\r\n return redirect('app_post:home')\r\n context={\r\n 'form':form\r\n } \r\n return render(request,'app_login/login.html',context) \r\n\r\n\r\n@login_required\r\ndef edit_profile(request):\r\n current_user = UserProfile.objects.get(user=request.user)\r\n form = EditProfile(instance=current_user)\r\n if request.method == 'POST':\r\n form = EditProfile(request.POST,request.FILES,instance=current_user)\r\n if form.is_valid():\r\n form.save(commit=True)\r\n form = EditProfile(instance=current_user)\r\n\r\n\r\n context = {\r\n 'form':form\r\n }\r\n return render(request,'app_login/profile.html',context)\r\n \r\n \r\n@login_required \r\ndef logout_user(request):\r\n logout(request)\r\n return HttpResponseRedirect(reverse('app_login:login'))\r\n\r\n\r\n@login_required\r\ndef profile(request):\r\n form = PostForm\r\n if request.method == 'POST':\r\n form = PostForm(request.POST,request.FILES)\r\n if form.is_valid():\r\n post = form.save(commit=False)\r\n post.author = request.user\r\n post.save()\r\n return HttpResponseRedirect(reverse('app_post:home'))\r\n context = {'form':form}\r\n return render(request,'app_login/user.html',context) \r\n\r\n\r\n\r\n@login_required\r\ndef user(request,username):\r\n user_other = User.objects.get(username=username)\r\n already_followed = Follow.objects.filter(follower=request.user,following = user_other)\r\n if user == request.user:\r\n return HttpResponseRedirect(reverse('app_login:profile'))\r\n context={\r\n 'user_other':user_other,\r\n 'already_followed':already_followed\r\n }\r\n return render(request,'app_login/user_other.html',context)\r\n\r\n\r\n@login_required\r\ndef follow(request,username):\r\n following_user = User.objects.get(username=username)\r\n follower_user = request.user \r\n already_followed = Follow.objects.filter(follower=follower_user,following = following_user)\r\n if not already_followed:\r\n followed_user = Follow(follower=follower_user,following = following_user)\r\n followed_user.save()\r\n return HttpResponseRedirect(reverse('app_login:user',kwargs={'username': username }))\r\n\r\n\r\n@login_required\r\ndef unfollow(request,username):\r\n following_user = User.objects.get(username=username)\r\n follower_user = request.user \r\n already_followed = Follow.objects.filter(follower=follower_user,following = following_user)\r\n already_followed.delete()\r\n return HttpResponseRedirect(reverse('app_login:user',kwargs={'username': username }))\r\n\r\n\r\n","sub_path":"app_login/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"388404534","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 14 12:21:23 2020\n\n@author: jon\n\"\"\"\n\nimport os\nimport time\nfrom pymongo import MongoClient\n\nimport logging\n\nlogging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\nproducts = {\"TEMPO_SWATH_POINT\",\"TEMPO_SWATH_GRID\"}\n\ndef processProducts( products ):\n #poll the esa directories \n tmp_file = \"out.txt\"\n logger.info( os.environ )\n tcp_address = \"mongodb://dataportal_db\"\n client = MongoClient(tcp_address, 27017 )\n \n productDb = client.product\n catalogue = productDb.catalogue\n \n for p in products:\n product_tmp_file = \"{}_{}\".format( p , tmp_file)\n if os.path.isfile( product_tmp_file ):\n os.remove( product_tmp_file )\n \n command = \"rclone --config config/rclone.conf ls esa:{} > {}\".format(p, product_tmp_file)\n \n os.system( command )\n if os.path.isfile( product_tmp_file ):\n def processline( l, product_type ):\n product_path = l.strip().split(\" \")[1]\n return {\"product\" : product_path }\n \n with open(product_tmp_file) as r:\n products = [ processline(l, p) for l in r ]\n existing_products = { p[\"product\"] for p in catalogue.aggregate([{\"$project\" : {\"product\" : 1}}]) }\n filter_products = [ p for p in products if p[\"product\"] not in existing_products and not p[\"product\"].startswith(\"LATEST\")]\n \n if len(filter_products) > 0:\n logger.info( \"About to insert {} products\".format(len(filter_products)))\n catalogue.insert_many( filter_products )\n else:\n logger.info(\"No new products found to process at this time\")\n \n else:\n logger.error(\"rclone failed to find any products under {}\".format(p))\n raise IOError( \"rclone job failed to create output file.\" )\n \ndef main( ):\n \n logger.info( \"Ingestion Process Started\" ) \n processProducts(products)\n while True:\n time.sleep(600)\n logger.info(\"About to process products\")\n processProducts(products)\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"dataportal/ingestion-service/ingestion.py","file_name":"ingestion.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"419475698","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n\tИнстанс хранилища истории изменений всех виджетов\n\t\n\n\"\"\"\n\nimport Tkinter\nimport Tix\n\n\n\n\nclass HistoryInst(object):\n\tinstance = None\n\tdef __new__(cls,*dt,**mp):\n\t\tif cls.instance is None:\n\t\t\tcls.instance = object.__new__(cls,*dt,**mp)\n\t\treturn cls.instance\n\n\thlist = []\n\thredolist = []\n\tignoreEnents_ = False\n\t_buffer_is_enabled = False\n\t_saved_dirty_id = None\n\t_callback_on_dirty = None\n\n\n\tdef setCallbackOnDirty(self, callback):\n\t\tself._callback_on_dirty = callback\n\n\tdef resetHistory(self):\n\t\t\"\"\"сбросить всю историю\"\"\"\n\t\tself.hlist = []\n\t\tself.hredolist = []\n\n\tdef onSaved(self):\n\t\t\"данные сохранены, пометить активное состояние как чистое\"\n\t\tself._saved_dirty_id = self.current_dirty_id\n\t\tif self._callback_on_dirty:\n\t\t\tself._callback_on_dirty(self.isDirty)\n\n\t@property\n\tdef current_dirty_id(self):\n\t\treturn id(self.hlist[-1]) if self.hlist else None\n\n\t@property\n\tdef isDirty(self):\n\t\t\"измененны ли данные после сохранения/загрузки\"\n\t\treturn self.current_dirty_id != self._saved_dirty_id\n\t \n\n\tdef startBufferEvents(self):\n\t\t\"\"\"для отмены изменений группы виджетов(копипаст по вкладке)\"\"\"\n\t\tself._buffer_in_events = []\n\t\tself._buffer_is_enabled = True\n\n\tdef endBufferEvents(self):\n\t\tif self._buffer_in_events:\n\t\t\tself.hlist.append(self._buffer_in_events)\n\t\tself._buffer_is_enabled = False\n\t\tself._buffer_in_events = []\n\t\tif self._callback_on_dirty:\n\t\t\tself._callback_on_dirty(self.isDirty)\n\n\n\tdef onValueChangeEndByUser(self, name, wiget, oldValue, newValue):\n\t\t\"\"\"виджет изменил значение\"\"\"\n\t\tif self.ignoreEnents_: return\n\t\tevent = (\"wiget\", name, wiget, oldValue, newValue)\n\t\tif self._buffer_is_enabled:\n\t\t\tself._buffer_in_events.append(event)\n\t\telse:\n\t\t\tself.hlist.append([event])\n\t\t\tif self._callback_on_dirty:\n\t\t\t\tself._callback_on_dirty(self.isDirty)\n \n\n\n\tdef onNavigateNotebook(self, notebook ,frompage , topage):\n\t\t\"\"\"переключение вкладки\"\"\"\n\t\tif self.ignoreEnents_: return\n\t\tif frompage == \"NONETAB\": return\n\t\tif frompage == topage: return\n\t\t# print \"page\",[notebook], [frompage ],\"=>\", [topage]\n\t\tevents = [(\"page\",notebook, frompage , topage)]\n\t\t# TODO переключение вкладки не должно флагать isDirty\n\t\tself.hlist.append(events)\n\t\tif self._callback_on_dirty:\n\t\t\t\tself._callback_on_dirty(self.isDirty)\n\n\n\n\n\n\tdef _changeWiget(self, data, undo = True):\n\t\tname_event, name, wiget, oldValue, newValue = data\n\t\tif undo:\n\t\t\twiget.setUndo(oldValue)\n\t\t\t# wiget.blink(\"red\")\n\t\t\twiget.blink(\"#ffcccc\")\n\t\telse:\n\t\t\twiget.setUndo(newValue)\n\t\t\t# wiget.blink(\"green\")\n\t\t\twiget.blink(\"#99ff99\")\n\n\tdef _changePage(self, data, undo = True):\n\t\tname_event, notebook, frompage , topage = data\n\t\tif undo:\n\t\t\t# notebook.raise_page(frompage)\n\t\t\tnotebook.select(frompage)\n\t\telse:\n\t\t\t# notebook.raise_page(topage)\n\t\t\tnotebook.select(topage)\n\n\tdef isCanUndo(self):\n\t\tif self.hlist:\n\t\t\treturn True\n\n\tdef isCanRedo(self):\n\t\tif self.hredolist:\n\t\t\treturn True\n\n\tdef undo(self):\n\t\t\"откатится назад на шаг\"\n\t\tif not self.hlist:\n\t\t\treturn\n\t\tself.ignoreEnents_ = True\n\t\tdata = self.hlist.pop()\n\t\tself.hredolist.append(data)\n\t\tfor event in data:\n\t\t\tif event[0] == \"wiget\":\n\t\t\t\tself._changeWiget(event)\n\t\t\telif event[0] == \"page\":\n\t\t\t\tself._changePage(event)\n\n\t\tTkinter._default_root.after(10, self._offIgnore)\n\n\n\tdef redo(self):\n\t\t\"откатится вперед на шаг\"\n\t\tif not self.hredolist:\n\t\t\treturn\n\t\tself.ignoreEnents_ = True\n\t\tdata = self.hredolist.pop()\n\t\tself.hlist.append(data)\n\t\tfor event in data:\n\t\t\tif event[0] == \"wiget\":\n\t\t\t\tself._changeWiget(event, False)\n\t\t\telif event[0] == \"page\":\n\t\t\t\tself._changePage(event, False)\n\n\t\tTkinter._default_root.after(10, self._offIgnore)\n\n\n\tdef _offIgnore(self):\n\t\tself.ignoreEnents_ = False\n\t\tif self._callback_on_dirty:\n\t\t\tself._callback_on_dirty(self.isDirty)\n\n\n\nhistory = HistoryInst()\n","sub_path":"widgets/history_inst.py","file_name":"history_inst.py","file_ext":"py","file_size_in_byte":4050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"484048496","text":"#!pyton3\n\nfrom flask import *\nimport pymysql\nimport pymysql.cursors\nfrom config import *\nimport pprint\n\napp = Flask(__name__)\napp.config.from_object(__name__)\n\n# 连接数据库\ndef connectdb():\n db = pymysql.connect(host=HOST,\n user=USER,\n passwd=PASSWORD,\n db=DATABASE,\n port=PORT,\n charset=CHARSET,\n cursorclass=pymysql.cursors.DictCursor)\n db.autocommit(True)\n cursor = db.cursor()\n return (db, cursor)\n\n# 关闭数据库\ndef closedb(db, cursor):\n db.close()\n cursor.close()\n\n# 首页\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n# 评分页面\n@app.route('/rate')\ndef rate():\n (db,cursor) = connectdb()\n try:\n cursor.execute(\"select rate, district, category, showtime, length from movie \" + \\\n \"where showtime<>'未知' and length<>'-1'\")\n movies = cursor.fetchall()\n movies = json.dumps({\"movies\": movies})\n cursor.execute(\"select name,\" + \\\n \"group_concat(concat_ws(',', category)) categories,\" + \\\n \"group_concat(concat_ws(',', rate)) rates \" + \\\n \"from rate \" + \\\n \"where category<>'未知' \" + \\\n \"group by name\")\n rates = cursor.fetchall()\n temp = {}\n for item in rates:\n temp[item['name']] = {}\n temp[item['name']]['categories'] = item['categories'].split(',')\n temp[item['name']]['rates'] = item['rates'].split(',')\n temp[item['name']]['rates'] = list( map(float, temp[item['name']]['rates']) )\n rates = temp\n rates = json.dumps({\"rates\": rates})\n finally:\n closedb(db,cursor)\n categories = ['剧情','喜剧','惊悚','爱情','动作','悬疑','犯罪','恐怖','科幻','冒险','奇幻','家庭','动画','战争','历史','古装','传记','音乐','同性','武侠','情色','灾难','运动','歌舞','西部','儿童','黑色电影','鬼怪','荒诞']\n districts = ['United States of America','China','Japan','South Korea','United Kingdom','France','Germany','Spain','Italy','Thailand','Canada','Russia','India','Australia','Ireland','Poland','Finland','Denmark','New Zealand','Czech Republic','Brazil','Sweden','Iran','Argentina','Belgium','Slovakia','Mexico','Norway','Austria','Netherlands','Chile','Hungary','Greece','Indonesia','Turkey','Switzerland','Iceland','Botswana','Malaysia','Israel','Romania','United Arab Emirates','Bulgaria','Myanmar','Bhutan','Armenia','Philippines','Panama','Portugal','Colombia','Luxembourg','Estonia','Uruguay','Slovenia','Georgia','Cuba','Vietnam']\n return render_template('rate.html',movies=movies,categories=categories,districts=districts,rates=rates)\n\n# 搜索页面\n@app.route('/search')\ndef search():\n (db,cursor) = connectdb()\n try:\n cursor.execute(\"select * from movie order by rate desc limit 10\")\n movies = cursor.fetchall()\n for item in movies:\n item['description'] = item['description'].split('/')\n finally:\n closedb(db,cursor)\n return render_template('search.html',movies=movies)\n\n@app.route('/keyword',methods=['POST'])\ndef keyword():\n data = request.form\n print(data['keyword'])\n (db,cursor) = connectdb()\n try:\n sql = \"select * from movie where title like '%%%s%%' order by rate desc\"\n cursor.execute(sql % data['keyword'])\n movies = cursor.fetchall()\n for item in movies:\n item['description'] = item['description'].split('/')\n finally:\n closedb(db,cursor)\n return json.dumps({\"movies\": movies})\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"web/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"266851349","text":"from setuptools import setup\n\n__version__ = '0.3.6'\nlong_description = file('README.markdown','r').read()\n\nsetup(name='cli53',\n version=__version__,\n description='Command line script to administer the Amazon Route 53 DNS service',\n long_description=long_description,\n license='MIT',\n author='Barnaby Gray',\n author_email='barnaby@pickle.me.uk',\n url='http://loads.pickle.me.uk/cli53/',\n install_requires=['boto', 'argparse', 'dnspython'],\n scripts=['scripts/cli53'],\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Topic :: Utilities\",\n \"License :: OSI Approved :: MIT License\",\n ],\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"332615219","text":"from PredRNN_Model import PredRNN\r\nimport torch.optim as optim\r\nimport torch.nn as nn\r\nimport matplotlib.pyplot as plt\r\nimport torch\r\n\r\n\r\ninput=torch.rand(1,10,1,100,100).cuda()\r\ntarget=torch.rand(1,10,1,100,100).cuda()\r\nclass PredRNN_enc(nn.Module):\r\n def __init__(self):\r\n super(PredRNN_enc, self).__init__()\r\n self.pred1_enc=PredRNN(input_size=(100,100),\r\n input_dim=1,\r\n hidden_dim=[7,1],\r\n hidden_dim_m=[7,7],\r\n kernel_size=(7,7),\r\n num_layers=2,\r\n batch_first=True,\r\n bias=True).cuda()\r\n def forward(self,enc_input):\r\n _, layer_h_c, last_h_m, _ = self.pred1_enc(enc_input)\r\n return layer_h_c, last_h_m\r\n\r\nclass PredRNN_dec(nn.Module):\r\n def __init__(self):\r\n super(PredRNN_dec, self).__init__()\r\n self.pred1_dec=PredRNN(input_size=(100,100),\r\n input_dim=1,\r\n hidden_dim=[7,1],\r\n hidden_dim_m=[7,7],\r\n kernel_size=(7,7),\r\n num_layers=2,\r\n batch_first=True,\r\n bias=True).cuda()\r\n self.relu = nn.ReLU()\r\n def forward(self,dec_input,enc_hidden,enc_h_m):\r\n out, layer_h_c, last_h_m, _ = self.pred1_dec(dec_input,enc_hidden,enc_h_m)\r\n out = self.relu(out)\r\n return out, layer_h_c, last_h_m\r\n\r\nenc=PredRNN_enc().cuda()\r\ndec=PredRNN_dec().cuda()\r\n\r\nimport itertools\r\nloss_fn=nn.MSELoss()\r\nposition=0\r\noptimizer=optim.Adam(itertools.chain(enc.parameters(), dec.parameters()),lr=0.001)\r\nfor epoch in range(100):\r\n loss_total=0\r\n enc_hidden, enc_h_y = enc(input)\r\n for i in range(input.shape[1]):\r\n optimizer.zero_grad()\r\n out,layer_h_c,last_h_y = dec(input[:,i:i+1,:,:,:], enc_hidden, enc_h_y)\r\n loss=loss_fn(out,target[:,i:i+1,:,:,:])\r\n loss_total+=loss\r\n enc_hidden = layer_h_c\r\n enc_h_y = last_h_y\r\n loss_total=loss_total/input.shape[1]\r\n loss_total.backward()\r\n optimizer.step()\r\n print(epoch,epoch,loss_total)\r\n\r\n","sub_path":"PredRNN_Seq2seq.py","file_name":"PredRNN_Seq2seq.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"399839872","text":"import gspread\nimport logging\nimport GDocsException\nfrom gspread.exceptions import SpreadsheetNotFound\n\nclass GDocs(object):\n \n log = logging.getLogger(\"GDocs\")\n worksheet = None\n \n def __init__(self, email, api_key):\n self._email = email\n self._api_key = api_key\n \n def initialize(self):\n \"\"\"Connect to Google Docs spreadsheet and return the first worksheet.\"\"\"\n self.gc = gspread.login(self._email, self._api_key)\n self.log.info(\"Connected to Google Docs.\")\n \n def open_spreadsheet(self, spreadsheet_name):\n try:\n self.worksheet = self.gc.open(spreadsheet_name).sheet1\n self.log.info\n except SpreadsheetNotFound as e:\n self.log.error(\"Spreadsheet not found.\", e)\n raise GDocsException(e)\n \n def write_value(self, col, row, value):\n self.worksheet.update_cell(row, col, value)\n self.log.debug(\"Value '{0}' was written into cell [{1},{2}].\".format(value, col, row))\n ","sub_path":"GDocs/GDocs.py","file_name":"GDocs.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"137349439","text":"\"\"\"Web app and utilities for rainbow colormap monitor\r\n\"\"\"\r\n\r\nimport os\r\nimport os.path\r\nimport re\r\nimport math\r\nimport itertools\r\n\r\nimport flask\r\nfrom flask_rq2 import RQ\r\nfrom flask_mail import Mail, Message\r\nfrom flask_wtf.csrf import CSRFProtect, CSRFError\r\n\r\nfrom waitress import serve\r\n\r\nfrom sqlalchemy import desc\r\n\r\nimport tweepy\r\n\r\nimport click\r\nimport pytest\r\n\r\nfrom models import db, Biorxiv, Test\r\nfrom biorxiv_scraper import find_authors, find_date, count_pages\r\nfrom detect_bargraph import detect_graph_types_from_iiif\r\nimport utils\r\n\r\nfrom fastai.vision import *\r\n#ml_path = os.environ['WEBAPP_PATH']\r\nlearn = load_learner(path='/data01/webapp/barzooka/', file='export.pkl')\r\n\r\n# Reads env file into environment, if found\r\n_ = utils.read_env()\r\n\r\napp = flask.Flask(__name__)\r\napp.config['BASE_URL'] = os.environ['BASE_URL']\r\n\r\n# For data storage\r\napp.config['SQLALCHEMY_DATABASE_URI'] = os.environ['SQLALCHEMY_DATABASE_URI']\r\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True\r\ndb.init_app(app)\r\n\r\n# For job handling\r\napp.config['RQ_REDIS_URL'] = os.environ['RQ_REDIS_URL']\r\nrq = RQ(app)\r\n\r\n# For monitoring papers (until Biorxiv provides a real API)\r\napp.config['TWITTER_APP_KEY'] = os.environ['TWITTER_APP_KEY']\r\napp.config['TWITTER_APP_SECRET'] = os.environ['TWITTER_APP_SECRET']\r\napp.config['TWITTER_KEY'] = os.environ['TWITTER_KEY']\r\napp.config['TWITTER_SECRET'] = os.environ['TWITTER_SECRET']\r\n\r\napp.config['DEBUG'] = os.environ.get('DEBUG', 0)\r\n\r\napp.config['WEB_PASSWORD'] = os.environ['WEB_PASSWORD']\r\n\r\napp.config['SECRET_KEY'] = os.environ['SECRET_KEY']\r\ncsrf = CSRFProtect(app)\r\n\r\ntweepy_auth = tweepy.OAuthHandler(\r\n app.config['TWITTER_APP_KEY'], app.config['TWITTER_APP_SECRET'])\r\ntweepy_auth.set_access_token(\r\n app.config['TWITTER_KEY'], app.config['TWITTER_SECRET'])\r\ntweepy_api = tweepy.API(tweepy_auth)\r\n\r\n@app.route('/')\r\ndef home():\r\n \"\"\"Renders the website with current results\r\n \"\"\"\r\n\r\n cats = flask.request.args.get('categories')\r\n if cats:\r\n cats = [int(x) for x in cats.split(',')]\r\n else:\r\n cats = [-2, -1, 0, 1, 2]\r\n\r\n papers = (Biorxiv.query\r\n .filter(Biorxiv.parse_status.in_(cats))\r\n .order_by(desc(Biorxiv.created))\r\n .limit(5000)\r\n .all())\r\n\r\n return flask.render_template('main.html', app=app, papers=papers)\r\n\r\n@app.route('/pages/')\r\ndef pages(paper_id, prepost=1, maxshow=10):\r\n \"\"\"Pages to show for preview\r\n 1-index I think...\r\n \"\"\"\r\n record = Biorxiv.query.filter_by(id=paper_id).first()\r\n if not record:\r\n return flask.jsonify({})\r\n\r\n pages = record.pages\r\n page_count = record.page_count\r\n\r\n # if requested, show all pages with each page's status\r\n try:\r\n all_pages = flask.request.args.get('all') == \"1\"\r\n except:\r\n all_pages = False\r\n\r\n show_pgs = {}\r\n if all_pages:\r\n for i in range(1, page_count + 1):\r\n if i in pages:\r\n show_pgs[i] = True\r\n else:\r\n show_pgs[i] = False\r\n elif pages:\r\n # add all detected pages up to maxshow count\r\n show_pgs = {i:True for i in pages[:maxshow]}\r\n # pad with undetected pages\r\n for i in pages:\r\n for j in range(i - prepost, min(i + prepost + 1, page_count)):\r\n if len(show_pgs) < maxshow:\r\n if j not in pages:\r\n show_pgs[j] = False\r\n else:\r\n break\r\n else:\r\n show_pgs = {i:False for i in range(1, maxshow + 1)}\r\n\r\n return flask.jsonify({'pdf_url': record.pdf_url, 'pages': show_pgs})\r\n\r\n@app.route('/detail/')\r\ndef show_details(paper_id, prepost=1, maxshow=10):\r\n \"\"\"\r\n \"\"\"\r\n record = Biorxiv.query.filter_by(id=paper_id).first()\r\n if not record:\r\n flask.flash('Sorry! Results with that ID have not been found')\r\n return flask.redirect('/')\r\n\r\n\r\n # display images\r\n return flask.render_template('detail.html',\r\n paper_id=record.id, title=record.title, url=record.url,\r\n pages=\", \".join([str(p) for p in record.pages]),\r\n pages_pie=\", \".join([str(p) for p in record.pages_pie]),\r\n pages_bardot=\", \".join([str(p) for p in record.pages_bardot]),\r\n pages_box=\", \".join([str(p) for p in record.pages_box]),\r\n pages_hist=\", \".join([str(p) for p in record.pages_hist]),\r\n pages_dot=\", \".join([str(p) for p in record.pages_dot]),\r\n pages_violin=\", \".join([str(p) for p in record.pages_violin]),\r\n pages_positive=\", \".join([str(p) for p in record.pages_positive]),\r\n parse_status=record.parse_status, email_sent=record.email_sent\r\n )\r\n\r\n@app.route('/notify/', methods=['POST'])\r\n@app.route('/notify//', methods=['POST'])\r\ndef notify_authors(paper_id, force=0):\r\n if flask.session.get('logged_in'):\r\n record = Biorxiv.query.filter_by(id=paper_id).first()\r\n if not record:\r\n return flask.jsonify(result=False, message=\"paper not found\")\r\n\r\n addr = record.author_contact.values()\r\n addr = list(itertools.chain.from_iterable(addr))\r\n # don't bother everyone if there are a ton of authors\r\n if len(addr) > 6:\r\n addr = [*addr[:2], *addr[-3:]]\r\n\r\n if addr is [] or '@' not in \"\".join(addr):\r\n return flask.jsonify(result=False,\r\n message=\"mangled or missing email addresses\")\r\n\r\n if force != 1 and record.email_sent == 1:\r\n return flask.jsonify(result=False,\r\n message=\"email already sent. use the cli to send another\")\r\n\r\n msg = Message(\r\n \"[JetFighter] bioRxiv manuscript {}\".format(record.id),\r\n recipients=addr,\r\n reply_to=app.config['MAIL_REPLY_TO'])\r\n msg.body = flask.render_template(\"email_notification.txt\",\r\n paper_id=paper_id,\r\n pages=record.pages_str,\r\n title=record.title,\r\n detail_url=flask.url_for('show_details', paper_id=paper_id))\r\n mail.send(msg)\r\n\r\n record.email_sent = 1\r\n db.session.merge(record)\r\n db.session.commit()\r\n\r\n return flask.jsonify(result=True, message=\"successfully sent\")\r\n else:\r\n return flask.jsonify(result=False, message=\"not logged in\")\r\n\r\n@app.route('/toggle/', methods=['POST'])\r\ndef toggle_status(paper_id):\r\n if flask.session.get('logged_in'):\r\n record = Biorxiv.query.filter_by(id=paper_id).first()\r\n if not record:\r\n return flask.jsonify(result=False, message=\"paper not found\")\r\n if record.parse_status > 0:\r\n record.parse_status = -2\r\n elif record.parse_status < 0:\r\n record.parse_status = 2\r\n else:\r\n return flask.jsonify(result=False, message=\"Not yet parsed\")\r\n db.session.merge(record)\r\n db.session.commit()\r\n\r\n return flask.jsonify(result=True, message=\"successfully changed\")\r\n else:\r\n return flask.jsonify(result=False, message=\"not logged in\")\r\n\r\n\r\n\r\n@app.route('/login', methods=['GET', 'POST'])\r\ndef admin_login():\r\n if flask.request.method == 'GET':\r\n if flask.session.get('logged_in'):\r\n flask.flash('You are already logged in!')\r\n return flask.redirect('/')\r\n return flask.render_template('login.html')\r\n\r\n if flask.request.form['password'] == app.config['WEB_PASSWORD']:\r\n flask.session['logged_in'] = True\r\n else:\r\n flask.flash('wrong password!')\r\n return flask.render_template('login.html')\r\n\r\n return flask.redirect('/')\r\n\r\n@app.route('/logout', methods=['GET'])\r\ndef logout():\r\n logged_in = flask.session.get('logged_in')\r\n flask.session.clear()\r\n if logged_in:\r\n flask.flash(\"You have been successfully logged out\")\r\n else:\r\n flask.flash(\"Not logged in! (but the session has been cleared)\")\r\n return flask.redirect('/')\r\n\r\n@app.errorhandler(CSRFError)\r\ndef handle_csrf_error(e):\r\n flask.flash('CSRF Error. Try again?')\r\n return flask.redirect(flask.url_for('admin_login'))\r\n\r\n\r\n\r\n@app.cli.command()\r\n@click.option('--count', default=500)\r\ndef retrieve_timeline(count):\r\n \"\"\"Picks up current timeline (for testing)\r\n \"\"\"\r\n # as we currently have to wait for a long time until the parsing is done\r\n # go through tweets twice: first only add basic info to SQL database,\r\n # second, parse pdf for bargraphs\r\n for t in tweepy.Cursor(tweepy_api.user_timeline,\r\n screen_name='biorxivpreprint', trim_user='True',\r\n include_entities=True, tweet_mode='extended').items(count):\r\n parse_tweet(t)\r\n\r\n\r\ndef parse_tweet(t, db=db, objclass=Biorxiv, verbose=True):\r\n \"\"\"Parses tweets for relevant data,\r\n writes each paper to the database,\r\n dispatches a processing job to the processing queue (rq)\r\n \"\"\"\r\n try:\r\n text = t.extended_tweet[\"full_text\"]\r\n except AttributeError:\r\n pass\r\n\r\n try:\r\n text = t.full_text\r\n except AttributeError:\r\n text = t.text\r\n\r\n if verbose:\r\n print(t.id_str, text[:25], end='\\r')\r\n if not db:\r\n return\r\n\r\n try:\r\n url = t.entities['urls'][0]['expanded_url']\r\n code = os.path.basename(url)\r\n except:\r\n print('Error parsing url/code from tweet_id', t.id_str)\r\n return\r\n\r\n try:\r\n title = re.findall('(.*?)\\shttp', text)[0]\r\n except:\r\n # keep ASCII only (happens with some Test tweets)\r\n title = re.sub(r'[^\\x00-\\x7f]', r'', text)\r\n\r\n obj = objclass(\r\n id=code,\r\n created=t.created_at,\r\n title=title,\r\n )\r\n\r\n obj = db.session.merge(obj)\r\n db.session.commit()\r\n\r\n # Only add to queue if not yet processed and if we actually want to do all the processing\r\n if obj.parse_status == 0:\r\n process_paper.queue(obj)\r\n\r\n\r\n@rq.job(timeout='30m')\r\ndef process_paper(obj):\r\n #Processes paper starting from url/code\r\n #\r\n #1. get object, find page count and posted date\r\n #2. detect graph classes\r\n #3. if bargraph, get authors\r\n #4. update database entry with graph detection and author info\r\n with app.app_context():\r\n obj = db.session.merge(obj)\r\n\r\n if obj.page_count == 0:\r\n obj.page_count = count_pages(obj.id)\r\n\r\n if obj.posted_date == \"\":\r\n obj.posted_date = find_date(obj.id)\r\n\r\n class_pages = detect_graph_types_from_iiif(obj.id, obj.page_count, learn)\r\n\r\n obj.pages = class_pages[\"bar\"]\r\n obj.pages_pie = class_pages[\"pie\"]\r\n obj.pages_hist = class_pages[\"hist\"]\r\n obj.pages_bardot = class_pages[\"bardot\"]\r\n obj.pages_box = class_pages[\"box\"]\r\n obj.pages_dot = class_pages[\"dot\"]\r\n obj.pages_violin = class_pages[\"violin\"]\r\n obj.pages_positive = class_pages[\"positive\"]\r\n\r\n\r\n if (len(obj.pages) + len(obj.pages_pie)) > 0:\r\n obj.parse_status = 1\r\n if obj.author_contact is None:\r\n obj.author_contact = find_authors(obj.id)\r\n else:\r\n obj.parse_status = -1\r\n\r\n db.session.merge(obj)\r\n db.session.commit()\r\n\r\n\r\n## NOTE: NEEDS WORK\r\n@pytest.fixture()\r\ndef test_setup_cleanup():\r\n # should only be one, but... just in case\r\n for obj in Test.query.filter_by(id='172627v1').all():\r\n db.session.delete(obj)\r\n db.session.commit()\r\n\r\n # Delete temporary row\r\n for obj in Test.query.filter_by(id='172627v1').all():\r\n db.session.delete(obj)\r\n db.session.commit()\r\n\r\ndef test_integration(test_setup_cleanup):\r\n \"\"\"Submit job for known jet colormap. Remove from database beforehand.\r\n Write to database.\r\n Check for written authors.\r\n \"\"\"\r\n\r\n #testq = rq.Queue('testq', is_async=False)\r\n\r\n preobj = Test(id='172627v1')\r\n testq.enqueue(process_paper, preobj)\r\n\r\n postobj = Test.query.filter_by(id='172627v1').first()\r\n\r\n # check that document was correctly identified as having a rainbow colormap\r\n assert postobj.parse_status\r\n\r\n # check that authors were correctly retrieved\r\n authors = postobj.author_contact\r\n assert authors['corr'] == ['t.ellis@imperial.ac.uk']\r\n assert set(authors['all']) == set([\r\n 'o.borkowski@imperial.ac.uk', 'carlos.bricio@gmail.com',\r\n 'g.stan@imperial.ac.uk', 't.ellis@imperial.ac.uk'])\r\n\r\nif __name__ == \"__main__\":\r\n #app.run(debug=True, threaded=True, use_reloader=True)\r\n serve(app, host='127.0.0.1', port=5000, url_scheme='https')","sub_path":"webapp.py","file_name":"webapp.py","file_ext":"py","file_size_in_byte":12601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"384212386","text":"import random\r\n\r\nCHOICE = [\"rock\", \"paper\", \"scissors\"]\r\nCONVERTTABLE = {\r\n \"rock\" :\"paper\",\r\n \"paper\" :\"scissors\",\r\n \"scissors\":\"rock\"\r\n }\r\n\r\nplayerHistory = [\"rock\", \"paper\", \"scissors\"]\r\nresultHistory = {\r\n \"wins\":0,\r\n \"losses\":0,\r\n \"ties\":0\r\n }\r\n\r\ndef interpreter(player, ai):\r\n if (player == \"rock\" and ai == \"scissors\") or (player == \"scissors\" and ai == \"paper\") or (player == \"paper\" and ai == \"rock\"):\r\n return \"Player wins\"\r\n elif (ai == \"rock\" and player == \"scissors\") or (ai == \"scissors\" and player == \"paper\") or (ai == \"paper\" and player == \"rock\"):\r\n return \"AI wins\"\r\n else:\r\n return \"Tie\"\r\n\r\nloop = 0\r\n\r\nwhile True:\r\n print (\"Pick an item.\")\r\n for i in range(len(CHOICE)):\r\n print (\"{}. {}\".format(i+1, CHOICE[i]))\r\n userInput = input()\r\n while userInput not in [\"1\", \"2\", \"3\"]:\r\n print (\"Please enter a valid number.\")\r\n userInput = input()\r\n\r\n playerChoice = CHOICE[int(userInput)-1]\r\n playerHistory.append(CONVERTTABLE[playerChoice])\r\n aiChoice = random.choice(playerHistory)\r\n\r\n result = interpreter(playerChoice, aiChoice)\r\n\r\n print (\"\\nYou played: {}\\nAI played: {}\\n{}\\n\".format(playerChoice, aiChoice, result))\r\n \r\n if result == \"Player wins\":\r\n resultHistory[\"wins\"] += 1\r\n elif result == \"AI wins\":\r\n resultHistory[\"losses\"] += 1\r\n else:\r\n resultHistory[\"ties\"] += 1\r\n\r\n loop += 1\r\n\r\n if loop % 10 == 0:\r\n print ()\r\n for i in [\"wins\", \"losses\", \"ties\"]:\r\n print (\"{}: {}\".format(i, resultHistory[i]))\r\n print ()\r\n","sub_path":"Python/Rock Paper Scissors AI/RockPaperScissors.py","file_name":"RockPaperScissors.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"95426773","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSphinx plugins for Riot documentation.\n\"\"\"\nimport re\nimport sphinx\nfrom docutils import nodes\nfrom sphinx.highlighting import lexers\nfrom freemarker import FreeMarkerHtmlLexer\n\ndef setup(app):\n app.add_config_value('apirefs', {}, 'env')\n app.add_config_value('eval_conf_values', 'release html_title', 'env')\n \n app.connect('builder-inited', init)\n lexers['ftl'] = FreeMarkerHtmlLexer()\n \ndef init(app):\n cfg = app.config\n \n def resolve_conf_values(s, cfg):\n return re.sub('\\$\\{(.+?)\\}', lambda m: cfg[m.group(1)], s)\n\n for key in cfg.eval_conf_values.split():\n cfg[key] = resolve_conf_values(cfg[key], cfg)\n \n def role(role, rawtext, text, lineno, inliner, options={}, content=[]):\n m = re.search('^(.*\\.(.*?))(?:#(\\S*))?(?:\\s(.*))?$', text)\n (fqn, classname, method, label) = m.group(1, 2, 3, 4)\n \n path = fqn.replace('.', '/').replace('@', '')\n hash = ''\n if method:\n hash = '#' + method\n classname += '.' + method\n \n for lib, uri in cfg.apirefs.iteritems():\n if fqn.find(lib) != -1:\n uri = resolve_conf_values(uri, cfg)\n ref = '%s/index.html?%s%s' % (uri, path, hash)\n node = nodes.reference(rawtext, label or classname, refuri=ref, **options)\n node['classes'] += ['api', lib]\n return [node], []\n \n app.add_role('api', role)\n","sub_path":"docs/src/_ext/riotdocs.py","file_name":"riotdocs.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"278488959","text":"import logging\r\nclass NullHandler(logging.Handler):\r\n def emit(self, record):\r\n pass\r\nlog = logging.getLogger('moteProbeSocketThread')\r\nlog.setLevel(logging.ERROR)\r\nlog.addHandler(NullHandler())\r\n\r\nimport threading\r\nimport socket\r\n\r\nfrom pydispatch import dispatcher\r\n\r\nclass moteProbeSocketThread(threading.Thread):\r\n \r\n def __init__(self,socketport,serialportName):\r\n \r\n # log\r\n log.debug(\"create instance\")\r\n \r\n # store params\r\n self.socketport = socketport\r\n self.serialportName = serialportName\r\n \r\n # local variables\r\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n self.conn = None\r\n \r\n # initialize the parent class\r\n threading.Thread.__init__(self)\r\n \r\n # give this thread a name\r\n self.name = 'moteProbeSocketThread@'+str(self.socketport)\r\n \r\n # subscribe to dispatcher\r\n dispatcher.connect(\r\n self.send,\r\n signal='bytesFromSerialPort'+self.serialportName,\r\n )\r\n \r\n def run(self):\r\n \r\n # log\r\n log.debug(\"start running\")\r\n \r\n # attach to a socket on all interfaces of the computer\r\n self.socket.bind(('',self.socketport))\r\n \r\n # listen for incoming connection requests\r\n self.socket.listen(1)\r\n \r\n while True:\r\n # wait for OpenVisualizer to connect\r\n self.conn,self.addr = self.socket.accept()\r\n \r\n # log\r\n log.info(\"openVisualizer connection from {0}\".format(self.addr))\r\n \r\n # read data sent from OpenVisualizer\r\n while True:\r\n \r\n try:\r\n bytesReceived = self.conn.recv(4096)\r\n \r\n # dispatch\r\n dispatcher.send(\r\n signal = 'bytesFromTcpPort'+self.serialportName,\r\n data = bytesReceived\r\n )\r\n \r\n except socket.error as err:\r\n \r\n # log\r\n log.info(\"openVisualizer disconnected\")\r\n \r\n self.conn = None\r\n break\r\n \r\n #======================== public ==========================================\r\n \r\n def send(self,data):\r\n if self.conn!=None:\r\n try:\r\n self.conn.send(data)\r\n except socket.error:\r\n # happens when not connected\r\n pass\r\n \r\n #======================== private =========================================","sub_path":"software/openvisualizer/moteProbe/moteProbeSocketThread.py","file_name":"moteProbeSocketThread.py","file_ext":"py","file_size_in_byte":2751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"541726294","text":"import numpy as np\nfrom numpy.testing import assert_array_equal\n\nfrom qndiag import ajd_pham\n\n\ndef test_ajd():\n \"\"\"Test approximate joint diagonalization.\"\"\"\n n, p = 10, 3\n rng = np.random.RandomState(42)\n diagonals = rng.uniform(size=(n, p))\n A = rng.randn(p, p) # mixing matrix\n C = np.array([A.dot(d[:, None] * A.T) for d in diagonals]) # dataset\n B, _ = ajd_pham(C)\n BA = np.abs(B.dot(A)) # BA Should be a permutation + scale matrix\n BA /= np.max(BA, axis=1, keepdims=True)\n BA[np.abs(BA) < 1e-8] = 0.\n assert_array_equal(BA[np.lexsort(BA)], np.eye(p))\n","sub_path":"qndiag/tests/test_pham.py","file_name":"test_pham.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"624982014","text":"#!/usr/bin/env python\n# coding : utf-8\nimport sys\n\ninput_lines = sys.stdin.read().rstrip().split(\"\\n\")\nresult = []\nfor line in input_lines:\n if line == \"0 0\":\n break\n h, w = [int(x) for x in line.rstrip().split(\" \")]\n single_draw = \"#\" * w\n total_draw_list = [single_draw] * h\n total_draw = \"\\n\".join(total_draw_list)\n result.append(total_draw + \"\\n\")\n\nprint(\"\\n\".join(result))\n","sub_path":"ITP1/ITP1_5_A.py","file_name":"ITP1_5_A.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"458190881","text":"# Checks if a string is a palindrome or not\n\ndef isPalindrome(s: str) -> bool:\n if(s == \"\" or len(s) == 1):\n return True\n elif(s[0] == s[-1]):\n return isPalindrome(s[1: len(s) -1])\n else:\n return False\n\n\nprint(str(isPalindrome(\"1000021\")))","sub_path":"Problem Set Two/is_palindrome.py","file_name":"is_palindrome.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"522695019","text":"from typing import List\n\n\nclass Solution:\n def findMaxLength(self, nums: List[int]) -> int:\n array_sum = 0\n sum_index_table = {0: -1}\n ans = 0\n for i in range(len(nums)):\n array_sum += 1 if nums[i] == 1 else -1\n if array_sum not in sum_index_table:\n sum_index_table[array_sum] = i\n else:\n ans = max(ans, i - sum_index_table[array_sum])\n\n return ans\n\n\nif __name__ == \"__main__\":\n try:\n Solution = Solution()\n nums = [0, 1]\n print(Solution.findMaxLength(nums))\n except Exception as e:\n print(e)\n finally:\n pass\n","sub_path":"event/30-Day LeetCoding Challenge/Week 2/medium_525_Contiguous Array.py","file_name":"medium_525_Contiguous Array.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"274026124","text":"from .models import Service\n\n\nclass ServicesMixin(object):\n\n\tdef get_context_data(self, **kwargs):\n\t\tcontext = super(ServicesMixin, self).get_context_data(**kwargs)\n\t\t\n\t\tcontext['services'] = Service.objects.filter(enabled=True)\n\n\t\treturn context","sub_path":"designpt/services/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"163429113","text":"\"\"\"Script to create template queries from 2-hop slot-filling queries.\"\"\"\n\nimport json\nimport argparse\nimport random\nimport collections\n\nrandom.seed(123)\n\ndef create_squad_questions(subject_list, relation_template, ans_object, id):\n qas = []\n _to_answer = lambda x: {\"answer_start\": 0, \"text\": x}\n ii = 0\n for subj in subject_list:\n for tmpl in relation_template:\n qas.append({\n \"question\": tmpl.replace(\"XXX\", subj[1]),\n \"subject_confidence\": subj[0],\n \"id\": id + \"_\" + str(ii),\n \"answers\": [_to_answer(ans)\n for ans in list(ans_object[\"aliases\"].keys()) + [ans_object[\"name\"]]],\n })\n ii += 1\n return {\"context\": \"dummy\", \"qas\": qas}\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"slot_filling_file\", type=str, help=\"path to slot filling qrys.\")\n parser.add_argument(\"out_file\", type=str, help=\"path to output qrys.\")\n parser.add_argument(\"hop\", type=int, help=\"which hop to create template from.\")\n parser.add_argument(\"--template_file\", type=str, default=None,\n help=\"JSON file with relation templates.\")\n parser.add_argument(\"--answer_file\", type=str, default=None,\n help=\"answer predictions from previous hop.\")\n parser.add_argument(\"--top_k\", type=int, default=1,\n help=\"number of answers to generate templates from.\")\n parser.add_argument(\"--num_templates\", type=int, default=1,\n help=\"Max number of templates to use per question\")\n parser.add_argument(\"--max_ques\", type=int, default=None,\n help=\"Max number of questions to output\")\n args = parser.parse_args()\n\n templates = None\n if args.template_file is not None:\n with open(args.template_file) as f:\n templates = json.load(f)\n del templates[\"instance of\"]\n del templates[\"subclass of\"]\n\n answers = None\n if args.answer_file is not None:\n with open(args.answer_file) as f:\n raw_answers = json.load(f)\n answers = collections.defaultdict(list)\n for id, ans in raw_answers.items():\n answers[id.rsplit(\"_\", 1)[0]].extend(ans)\n answers = {k: sorted(v, key=lambda x: x[0], reverse=True)\n for k, v in answers.items()}\n print(\"%d answers available\" % len(answers))\n\n with open(args.slot_filling_file) as f:\n paras = []\n total = 0\n for line in f:\n item = json.loads(line.strip())\n total += 1\n if templates is not None:\n if item[\"relation\"][args.hop][\"text\"][0] not in templates:\n # print(\"%s not found in templates, skipping.\" %\n # item[\"relation\"][args.hop][\"text\"][0])\n continue\n max_ = min(len(templates[item[\"relation\"][args.hop][\"text\"][0]]),\n args.num_templates)\n template = random.sample(\n templates[item[\"relation\"][args.hop][\"text\"][0]], max_)\n else:\n template = [\"XXX . \" + item[\"relation\"][args.hop][\"text\"][0]]\n if args.hop == 0:\n subjs = [(1.0, item[\"subject\"][\"name\"])]\n obj = item[\"bridge\"] if \"bridge\" in item else item[\"bridge_0\"]\n elif args.hop == 1:\n if answers is None:\n if \"bridge\" in item:\n subjs = [(1.0, item[\"bridge\"][\"name\"])]\n else:\n subjs = [(1.0, item[\"bridge_0\"][\"name\"])]\n else:\n if item[\"id\"] not in answers:\n print(\"answers for %s not found, skipping (e.g. %s)\" %\n (item[\"id\"], list(answers.keys())[0]))\n continue\n subjs = [ans[0:2] for ans in answers[item[\"id\"]][:args.top_k]]\n obj = item[\"object\"] if not \"bridge_1\" in item else item[\"bridge_1\"]\n else:\n if answers is None:\n subjs = [(1.0, item[\"bridge_1\"][\"name\"])]\n else:\n if item[\"id\"] not in answers:\n print(\"answers for %s not found, skipping (e.g. %s)\" %\n (item[\"id\"], list(answers.keys())[0]))\n continue\n subjs = [ans[0:2] for ans in answers[item[\"id\"]][:args.top_k]]\n obj = item[\"object\"]\n paras.append(create_squad_questions(subjs, template, obj, item[\"id\"]))\n print(\"created %d queries, given %d inputs\" % (len(paras), total))\n\n with open(args.out_file, \"w\") as f:\n json.dump({\"version\": \"2-hop\", \"data\": [{\"title\": \"\", \"paragraphs\": paras}]}, f)\n","sub_path":"scripts/create_templates_2hop.py","file_name":"create_templates_2hop.py","file_ext":"py","file_size_in_byte":4358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"26293555","text":"from django.urls import path\nfrom .views import Login, Logout, Signup, home\nfrom events import views\n\n\nurlpatterns = [\n\tpath('', home, name='home'),\n path('signup/', Signup.as_view(), name='signup'),\n path('login/', Login.as_view(), name='login'),\n path('logout/', Logout.as_view(), name='logout'),\n path('events/create/',views.event_create ,name='event-create'),\n path('events/list/',views.event_list ,name='event-list'),\n path('events//detail/',views.event_detail ,name='event-detail'),\n path('no-access/',views.no_access ,name='no-access'),\n path('events//update/',views.event_update ,name='event-update'),\n path('events/dashboard/',views.organizer_dashboard ,name='dashboard'),\n path('events//book/',views.event_book ,name='event-book'),\n path('events//delete/',views.event_delete ,name='event-delete'),\n path('events/deletex/',views.book_delete ,name='book-delete'),\n path('events/update//',views.user_update ,name='user-update'),\n]","sub_path":"events/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"193936341","text":"import datetime\n\nfrom selenium.common.exceptions import NoSuchElementException, TimeoutException\nfrom selenium.webdriver import Chrome\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\n\nimport configs\nfrom producer import produce\n\n\ndef setup() -> Chrome:\n opts = Options()\n if configs.GOOGLE_DRIVER_HEADLESS:\n opts.set_headless()\n BINARY_PATH = configs.GOOGLE_DRIVER_BINARY_PATH\n\n return Chrome(executable_path=BINARY_PATH, chrome_options=opts)\n\n\ndef pipeline(*, driver: Chrome, pages_limit=3) -> list:\n BASE_URL = configs.BASE_URL\n QUERY_PARAMS = configs.QUERY_PARAMS\n driver.get(f'{BASE_URL}{QUERY_PARAMS}')\n return_results = list()\n\n while pages_limit > 0:\n pages_limit -= 1\n WebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.CLASS_NAME, \"search-result\")))\n\n print(f\"Crawling {driver.current_url} ...\")\n\n for result in driver.find_elements_by_class_name('search-result'):\n try:\n return_results.append(\n dict(\n title=result.find_element_by_class_name(\n 'biz-name').text,\n phone=result.find_element_by_class_name('biz-phone')\n .text,\n category_list=[\n category.text\n for category in result.find_elements_by_class_name(\n 'category-str-list')\n ],\n time=str(datetime.datetime.now())))\n except NoSuchElementException as exp:\n print(exp)\n except TimeoutException:\n pass\n\n try:\n next_page_element = driver.find_element_by_xpath(\n '//div[contains(@class, \"pagination-links\")]' +\n '//a[contains(@class, \"next\")]')\n next_page_url = next_page_element.get_attribute(\"href\")\n driver.get(next_page_url)\n except NoSuchElementException as exp:\n print(exp)\n\n return return_results\n\n\nif __name__ == '__main__':\n driver: Chrome = setup()\n print('loading ...')\n results = pipeline(driver=driver, pages_limit=configs.PAGES_LIMIT)\n driver.close()\n\n if produce(data=results):\n exit(0)\n else:\n exit(1)\n","sub_path":"src/crawler/yelp_crawler/yelp.py","file_name":"yelp.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"632085074","text":"#!/usr/bin/python3\n# Imports\nfrom keras.preprocessing.image import img_to_array, load_img\nimport numpy as np\nfrom glob import glob\nfrom tqdm import tqdm\nfrom time import sleep\n\n# Config\ntraindir = 'data'\nsize = [256, 256]\nincmax = 500\n\n# Process input data into pics.npy\nprint('getting input data')\ndata = np.zeros([1] + size + [1], dtype=np.float32)\nbuffer = []\ninc = 0\nstart = True\nfor x in tqdm(glob('./' + traindir + '/*'), unit='pics', ascii=True):\n #try:\n buffer.append(img_to_array(load_img(x, grayscale=True, target_size=size)))\n inc += 1\n if inc == incmax:\n inc = 0\n data = np.concatenate((data, buffer))\n buffer = []\n if start and inc == incmax:\n start = False\n data = np.delete(data, 0)\n #except:\n #print('couldnt process ' + x.split('/')[-1])\nnp.save('pics', data)\nprint('saved input data')\nsleep(10)\n\n\n# Process output data into preds.npy\nprint('getting expected output data')\ndata = np.zeros([1] + size + [3], dtype=np.float32)\nbuffer = []\ninc = 0\nstart = True\nfor x in tqdm(glob('./' + traindir + '/*'), unit='pics', ascii=True):\n try:\n buffer.append(img_to_array(load_img(x, grayscale=True, target_size=size)))\n inc += 1\n if inc == incmax:\n inc = 0\n data = np.concatenate((data, buffer))\n buffer = []\n if start and inc == incmax:\n start = False\n data = np.delete(data, 0, 0)\n except:\n print('couldnt process ' + x.split('/')[-1])\nnp.save('preds', data)\nprint('saved output data')\n","sub_path":"colorize/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"261873535","text":"import string\r\nimport unicodedata\r\nimport logging\r\nimport re\r\nfrom .SnowBall import SnowballStemmer\r\nfrom .StopWords import get_stopwords_by_language\r\n\r\nlogger = logging.getLogger('summa.preprocessing.cleaner')\r\n\r\ntry:\r\n from pattern.en import tag\r\n\r\n logger.info(\"'pattern' package found; tag filters are available for English\")\r\n HAS_PATTERN = True\r\nexcept ImportError:\r\n logger.info(\"'pattern' package not found; tag filters are not available for English\")\r\n HAS_PATTERN = False\r\n\r\n# Часть функций взята из Gensim v0.10.0:\r\n# Gensim - это готовая к работе библиотека с\r\n# открытым исходным кодом для неконтролируемого моделирования\r\n# тем и обработки естественного языка с использованием современного\r\n# статистического машинного обучения. Gensim реализован на Python и Cython\r\n# для максимальной производительности и масштабируемости.\r\n# https://github.com/RaRe-Technologies/gensim/blob/0.10.0/gensim/utils.py\r\n# https://github.com/RaRe-Technologies/gensim/blob/0.10.0/gensim/parsing/preprocessing.py\r\n\r\n\r\nSEPARATOR = r\"@\"\r\nRE_SENTENCE = re.compile('(\\S.+?[.!?])(?=\\s+|$)|(\\S.+?)(?=[\\n]|$)')\r\nAB_SENIOR = re.compile(\"([A-Z][a-z]{1,2}\\.)\\s(\\w)\")\r\nAB_ACRONYM = re.compile(\"(\\.[a-zA-Z]\\.)\\s(\\w)\")\r\nAB_ACRONYM_LETTERS = re.compile(\"([a-zA-Z])\\.([a-zA-Z])\\.\")\r\nUNDO_AB_SENIOR = re.compile(\"([A-Z][a-z]{1,2}\\.)\" + SEPARATOR + \"(\\w)\")\r\nUNDO_AB_ACRONYM = re.compile(\"(\\.[a-zA-Z]\\.)\" + SEPARATOR + \"(\\w)\")\r\n\r\nSTEMMER = None\r\nSTOPWORDS = None\r\n\r\n\r\ndef set_stemmer_language(language):\r\n global STEMMER\r\n if not language in SnowballStemmer.languages:\r\n raise ValueError(\"Valid languages are: \" + \", \".join(sorted(SnowballStemmer.languages)))\r\n STEMMER = SnowballStemmer(language)\r\n\r\n\r\ndef set_stopwords_by_language(language, additional_stopwords):\r\n global STOPWORDS\r\n words = get_stopwords_by_language(language)\r\n if not additional_stopwords:\r\n additional_stopwords = {}\r\n STOPWORDS = frozenset({w for w in words.split() if w} | {w for w in additional_stopwords if w})\r\n\r\n\r\ndef init_textcleanner(language, additional_stopwords):\r\n set_stemmer_language(language)\r\n set_stopwords_by_language(language, additional_stopwords)\r\n\r\n\r\ndef split_sentences(text):\r\n processed = replace_abbreviations(text)\r\n return [undo_replacement(sentence) for sentence in get_sentences(processed)]\r\n\r\n\r\ndef replace_abbreviations(text):\r\n return replace_with_separator(text, SEPARATOR, [AB_SENIOR, AB_ACRONYM])\r\n\r\n\r\ndef undo_replacement(sentence):\r\n return replace_with_separator(sentence, r\" \", [UNDO_AB_SENIOR, UNDO_AB_ACRONYM])\r\n\r\n\r\ndef replace_with_separator(text, separator, regexs):\r\n replacement = r\"\\1\" + separator + r\"\\2\"\r\n result = text\r\n for regex in regexs:\r\n result = regex.sub(replacement, result)\r\n return result\r\n\r\n\r\ndef get_sentences(text):\r\n for match in RE_SENTENCE.finditer(text):\r\n yield match.group()\r\n\r\n\r\n# Взято из Gensim\r\nRE_PUNCT = re.compile('([%s])+' % re.escape(string.punctuation), re.UNICODE)\r\n\r\n\r\ndef strip_punctuation(s):\r\n return RE_PUNCT.sub(\" \", s)\r\n\r\n\r\n# Взято из Gensim\r\nRE_NUMERIC = re.compile(r\"[0-9]+\", re.UNICODE)\r\n\r\n\r\ndef strip_numeric(s):\r\n return RE_NUMERIC.sub(\"\", s)\r\n\r\n\r\ndef remove_stopwords(sentence):\r\n return \" \".join(w for w in sentence.split() if w not in STOPWORDS)\r\n\r\n\r\ndef stem_sentence(sentence):\r\n word_stems = [STEMMER.stem(word) for word in sentence.split()]\r\n return \" \".join(word_stems)\r\n\r\n\r\ndef apply_filters(sentence, filters):\r\n for f in filters:\r\n sentence = f(sentence)\r\n return sentence\r\n\r\n\r\ndef filter_words(sentences):\r\n filters = [lambda x: x.lower(), strip_numeric, strip_punctuation, remove_stopwords,\r\n stem_sentence]\r\n apply_filters_to_token = lambda token: apply_filters(token, filters)\r\n return list(map(apply_filters_to_token, sentences))\r\n\r\n\r\n# Взято из Gensim\r\ndef deaccent(text):\r\n \"\"\"\r\n Удалить акцентуацию с заданной строки.\r\n \"\"\"\r\n norm = unicodedata.normalize(\"NFD\", text)\r\n result = \"\".join(ch for ch in norm if unicodedata.category(ch) != 'Mn')\r\n return unicodedata.normalize(\"NFC\", result)\r\n\r\n\r\n# Взято из Gensim\r\nPAT_ALPHABETIC = re.compile('(((?![\\d])\\w)+)', re.UNICODE)\r\n\r\n\r\ndef tokenize(text, lowercase=False, deacc=False):\r\n \"\"\"\r\n Итеративно выдает токены в виде строк в кодировке Юникод, опционально также их нижний регистр\r\n    и удаляет следы акцента.\r\n \"\"\"\r\n if lowercase:\r\n text = text.lower()\r\n if deacc:\r\n text = deaccent(text)\r\n for match in PAT_ALPHABETIC.finditer(text):\r\n yield match.group()\r\n\r\n\r\ndef merge_syntactic_units(original_units, filtered_units, tags=None):\r\n units = []\r\n for i in range(len(original_units)):\r\n if filtered_units[i] == '':\r\n continue\r\n\r\n text = original_units[i]\r\n token = filtered_units[i]\r\n tag = tags[i][1] if tags else None\r\n sentence = SyntacticUnit(text, token, tag)\r\n sentence.index = i\r\n\r\n units.append(sentence)\r\n\r\n return units\r\n\r\n\r\ndef clean_text_by_sentences(text, language, additional_stopwords=None):\r\n \"\"\" Разбивает данный текст на предложения, применяя фильтры и их лемматизируя.\r\n     Возвращает список SyntacticUnit. \"\"\"\r\n init_textcleanner(language, additional_stopwords)\r\n original_sentences = split_sentences(text)\r\n filtered_sentences = filter_words(original_sentences)\r\n\r\n return merge_syntactic_units(original_sentences, filtered_sentences)\r\n\r\n\r\ndef clean_text_by_word(text, language, deacc=False, additional_stopwords=None):\r\n \"\"\" Разбивает данный текст на слова, применяя фильтры и их лемматизируя.\r\n     Возвращает слово слова -> syntacticUnit. \"\"\"\r\n init_textcleanner(language, additional_stopwords)\r\n text_without_acronyms = replace_with_separator(text, \"\", [AB_ACRONYM_LETTERS])\r\n original_words = list(tokenize(text_without_acronyms, lowercase=True, deacc=deacc))\r\n filtered_words = filter_words(original_words)\r\n if HAS_PATTERN:\r\n tags = tag(\" \".join(original_words)) # тегу нужен контекст слов в тексте\r\n else:\r\n tags = None\r\n units = merge_syntactic_units(original_words, filtered_words, tags)\r\n return {unit.text: unit for unit in units}\r\n\r\n\r\ndef tokenize_by_word(text, deacc=False):\r\n text_without_acronyms = replace_with_separator(text, \"\", [AB_ACRONYM_LETTERS])\r\n return tokenize(text_without_acronyms, lowercase=True, deacc=deacc)\r\n\r\n\r\nclass SyntacticUnit(object):\r\n\r\n def __init__(self, text, token=None, tag=None):\r\n self.text = text\r\n self.token = token\r\n self.tag = tag[:2] if tag else None # только первые две буквы тега\r\n self.index = -1\r\n self.score = -1\r\n\r\n def __str__(self):\r\n return \"Original unit: '\" + self.text + \"' *-*-*-* \" + \"Processed unit: '\" + self.token + \"'\"\r\n\r\n def __repr__(self):\r\n return str(self)\r\n","sub_path":"TextRank/Utils/TextCleaner.py","file_name":"TextCleaner.py","file_ext":"py","file_size_in_byte":7493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"592929634","text":"import faiss \nimport csv\nimport numpy as np\nimport sys\n\nif __name__ == '__main__':\n embeddingspath = '../../data/codeGraph/embeddings.csv'\n embeddingsToLabelPath='../../data/codeGraph/embeddingtolabel.csv'\n textToLabelPath='../../data/codeGraph/labeltotext.csv'\n embeded_docmessages=[]\n index = faiss.IndexFlatL2(512)\n\n with open(embeddingspath, 'r') as embeddings, open(embeddingsToLabelPath,'r') as embeddingsToLabels,open(textToLabelPath,'r') as textToLabels:\n# i = 0\n embeddingtolabelmap = {}\n labeltotextmap = {}\n for (line1,line2,line3) in zip(embeddings,embeddingsToLabels,textToLabels):\n newline = line1.rstrip()\n parsedline = newline.split(',')\n embeded_docmessages.append(parsedline)\n linetoadd = np.asarray(parsedline, dtype=np.float32).reshape(1,-1)\n index.add(linetoadd)\n #print(parsedline)\n newline = line2.rstrip()\n parsedline = newline.split(',')\n splitembedding = parsedline[0].split(';')\n arrayembedding = np.asarray(splitembedding, dtype=np.float32).reshape(1,-1)\n arrayembedding = arrayembedding.tolist()\n #print(arrayembedding)\n finalembedding = tuple(arrayembedding[0])\n #print(finalembedding)\n embeddingtolabelmap[finalembedding] = parsedline[1]\n #print(parsedline)\n\n newline = line3.rstrip()\n parsedline = newline.split(',')\n try:\n labeltotextmap[parsedline[0]] = parsedline[1] \n # this was originally included to find a bug caused by not omitting\n # carriage return in the csv, feel free to leave this part out\n except IndexError:\n print(newline)\n print('\\n\\n\\n\\n\\nSEPARATOR\\n\\n\\n\\n\\n')\n print(parsedline)\n exit()\n #print(parsedline)\n \n \n# i += 1\n k=11\n \n embeded_distance_index_info=[]\n embeded_distance_info=[]\n embeded_docmessages=np.asarray(embeded_docmessages,dtype=np.float32)\n for i in range(embeded_docmessages.shape[0]):\n # we want to see 2 nearest neighborS\n# print(embeded_docmessages[i].reshape(-1,1).shape)\n D, I = index.search(embeded_docmessages[i].reshape(1,-1), k)\n embeded_distance_index_info.append(I)\n embeded_distance_info.append(D)\n #print(embeded_distance_index_info)\n# sys.stdout = open(output_path, \"w\")\n\n# print(embeded_distance_index_info) \n# print(embeded_distance_info)\n originalOut = sys.stdout\n with open('../../data/codeGraph/finalSimilarityAnalysis.txt', 'w') as outputFile:\n sys.stdout = outputFile\n for i in range(embeded_docmessages.shape[0]):\n print(\"\\n-------------------------------------------------------------\")\n adjustedtopembedding = tuple(embeded_docmessages[i].tolist())\n toplabel = embeddingtolabelmap[adjustedtopembedding]\n print('\\nName of document is:', toplabel)\n print('\\nText of document is:', labeltotextmap[toplabel])\n for p in range(len(embeded_distance_index_info[i])):\n # call to tolist() here is optional, just looks better for output imo\n print(\"\\nIndices of related vectors:\", embeded_distance_index_info[i][p].tolist()) \n print(\"Distances to each related vector:\", embeded_distance_info[i][p].tolist())\n for f in range(0, k):\n numpyembedding = embeded_docmessages[embeded_distance_index_info[i][p][f]] \n adjustedembedding = tuple(numpyembedding.tolist())\n label = embeddingtolabelmap[adjustedembedding]\n print('\\nName of document in ranking order', f, 'is:', label)\n print('\\nText of document', f, 'is:', labeltotextmap[label])\n sys.stdout = originalOut\n\n\n\n\n","sub_path":"embeddingsTest/parseUSECSV.py","file_name":"parseUSECSV.py","file_ext":"py","file_size_in_byte":4762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"175475013","text":"# BlackJack Project\n\n# Our Blackjack House Rules\n# 1. The deck is unlimited in size. \n# 2. There are no jokers. The Jack/Queen/King all count as 10. The the Ace can count as 11 or 1.\n# 3. Use the following list as the deck of cards: cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] \n# 4. The cards in the list have equal probability of being drawn.\n# 5. Cards are not removed from the deck as they are drawn.\n# 6. The computer is the dealer.\n\nfrom black_jack_ASCII import logo\nimport random\n\ncards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]\n\n# Print final card list\ndef final_list_print(p_card, p_total, c_card, c_total):\n print(f\"Your final hand: {p_card}, final score: {p_total}\")\n print(f\"Computer's final hand: {c_card}, final score: {c_total}\")\n\n# Check the total scores for player and computer\ndef find_total(total_score_cards):\n total = 0\n for i in range(len(total_score_cards)):\n total += total_score_cards[i]\n return total\n\n# Checking conditions if player asks for another card\ndef checking_for_another_card_conditions(p_total, p_card, c_card, c_total):\n if p_total > 21:\n if 11 in p_card:\n index_of_value_change = p_card.index(11)\n p_card[index_of_value_change] = 1\n p_total = find_total(p_card)\n print(p_total)\n p_total = checking_for_another_card_conditions(p_total,p_card, c_card, c_total)\n return p_total\n else:\n final_list_print(p_card, p_total, c_card, c_total)\n print(\"You went over. You lose 😤\")\n new_game()\n elif p_total < 21:\n return p_total\n else:\n final_list_print(p_card, p_total, c_card, c_total)\n print(\"Congrats!! You have got a BlackJack\")\n new_game()\n\n# Checking computer's 17 score condition\ndef checking_computer_conditions(c_total, c_card):\n if c_total < 17:\n c_card.append(random.choice(cards))\n c_total = find_total(c_card)\n checking_computer_conditions(c_total, c_card)\n return c_total\n else:\n c_total = find_total(c_card)\n return c_total\n\n# The Begins Here\ndef new_game():\n start_game = input(\"Do you want to play the Black Jack Game. Press 'Y' if yes else press 'N'! \").lower()\n if start_game == 'n':\n print(\"Thanks for playing the Game.\")\n quit()\n elif start_game == 'y':\n print(logo)\n player_cards = random.sample(cards,2)\n player_total = find_total(player_cards)\n\n computer_cards = random.sample(cards,2)\n computer_total = find_total(computer_cards)\n \n print(f\"Your cards are {player_cards}, current score is {player_total}\")\n print(f\"Computer's first card: {computer_cards[0]}\")\n\n flag = True\n while flag:\n player_total = checking_for_another_card_conditions(player_total, player_cards, computer_cards, computer_total)\n next_round = input(\"Type 'y' to get another card, type 'n' to pass: \").lower()\n if next_round == \"y\":\n player_cards.append(random.choice(cards))\n player_total = find_total(player_cards)\n print(f\"Your cards are {player_cards}, current score is {player_total}\")\n print(f\"Computer's first card: {computer_cards[0]}\")\n else:\n flag = False\n if player_total < 21:\n computer_total = checking_computer_conditions(computer_total, computer_cards)\n if player_total > computer_total:\n final_list_print(player_cards, player_total, computer_cards, computer_total)\n print(\"You have won the game!!\")\n new_game()\n elif player_total < computer_total:\n final_list_print(player_cards, player_total, computer_cards, computer_total)\n print(\"You have lost the game!!\")\n new_game() \n elif player_total == computer_total:\n final_list_print(player_cards, player_total, computer_cards, computer_total)\n print(\"This game is a Draw\")\n new_game()\n else:\n final_list_print(player_cards, player_total, computer_cards, computer_total)\n print(\"Computer Won the Game\")\n new_game()\n else:\n print(\"Please enter a valid input\")\n new_game()\nnew_game()","sub_path":"day_11.py","file_name":"day_11.py","file_ext":"py","file_size_in_byte":4271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"257459622","text":"from django.contrib.admin.views.decorators import staff_member_required\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render_to_response, render\nfrom django.conf import settings\nfrom mynav.nav import main_nav\nfrom .models import *\nfrom .forms import *\n\n# Create your views here.\n@staff_member_required\ndef load_brackets_view(request, **kwargs):\n # read bracket list from CSV file\n import csv\n file_path = settings.DIR_UPLOAD_DATA + 'tournaments/load_brackets.csv'\n with open(file_path, 'rb') as csvfile:\n infile = csv.reader(csvfile, delimiter=',', quotechar='\"')\n for row in infile:\n bracket = Bracket.objects.get_or_create(name=row[0])[0]\n bracket.manager=row[1]\n bracket.description=row[2]\n #bracket.description='Chem 130 - Exam Prep'\n bracket.save()\n return render(request, 'mytournament/load_brackets.html', {\n \"main_nav\": main_nav(request.user, 'student_linkback')\n })\n\n\n@staff_member_required\ndef load_competitors_view(request, **kwargs):\n # read competitor list from CSV file\n import csv\n file_path = settings.DIR_UPLOAD_DATA + 'tournaments/load_competitors.csv'\n with open(file_path, 'rb') as csvfile:\n infile = csv.reader(csvfile, delimiter=',', quotechar='\"')\n bracket_prefix = infile.next()[0]\n for row in infile:\n bracket = get_bracket(bracket_prefix+str(row[1]))\n # populate bracket_id, name, game\n # avoid duplicate names per bracket, update game as needed\n cc = Competitor.objects.get_or_create(bracket=bracket, name=row[0])[0]\n cc.game = row[2]\n cc.wins = 0\n cc.losses = 0\n cc.points = 0\n cc.byes = 0\n cc.status = -1\n cc.save() \n return render(request, 'mytournament/load_competitors.html', {\n \"main_nav\": main_nav(request.user, 'student_linkback')\n })\n\n@staff_member_required\ndef load_judges_view(request, **kwargs):\n # read judges list from CSV file\n import csv\n file_path = settings.DIR_UPLOAD_DATA + 'tournaments/load_judges.csv'\n with open(file_path, 'rb') as csvfile:\n infile = csv.reader(csvfile, delimiter=',', quotechar='\"')\n bracket_prefix = infile.next()[0]\n for row in infile:\n bracket = get_bracket(bracket_prefix+str(row[1]))\n # populate the bracket_id, name, eligable \n # avoid duplicate names per bracket, update eligable as needed\n cc = Judge.objects.get_or_create(bracket=bracket, name=row[0])[0]\n cc.eligable=row[2]\n cc.decisions=0\n cc.save() \n return render(request, 'mytournament/load_judges.html', {\n \"main_nav\": main_nav(request.user, 'student_linkback')\n })\n\ndef tournament_selector_view(request):\n return render(request, 'mytournament/selector.html', {\n \"main_nav\": main_nav(request.user, 'student_linkback'),\n \"bracket\": \"None\" \n })\n\ndef info_view(request, **kwargs):\n bname = kwargs[\"bracket\"]\n bracket = get_bracket(bname)\n return render(request, 'mytournament/info.html', {\n \"main_nav\": main_nav(request.user, 'student_linkback'),\n \"bracket\": bracket.description \n })\n\ndef register_view(request, **kwargs):\n bname = kwargs[\"bracket\"]\n bracket = get_bracket(bname)\n # load the manager\n manager = eval(bracket.manager)(bracket=bracket)\n \n # handle the form\n if request.method == 'POST':\n form = Register_Form(\n data=request.POST,\n )\n if form.is_valid():\n game = form.cleaned_data['game']\n manager.Register(request.user.username, game)\n form = Register_Form(\n initial={\n 'game': manager.Game(request.user)\n },\n )\n\n return render(request, 'mytournament/register.html', {\n \"main_nav\": main_nav(request.user, 'student_linkback'),\n \"bracket\": bracket.description,\n \"form\": form,\n 'game': manager.Game(request.user)\n })\n\ndef vote_view(request, **kwargs):\n bname = kwargs[\"bracket\"]\n bracket = get_bracket(bname)\n # load the manager\n manager = eval(bracket.manager)(bracket=bracket)\n \n # handle the form\n if request.method == 'POST':\n form = Voter_Form(\n data=request.POST,\n vote_choices = manager.Vote_Choices(who=request.user.username),\n )\n if form.is_valid():\n bout = form.cleaned_data['bout']\n decision = form.cleaned_data['vote']\n manager.Record_Vote(bout, request.user.username, decision)\n # run manager setup\n manager.Setup(request.user.username) \n form = Voter_Form(\n initial={\n 'bout': manager.Bout_Id(request.user.username)\n },\n vote_choices = manager.Vote_Choices(who=request.user.username)\n )\n return render(request, 'mytournament/vote.html', {\n \"main_nav\": main_nav(request.user, 'student_linkback'),\n \"bracket\": bracket.description,\n \"form\": form,\n \"judge\": manager.Get_Judge(request.user.username),\n \"status\": manager.Status(request.user.username),\n \"winner\": manager.GetWinner()\n })\n\ndef get_bracket(bname):\n # find/create the bracket\n brackets = Bracket.objects.filter(name=bname)\n if brackets.count() == 0:\n #import pdb; pdb.set_trace() \n bracket = Bracket.objects.get_or_create(name='00')[0]\n bracket.manager='Top20'\n bracket.description='Example for testing'\n bracket.save()\n else:\n bracket = brackets[0] \n return bracket\n\n\n","sub_path":"mytournament13/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"195002667","text":"#!/usr/bin/python\n#coding: utf-8\n\nfrom sopel.module import commands, example\nimport cPickle\nfrom fuzzywuzzy import fuzz, process\n\n@commands('abb')\n@commands('acr')\ndef lookup_command(bot, trigger):\n \"\"\"Searches the FL wiki for an abbreviation.\"\"\"\n data = cPickle.load(open('/home/alan/.sopel/abbreviations'))\n if not trigger.group(2):\n bot.say('What acronym do you want to look up?')\n return\n key = trigger.group(2).strip().upper()\n match = process.extractOne(key,data.keys(),scorer=fuzz.token_set_ratio)\n if match[1] < 80:\n bot.say('I don\\'t think I have that acronym.')\n return\n bot.say(data[match[0]])\n","sub_path":"sopel/modules/abbreviations.py","file_name":"abbreviations.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"569506057","text":"from django.urls import path\nfrom .views import HomePageView, DetailArticle, SearchResultsView, ClassesView, FuncView, OtherView\n\nurlpatterns = [\npath('', HomePageView.as_view(), name='home'),\npath('articles//',DetailArticle.as_view(), name='articles'),\npath('search/', SearchResultsView.as_view(), name='search'),\npath('classes/', ClassesView.as_view(), name='classes'),\npath('fm/', FuncView.as_view(), name='fm'),\npath('other/', OtherView.as_view(), name='other')\n]","sub_path":"pages/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"591387708","text":"import numpy as np\nfrom scipy.signal import lfilter, lfiltic, butter\n\ndef hz2mel(F):\n \"\"\"\n Transforms Hz to Mel scale using formulat from https://en.wikipedia.org/wiki/Mel_scale\n \n Parameters\n ----------\n F : float\n frequency in Hz\n\n Returns\n -------\n m : float\n frequency on Mel scale\n \"\"\"\n return 2595. * np.log10( 1. + F / 700. )\n\ndef mel2hz(m):\n \"\"\"\n Transforms frequency on Mel scale to Hz using formulat from https://en.wikipedia.org/wiki/Mel_scale\n \n Parameters\n ----------\n m : float\n frequency on Mel scale\n\n Returns\n -------\n F : float\n frequency in Hz\n \"\"\"\n return 700. * ( 10.** (m/2595.) - 1. )\n\ndef meluniform(F_min = 0, F_max = 44100, num = 50):\n \"\"\"\n Generates an array of frequencies uniformly distributed on Mel scale\n \n Parameters\n ----------\n F_min : float, optional\n maximal frequency in Hz\n F_max : float, optional\n maximal frequency in Hz\n num : int, optional\n number of elements\n\n Returns\n -------\n F : numpy array\n frequencies in Hz\n \"\"\"\n return mel2hz( np.linspace(start = hz2mel(F_min), stop = hz2mel(F_max), num = num) )\n\n\ndef spec_tri_window(n, center, left = None, right = None):\n \"\"\"\n Assymetrical triangular window\n \n Parameters\n ----------\n samples : int\n total number of samples in the domain\n center : int \n center of the window\n left : int, optional\n left point of the window; can be ommited if center = 0\n right: int, optional\n right point of the window; can be ommited if center = samples\n\n Returns\n -------\n window : numpy array\n window is zero everywhere except for the domain between left and right\n \"\"\"\n window = np.zeros((n,), dtype = float)\n if left is not None:\n window[left:center+1] = np.linspace(0, 1, center-left+1)\n elif center != 0:\n raise ValueError('left can be ommited only when center = 0')\n if right is not None:\n try:\n window[center:right+1] = np.linspace(1, 0, right-center+1)\n except ValueError:\n window[center:right+1] = np.linspace(1, 0, right-center+1)[ :window[center:right+1].shape[0] ]\n elif center != n-1:\n raise ValueError('right can be ommited only when center = n-1')\n return window\n\ndef mel_scale_windows(n, F_max, num, F_max_mel = None):\n \"\"\"\n List of triangular windows to convert spectrum from Hz to Mel scale\n \n Parameters\n ----------\n n : int\n number of samples in the spectrum\n F_max : float\n maximal frequency in the spectrum\n num : int\n number of points on Mel scale\n\n Returns\n -------\n windows : list of numpy arrays\n each element defines a window for a certain central frequency on Mel scale\n \"\"\"\n if F_max_mel is None:\n F_max_mel = F_max\n mel = meluniform(F_min = 0, F_max = F_max_mel, num = num + 1)\n windows = []\n centers = np.round( mel / (float(F_max) / n) )\n left = None\n center = centers[0]\n for right in centers[1:]:\n window = spec_tri_window(n = n, center = center, left = left, right = right)\n left, center = center, right\n windows.append(window)\n return windows\n\ndef mel_scale_butter(F, F_max, num):\n mel = meluniform(F_min = 0, F_max = F_max, num = 2 * num + 1)\n filters = [];\n b, a = butter(2, mel[1] / F);\n filters.append( (b,a) )\n for cnt in range(3, len(mel)-2, 2):\n b, a = butter(2, [mel[cnt-1], mel[cnt+1]] / F, btype = 'band');\n filters.append( (b,a) )\n b, a = butter(2, mel[-2] / F);\n filters.append( (b,a) )\n \n","sub_path":"melmisc.py","file_name":"melmisc.py","file_ext":"py","file_size_in_byte":3679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"604835710","text":"\"\"\"\nThis sample demonstrates a simple skill built with the Amazon Alexa Skills Kit.\nThe Intent Schema, Custom Slots, and Sample Utterances for this skill, as well\nas testing instructions are located at http://amzn.to/1LzFrj6\n\nFor additional samples, visit the Alexa Skills Kit Getting Started guide at\nhttp://amzn.to/1LGWsLG\n\"\"\"\n\nfrom __future__ import print_function\nimport json as JSON\n\n# --------------- Helpers that build all of the responses ----------------------\n\n\nPIE_URL = \"https://s3.amazonaws.com/analyticsawaken/allocation_{}_{}.png\"\nBACK_URL = \"https://ak2.picdn.net/shutterstock/videos/16726672/thumb/1.jpg\"\nRASPUTIN_URL = \"https://s3.amazonaws.com/analyticsawaken/rasputin_1024.png\"\nSESSION_BODY_3 = \"body_3\"\n\n\n\ndef create_previous_intent_attribute(intent_name):\n return {\"previous_intent\": intent_name}\n\n\n\ndef build_speechlet_response(title, output, reprompt_text, should_end_session):\n return {\n 'outputSpeech': {\n 'type': 'PlainText',\n 'text': output\n },\n 'card': {\n 'type': 'Simple',\n 'title': \"SessionSpeechlet - \" + title,\n 'content': \"SessionSpeechlet - \" + output\n },\n 'reprompt': {\n 'outputSpeech': {\n 'type': 'PlainText',\n 'text': reprompt_text\n }\n },\n 'shouldEndSession': should_end_session,\n }\n\n\ndef build_response(session_attributes, speechlet_response):\n\n return {\n 'version': '1.0',\n 'sessionAttributes': session_attributes,\n 'response': speechlet_response\n }\n\n\ndef build_speechlet_response_echoshow(title, speech, directives, session_attributes):\n response = {\n \"version\": \"1.0\",\n \"response\": {\n \"outputSpeech\": {\n \"type\": \"PlainText\",\n \"text\": \"{}. \".format(speech)\n },\n \"card\": {\n 'type': 'Simple',\n 'title': title,\n 'content': speech\n },\n \"directives\": directives,\n \"shouldEndSession\": False\n },\n \"sessionAttributes\": session_attributes\n }\n print(response)\n return response\n\n\n\n\n##### NEW CODE\n##### -------------------------\n##### -------------------------\n##### -------------------------\n##### -------------------------\n##### -------------------------\n\n# a function that lookups allocation values using age and risktype\ndef show_asset_allocation(risktype, age):\n return body_template_two(risktype, age)\n\ndef pie_url(maxage, risktype):\n return PIE_URL.format(maxage, risktype)\n\n## --------- body template ---------\ndef body_template_one():\n title = \" \"\n speech = \"\"\n primary_text = \" \"\n secondary_text = \" \"\n tertiary_text = \"AI V MAP monitors your investment performance and determines how you're doing relative to your peers, who are \" \\\n \"anonymous Vanguard participants with a similar educational background, work experience, income level and zip code. \" \\\n \"Furthermore, AI V MAP leverages social network information you linked to your account to automatically update your \" \\\n \"work experience and income level.\" \\\n \"...\" \\\n \"We found your performance has fallen below your threshold of 7 percent in comparison with your peers. Do you want me to \" \\\n \"change your allocation from conservative to moderate? \"\n speech = \" \".join([speech, primary_text, secondary_text, tertiary_text])\n\n template = {\n \"type\": \"Display.RenderTemplate\",\n \"template\": {\n \"type\": \"BodyTemplate1\",\n \"token\": \"bt1\",\n \"backButton\": \"HIDDEN\",\n \"backgroundImage\": {\n \"contentDescription\": \"Mt Fuji\",\n \"sources\": [\n {\n \"url\": RASPUTIN_URL\n }\n ]\n },\n \"title\": \" \",\n \"textContent\": {\n \"primaryText\": {\n \"text\": \"\",\n \"type\": \"PlainText\"\n },\n \"secondaryText\": {\n \"text\": \"\" + \" \" + \"\",\n \"type\": \"RichText\"\n },\n \"tertiaryText\": {\n \"text\": \" \",\n \"type\": \"PlainText\"\n }\n }\n }\n }\n\n directives = [\n template\n ]\n\n return build_speechlet_response_echoshow(title, speech, directives, create_attribute(\"previous_intent\",\"how_compare\"))\n\n\ndef list_template_two():\n title = \"Vanguard Asset Allocation\"\n speech = \"This is recommended asset allocation for moderate investor between 29 and 33 years old. I also send you the peer performance chart. Let me know what you think. \"\n\n template ={\n \"type\": \"Display.RenderTemplate\",\n \"template\": {\n \"type\": \"ListTemplate2\",\n \"title\": \"Vanguard Asset Allocation Recommendation\",\n \"token\": \"TOKEN\",\n \"listItems\": [\n {\n \"token\": \"TOKEN0\",\n \"image\": {\n \"contentDescription\": \"Item Description\",\n \"sources\": [\n {\n \"url\": \"https://s3.amazonaws.com/analyticsawaken/peers.jpeg\",\n \"widthPixels\":320,\n \"heightPixels\": 280,\n \"size\": \"X_SMALL\"\n }\n ]\n },\n \"textContent\": {\n \"primaryText\": {\n \"text\": \"Comparison with your peers\",\n \"type\": \"PlainText\"\n },\n \"secondaryText\": {\n \"text\": \" \",\n \"type\": \"PlainText\"\n },\n \"tertiaryText\": {\n \"text\": \" \",\n \"type\": \"PlainText\"\n }\n }\n },\n {\n \"token\": \"TOKEN1\",\n \"image\": {\n \"contentDescription\": \"Item Description\",\n \"sources\": [\n {\n \"url\": \"https://s3.amazonaws.com/analyticsawaken/allocation_33_moderate.png\",\n \"widthPixels\": 280,\n \"heightPixels\": 280,\n \"size\": \"X_SMALL\"\n }\n ]\n },\n \"textContent\": {\n \"primaryText\": {\n \"text\": \"Moderate Asset Allocation for 29 - 33 years old\",\n \"type\": \"PlainText\"\n },\n \"secondaryText\": {\n \"text\": \" \",\n \"type\": \"PlainText\"\n },\n \"tertiaryText\": {\n \"text\": \" \",\n \"type\": \"PlainText\"\n }\n }\n }\n\n ],\n \"backgroundImage\": {\n \"sources\": [\n {\n \"url\": BACK_URL\n }\n ]\n },\n \"backButton\": \"HIDDEN\"\n }\n }\n\n hint = {\n \"type\": \"Hint\",\n \"hint\": {\n \"type\": \"PlainText\",\n \"text\": \"You can also check aggressive allocation\"\n }\n }\n\n directives = [\n template,\n hint\n ]\n\n return build_speechlet_response_echoshow(title, speech, directives, create_attribute(\"previous_intent\",\"how_compare\"))\n\ndef body_template_two(risktype, age):\n if age <= 23:\n term = \" below 23 \"\n maxage = 24\n elif age <= 28:\n term = \" between 24 and 28 \"\n maxage = 28\n elif age <= 33:\n term = \" between 29 and 33 \"\n maxage = 33\n elif age <= 38:\n term = \" between 34 and 38 \"\n maxage = 38\n elif age <= 43:\n term = \" between 39 and 43 \"\n maxage = 43\n elif age <= 48:\n term = \" between 44 and 48 \"\n maxage = 48\n elif age <= 53:\n term = \" between 49 and 53 \"\n maxage = 53\n elif age <= 58:\n term = \" between 54 and 58 \"\n maxage = 58\n elif age <= 63:\n term = \" between 59 and 63 \"\n maxage = 63\n elif age <= 68:\n term = \" between 64 and 68 \"\n maxage = 68\n elif age <= 72:\n term = \" between 69 and 72 \"\n maxage = 72\n else:\n term = \" between 73 and 125 \"\n maxage = 125\n\n title = \"Vanguard Asset Allocation\"\n speech = \"This is recommended asset allocation \"\n primary_text = \"for \"+ str(risktype) + \" investors who are \" + term + \" years old. \"\n\n secondary_text = \"\"\n\n if risktype=='moderate':\n tertiary_text = \"I also sent you your peer comparison chart. Let me know what you think. \"\n else:\n tertiary_text = \" Let me know what you think. \"\n\n\n speech = \" \".join([speech, primary_text, secondary_text, tertiary_text])\n\n template = {\n \"type\": \"Display.RenderTemplate\",\n \"template\": {\n \"type\": \"BodyTemplate2\",\n \"token\": \"bt2\",\n \"backButton\": \"VISIBLE\",\n \"backgroundImage\": {\n \"contentDescription\": \"Mt Fuji\",\n \"sources\": [\n {\n \"url\": BACK_URL\n }\n ]\n },\n \"title\": title,\n \"image\": {\n \"contentDescription\": \"BBQ gril\",\n \"sources\": [\n {\n \"url\": pie_url(maxage, risktype)\n }\n ]\n },\n \"textContent\": {\n \"primaryText\": {\n \"text\": primary_text,\n \"type\": \"PlainText\"\n },\n \"secondaryText\": {\n \"text\": \"\" + secondary_text + \"\",\n \"type\": \"RichText\"\n },\n \"tertiaryText\": {\n \"text\": tertiary_text,\n \"type\": \"PlainText\"\n }\n }\n }\n }\n\n hint = {\n \"type\": \"Hint\",\n \"hint\": {\n \"type\": \"PlainText\",\n \"text\": \"tell invocation name body template number 3\"\n }\n }\n\n directives = [\n template,\n hint\n ]\n\n return build_speechlet_response_echoshow(title, speech, directives, create_attribute(\"previous_intent\",\"show_allocations\"))\n\n\n\ndef update_session_attribute(session, attribute_name, attribute_value):\n\n global session_attributes\n\n if session.get('attributes', {}) and attribute_name not in session.get('attributes', {}):\n session_attributes.update(create_previous_intent_attribute(attribute_value))\n elif attribute_name in session.get('attributes', {}):\n session_attributes.update(create_previous_intent_attribute(attribute_value))\n else:\n print(\"not found session attributes\")\n\n return session_attributes\n\n\ndef create_attribute(attribute_name, attribute_value):\n return {attribute_name: attribute_value}\n\ndef get_welcome_response():\n\n \"\"\" If we wanted to initialize the session to have some attributes we could\n add those here\n \"\"\"\n global session_attributes\n\n session_attributes = {}\n\n\n\n card_title = \"Welcome\"\n\n\n speech_output = \"Hello Rasputin, your voice is your password, thanks for authenticating. \" \\\n \"You have a new message from Vanguard on January 10th, 2018, 11 AM. \" \\\n \"do you want me to open it for you? \"\n\n reprompt_text = \"Hello Rasputin, your voice is your password, thanks for authenticating. \" \\\n \"You have a new message from Vanguard on January 10th, 2018, 11 AM. \" \\\n \"do you want me to open it for you? \"\n\n should_end_session = False\n\n return build_response(session_attributes, build_speechlet_response(\n card_title, speech_output, reprompt_text, should_end_session))\n\n\n\n#step2 Step_two_open_mail\ndef Step_two_open_mail(intent,session):\n card_title = intent['name']\n\n\n session_attributes = {}\n\n session_attributes = update_session_attribute(session, 'previous_intent', 'open_mail')\n\n speech_output = \"Okay, here is the message. Dear Rasputin, Vanguard appreciates your participation in \" \\\n \"our retirement savings program. You have been with us for 11 months, and we noticed your \" \\\n \"performance has fallen below your threshold of 7 percent in comparison with your peers. Do you \" \\\n \"want me to change your allocation from conservative to moderate. \"\n\n reprompt_text = \"Okay, here is the message. Dear Rasputin, Vanguard appreciates your participation in \" \\\n \"our retirement savings program. You have been with us for 11 months, and we noticed your \" \\\n \"performance has fallen below your threshold of 7 percent in comparison with your peers. Do you \" \\\n \"want me to change your allocation from conservative to moderate. \"\n\n should_end_session = False\n\n return build_response(session_attributes, build_speechlet_response(\n card_title, speech_output, reprompt_text, should_end_session))\n\n\n# step3 Step_three_open_mail\ndef Step_three_how_compare(intent, session):\n\n #session_attributes = update_session_attribute(session, 'previous_intent', 'how_compare')\n # card_title = intent['name']\n #\n #\n #\n # speech_output = \"AI V MAP monitors your investment performance and determines how you're doing relative to your peers, who are \" \\\n # \"anonymous Vanguard participants with a similar educational background, work experience, income level and zip code. \" \\\n # \"Furthermore, AI V MAP leverages social network information you linked to your account to automatically update your \" \\\n # \"work experience and income level.\" \\\n # \"...\" \\\n # \"We found your performance has fallen below your threshold of 7 percent in comparison with your peers. Do you want me to \" \\\n # \"change your allocation from conservative to moderate? \"\n #\n # reprompt_text = \"AI V MAP monitors your investment performance and determines how you're doing relative to your peers, who are\" \\\n # \"anonymous Vanguard participants with a similar educational background, work experience, income level and zip code.\" \\\n # \"Furthermore, AI V MAP leverages social network information you linked to your account to automatically update your\" \\\n # \"work experience and income level.\" \\\n # \"...\" \\\n # \"We found your performance has fallen below your threshold of 7 percent in comparison with your peers. Do you want me to \" \\\n # \"change your allocation from conservative to moderate? \"\n #\n # should_end_session = False\n #\n # return build_response(session_attributes, build_speechlet_response(\n # card_title, speech_output, reprompt_text, should_end_session))\n #return list_template_two()\n return body_template_one()\n\n# step4 Step_four_send_allocations\ndef Step_four_send_allocations(intent,session):\n\n card_title = intent['name']\n\n session_attributes = update_session_attribute(session, 'previous_intent', 'send_allocations')\n\n speech_output = \"Sure, just to confirm you are 32 years old now, and you want a new allocation chart for moderate investment?\"\n\n reprompt_text = \"Sure, just to confirm you are 32 years old now, and you want a new allocation chart for moderate investment?\"\n should_end_session = False\n\n return build_response(session_attributes, build_speechlet_response(\n card_title, speech_output, reprompt_text, should_end_session))\n\n\n# # step5 Step_five_confirm_age\n# def Step_five_confirm_age(intent,session):\n#\n# card_title = intent['name']\n#\n# session_attributes = update_session_attribute(session, 'previous_intent', 'confirm_age')\n#\n#\n#\n# # speech_output = \"Sure, ..., Done! Let me know what you think. I also sent you your peer comparison chart. \"\n# #\n# # reprompt_text = \"Sure, ..., Done! Let me know what you think. I also sent you your peer comparison chart. \"\n# # should_end_session = False\n# #\n# # return build_response(session_attributes, build_speechlet_response(\n# # card_title, speech_output, reprompt_text, should_end_session))\n#\n# #return show_asset_allocation(\"moderate\",32)\n# return list_template_two()\n\n#step6 Step_six_show_aggressive\ndef Step_six_show_aggressive(intent,session):\n\n card_title = intent['name']\n\n session_attributes = update_session_attribute(session, 'previous_intent', 'show_aggressive')\n return show_asset_allocation(\"aggressive\", 32)\n\n\n#step7 Step_seven_sign_up\ndef Step_seven_sign_up(intent, session):\n\n card_title = intent['name']\n session_attributes = update_session_attribute(session, 'previous_intent', 'sign_up')\n\n\n\n speech_output = \"Sure, ..., Done! By the way, from your social network profile that you linked to your Vanguard account, I noticed that you just had a baby. Is that correct ? \"\n\n reprompt_text = \"Sure, ..., Done! By the way, from your social network profile that you linked to your Vanguard account, I noticed that you just had a baby. Is that correct ? \"\n should_end_session = False\n\n return build_response(session_attributes, build_speechlet_response(\n card_title, speech_output, reprompt_text, should_end_session))\n\n\n# step8 Step_eight_new_baby\ndef Step_eight_new_baby(intent, session):\n\n card_title = intent['name']\n session_attributes = update_session_attribute(session, 'previous_intent', 'new_baby')\n\n\n\n speech_output = \"Congratulations! This is a great time to talk to an advisor about your financial plan. From our records, I see you have talked to our advisor Mike\" \\\n \"Albano before, and he is available to talk to you. Would you like to have a video conference with him now? \"\n\n reprompt_text = \"Congratulations! This is a great time to talk to an advisor about your financial plan. From our records, I see you have talked to our advisor Mike\" \\\n \"Albano before, and he is available to talk to you. Would you like to have a video conference with him now? \"\n\n should_end_session = False\n\n return build_response(session_attributes, build_speechlet_response(\n card_title, speech_output, reprompt_text, should_end_session))\n\n\n# step8 Step_nine_call_Mike\ndef Step_nine_call_Mike(intent, session):\n\n card_title = intent['name']\n session_attributes = update_session_attribute(session, 'previous_intent', 'call_mike')\n\n\n speech_output = \"Fantastic! You can say Call Mike Albano to contact him. Thank you for choosing Vanguard and have a wonderful day. \"\n\n reprompt_text = \"Fantastic! You can say Call Mike Albano to contact him. Thank you for choosing Vanguard and have a wonderful day. \"\n\n should_end_session = True\n\n return build_response(session_attributes, build_speechlet_response(\n card_title, speech_output, reprompt_text, should_end_session))\n\n\n\n#\n# def sendpicture(intent, session):\n#\n# card_title = intent['name']\n#\n# account_sid = \"ACa35ea580c7f4e30d2f4aaa3eed3c2fe6\"\n# # Your Auth Token from twilio.com/console\n# auth_token = \"94f09ea764f53f2448f7cf4d0a487043\"\n# should_end_session = True\n# session_attributes = {}\n#\n# try:\n# client = Client(account_sid, auth_token)\n#\n# # message = client.messages.create(\n# # to=\"+17735587753\",\n# # from_=\"+12242573280\",\n# # body=\"Hello from Python!\")\n#\n#\n# #client = Client(account_sid, auth_token)\n#\n# message = client.api.account.messages.create(\n# to=\"+17735587753\",\n# from_=\"+12242573280\",\n# body=\"Hello there!\",\n# media_url=['https://demo.twilio.com/owl.png'])\n\n # except (RuntimeError, TypeError, NameError):\n # speech_output = \"I am sorry, there is some technical issues sending you the chart.\"\n # return build_response({}, build_speechlet_response(\n # card_title, speech_output, None, should_end_session))\n #\n # speech_output = \"The chart has been sent to your mobile number registered in your account.\"\n #\n # return build_response({}, build_speechlet_response(\n # card_title, speech_output, None, should_end_session))\n\n\n\ndef handle_session_end_request():\n card_title = \"Session Ended\"\n speech_output = \"Thank you for trying the Vanguard Virtual Assistant. \" \\\n \"Have a nice day! \"\n # Setting this to true ends the session and exits the skill.\n should_end_session = True\n return build_response({}, build_speechlet_response(\n card_title, speech_output, None, should_end_session))\n\n\n# --------------- Events ------------------\n\ndef on_session_started(session_started_request, session):\n \"\"\" Called when the session starts \"\"\"\n\n print(\"on_session_started requestId=\" + session_started_request['requestId']\n + \", sessionId=\" + session['sessionId'])\n\n\ndef on_launch(launch_request, session):\n \"\"\" Called when the user launches the skill without specifying what they\n want\n \"\"\"\n\n print(\"on_launch requestId=\" + launch_request['requestId'] +\n \", sessionId=\" + session['sessionId'])\n # Dispatch to your skill's launch\n return get_welcome_response()\n\n\ndef on_intent (intent_request, session):\n \"\"\" Called when the user specifies an intent for this skill \"\"\"\n\n # global session_attributes\n #\n # p_node = \"\"\n\n print(\"on_intent requestId=\" + intent_request['requestId'] +\n \", sessionId=\" + session['sessionId'])\n\n\n p_intent = ''\n\n if (session.get('attributes', {})) and (\"previous_intent\" in session.get('attributes', {})):\n p_intent = session['attributes']['previous_intent']\n\n\n intent = intent_request['intent']\n intent_name = intent_request['intent']['name']\n\n # print (\"intent name is \" + str(intent_name) + \"p node is \"+str(p_node))\n\n # Dispatch to your skill's intent handlers\n if (intent_name == \"Step_two_open_mail\"):\n return Step_two_open_mail(intent, session)\n elif (intent_name == \"Step_three_how_compare\"):\n return Step_three_how_compare(intent, session)\n elif (intent_name == \"Step_three_how_compare\"):\n return Step_three_how_compare(intent, session)\n elif (intent_name == \"Step_four_send_allocations\"):\n return Step_four_send_allocations(intent, session)\n # elif (intent_name == \"Step_five_confirm_age\"):\n # return Step_five_confirm_age(intent, session)\n elif (intent_name == \"Step_six_show_aggressive\"):\n\n print (\"At show aggressive ======== and p intent is \"+p_intent)\n if (p_intent=='send_allocations'):\n return list_template_two()\n else:\n return Step_six_show_aggressive(intent, session)\n elif (intent_name == \"Step_seven_sign_up\"):\n return Step_seven_sign_up(intent, session)\n # elif (intent_name == \"Step_eight_new_baby\"):\n # return Step_eight_new_baby(intent, session)\n elif (intent_name == \"Step_nine_call_Mike\"):\n return Step_nine_call_Mike(intent, session)\n elif (intent_name == \"Step_General_Confirm\"):\n if p_intent=='send_allocations':\n return list_template_two()\n elif p_intent=='sign_up':\n return Step_eight_new_baby(intent, session)\n else:\n return list_template_two()\n elif intent_name == \"AMAZON.HelpIntent\":\n return get_welcome_response()\n elif intent_name == \"AMAZON.CancelIntent\" or intent_name == \"AMAZON.StopIntent\":\n return handle_session_end_request()\n else:\n raise ValueError(\"Invalid intent\")\n\n\ndef on_session_ended(session_ended_request, session):\n \"\"\" Called when the user ends the session.\n\n Is not called when the skill returns should_end_session=true\n \"\"\"\n print(\"on_session_ended requestId=\" + session_ended_request['requestId'] +\n \", sessionId=\" + session['sessionId'])\n # add cleanup logic here\n\n\n# --------------- Main handler ------------------\n\ndef lambda_handler(event, context):\n \"\"\" Route the incoming request based on type (LaunchRequest, IntentRequest,\n etc.) The JSON body of the request is provided in the event parameter.\n \"\"\"\n print(\"event.session.application.applicationId=\" +\n event['session']['application']['applicationId'])\n\n print(\"===EVENT=== \\n\" + JSON.dumps(event))\n\n\n my_session = event['session']\n p_intent = ''\n\n if (my_session.get('attributes', {})) and (\"previous_intent\" in my_session.get('attributes', {})):\n p_intent = my_session['attributes']['previous_intent']\n\n print ('p_intent is ' + p_intent)\n\n\n \"\"\"\n Uncomment this if statement and populate with your skill's application ID to\n prevent someone else from configuring a skill that sends requests to this\n function.\n \"\"\"\n # if (event['session']['application']['applicationId'] !=\n # \"amzn1.echo-sdk-ams.app.[unique-value-here]\"):\n # raise ValueError(\"Invalid Application ID\")\n\n if event['session']['new']:\n on_session_started({'requestId': event['request']['requestId']},\n event['session'])\n if event['request']['type'] == \"LaunchRequest\":\n return on_launch(event['request'], event['session'])\n elif event['request']['type'] == \"IntentRequest\":\n return on_intent(event['request'], event['session'])\n elif event['request']['type'] == \"SessionEndedRequest\":\n return on_session_ended(event['request'], event['session'])\n else:\n print (\"********************** Unknown Request\")\n","sub_path":"demo2/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":26891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"558639788","text":"import collections\n\nimport pytest\nimport pytest_mock\n\nfrom inreach_ground_control.message import Message\n\nDEFAULT_LATITUDE = 42\nDEFAULT_LONGITUDE = 45\n\ndef message_factory(text_msg=\"wx +2 days, daily=YES, hourly=n, units=aUto, include_emoji=True\"):\n return Message(\n text_msg_extid=\"id-number-1\",\n text_msg=text_msg,\n latitude=DEFAULT_LATITUDE,\n longitude=DEFAULT_LONGITUDE,\n response_sent=False\n )\n\n@pytest.fixture\ndef message():\n return message_factory()\n\ndef test_query_params_type(message):\n assert type(message.query_params()) == collections.defaultdict\n\ndef test_first_line_requirements(message):\n with pytest.raises(AssertionError):\n Message(\n text_msg_extid=\"id-number-1\",\n text_msg=\"invalid first line\",\n latitude=42,\n longitude=-43,\n response_sent=False\n )\n\n@pytest.mark.parametrize(\"text_msg,latitude,longitude\", [\n (\"wx +2 days, lat=3.1415, lon=55\", 3.1415, 55),\n (\"wx +2 days, lat=-43.2, lon=55\", -43.2, 55),\n (\"wx +2 days, lat=-5\", DEFAULT_LATITUDE, DEFAULT_LONGITUDE),\n (\"wx +2 days, lon=-5\", DEFAULT_LATITUDE, DEFAULT_LONGITUDE),\n (\"wx +2 days, daily=FALSE\", DEFAULT_LATITUDE, DEFAULT_LONGITUDE)\n])\n\ndef test_coordinates(message, text_msg, latitude, longitude):\n message.text_msg = text_msg\n opts = message.query_params()\n\n assert opts[\"lat\"] == latitude\n assert opts[\"lon\"] == longitude\n\n@pytest.mark.parametrize(\"text_msg,start_offset_days\", [\n (\"wx +2 days, daily=YES\", 2),\n (\"wx -1 days, daily=YES\", -1),\n (\"wx now, daily=YES\", 0)\n])\n\ndef test_start_offset_days(message, text_msg, start_offset_days):\n message.text_msg = text_msg\n opts = message.query_params()\n\n assert opts[\"start_offset_days\"] == start_offset_days\n\n@pytest.mark.parametrize(\"text_msg,daily,hourly\", [\n (\"wx +2 days, daily=YES, hourly=n\", True, False),\n (\"wx -1 days, daily=true, hourly=f\", True, False),\n (\"wx now, daily=t\", True, None)\n])\ndef test_boolean_options(message, text_msg, daily, hourly):\n message.text_msg = text_msg\n opts = message.query_params()\n\n assert opts[\"daily\"] is daily\n assert opts[\"hourly\"] is hourly\n\n@pytest.mark.parametrize(\"text_msg,units\", [\n (\"wx +2 days, units=auto\", \"auto\"),\n (\"wx +2 days, units=aUto\", \"auto\")\n])\ndef test_units(message, text_msg, units):\n # opts[\"units\"] should be lowercased\n message.text_msg = text_msg\n opts = message.query_params()\n\n assert opts[\"units\"] == 'auto'\n\ndef test_invalid_keys(message):\n opts = message.query_params()\n\n # Invalid keys should be ignored\n assert opts[\"include_emoji\"] == None\n","sub_path":"tests/test_message.py","file_name":"test_message.py","file_ext":"py","file_size_in_byte":2669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"156444840","text":"class TreeNode:\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Tree:\n def __init__(self, root=None):\n self.root = root\n\n def add_to_tree(self, val):\n new_node = TreeNode(val)\n if not self.root:\n self.root = new_node\n return\n node = self.root\n while True:\n if not node.left:\n node.left = new_node\n break\n elif not node.right:\n node.right = new_node\n break\n\n node = node.left\n\n def add_list_to_tree(self, list_of_vals):\n for item in list_of_vals:\n self.add_to_tree(item)\n\n def recur_print(self, node=None):\n if not node:\n return\n\n if node.left:\n print(node.left.val)\n if node.right:\n print(node.right.val)\n\n self.recur_print(node.left)\n self.recur_print(node.right)\n\n def print_tree(self):\n \"\"\"\n This with recur_print function above prints tree in order of additions\n \"\"\"\n if not self.root:\n return\n node = self.root\n print(self.root.val)\n self.recur_print(node)\n\n def check_symmetry_recur(self, list_of_vals, level=1):\n print(\"in\", list_of_vals, level)\n if not list_of_vals:\n return True\n\n nums_to_check = list_of_vals[:level]\n\n if not nums_to_check == nums_to_check[::-1]:\n return False\n\n next_level = level * 2\n return self.check_symmetry_recur(list_of_vals[level:], next_level)\n\n def check_symmetry_iterate(self, list_of_vals):\n level = 1\n while len(list_of_vals):\n nums_to_check = list_of_vals[:level]\n\n if not nums_to_check == nums_to_check[::-1]:\n return False\n\n list_of_vals = list_of_vals[level:]\n level *= 2\n\n return True\n\n\nt = Tree()\n# t.add_list_to_tree([1, 2, 2, 3, 4, 4, 3])\n# t.add_list_to_tree([1, 2, 2, \"null\", 3, \"null\", 3])\n# t.print_tree()\n# print(t.check_symmetry([1, 2, 2, 3, 4, 4, 3]))\n\nassert t.check_symmetry_recur([1, 2, 2, 3, 4, 4, 3])\nassert not t.check_symmetry_recur([1, 2, 2, \"null\", 3, \"null\", 3])\n\nassert t.check_symmetry_iterate([1, 2, 2, 3, 4, 4, 3])\nassert not t.check_symmetry_iterate([1, 2, 2, \"null\", 3, \"null\", 3])\n","sub_path":"symmetric_tree.py","file_name":"symmetric_tree.py","file_ext":"py","file_size_in_byte":2402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"530671592","text":"from django.core.exceptions import ObjectDoesNotExist\n\nfrom rest_framework import serializers\nfrom phone.models import CallDetail, Phone, Call\nfrom phone.choices import START, END, TYPE_CALL_CHOICES\n\nREGEX_NUMBER = r\"^\\d{10,11}\"\n\n\nclass CallDetailSerializer(serializers.Serializer):\n \"\"\"Serialization for CallDetail.\n\n :param call_id: Call id pk.\n :type call_id: int\n\n :param source: number source call\n :type source: str numbers, min lenght 10, max_length 11\n\n :param destination: number destination call\n :type destination: str number, min lenght 10, max_length 11\n\n :param type_call: number destination call\n :type type_call: str choices, start or end\n\n :param timestamp: the datetime starts or ends call\n :type timestamp: str\n\n \"\"\"\n call_id = serializers.IntegerField()\n source = serializers.RegexField(REGEX_NUMBER,\n min_length=10, max_length=11,\n required=False)\n destination = serializers.RegexField(REGEX_NUMBER,\n min_length=10, max_length=11,\n required=False)\n type_call = serializers.ChoiceField(choices=TYPE_CALL_CHOICES)\n timestamp = serializers.DateTimeField()\n\n def validate(self, data):\n \"\"\"Returns the validated_data\n\n :raises: ValidationError\n\n \"\"\"\n call = CallDetail.objects.filter(call_id=data[\"call_id\"],\n type_call=data[\"type_call\"])\n if call:\n raise serializers.ValidationError(\n {\"call_id\": \"call_id already exists for type_call\"})\n\n if data[\"type_call\"] == END:\n\n try:\n call = CallDetail.objects.get(call_id=data[\"call_id\"],\n type_call=START)\n\n if call.timestamp > data[\"timestamp\"]:\n raise serializers.ValidationError(\n {\"timestamp\":\n \"Timestamp start call is > to timestamp\"})\n\n except ObjectDoesNotExist:\n raise serializers.ValidationError(\n {\"call_id\":\n \"call_id does not exists. Please create call start\"})\n\n if data[\"type_call\"] == START:\n\n if not data.get(\"source\") or not data.get(\"destination\"):\n raise serializers.ValidationError(\n \"For type_call start, source and destination is required\")\n elif data[\"source\"] == data[\"destination\"]:\n raise serializers.ValidationError(\n \"source and destination are identical\")\n\n return data\n\n def create(self, validated_data):\n \"\"\"Create the Phone, Destination, Call and\n CallDetail registry\n\n .. note::\n If type_call == 'start' the source and\n destination is required.\n\n :returns: validated_data\n :rtype: dict\n\n \"\"\"\n call_id = validated_data.get(\"call_id\")\n validated = validated_data.copy()\n source = validated.pop(\"source\", \"\")\n destination = validated.pop(\"destination\", \"\")\n\n if validated_data.get(\"type_call\") == START:\n source, created_source = Phone.objects.get_or_create(number=source)\n destination, created_destination = Phone.objects.get_or_create(\n number=destination)\n call, created = Call.objects.get_or_create(\n call_id=call_id,\n source=source,\n destination=destination)\n else:\n call = Call.objects.get(call_id=call_id)\n validated_data[\"source\"] = call.source.number\n validated_data[\"destination\"] = call.destination.number\n\n validated[\"call_id\"] = call\n CallDetail.objects.create(**validated)\n return validated_data\n\n\nclass PhoneSerializer(serializers.ModelSerializer):\n \"\"\"Serialization for Phone.\n\n :param id: phone pk.\n :type id: int auto_add\n\n :param number: phone number.\n :type str: min_length 10, max_length 11\n \"\"\"\n\n class Meta:\n model = Phone\n fields = (\"id\", \"number\")\n","sub_path":"phonecalls/phone/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":4189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"613620687","text":"from random import randint\n\nfrom .AbstractStrategy import AbstractStrategy\nfrom .DeepQ import DeepQ\nfrom ..Game.Game import Game\nfrom .Tree.TETTree import TETTree\nimport numpy as np\nfrom ..Game.Piece import *\n\nimport multiprocessing\nfrom copy import deepcopy\nimport sys\nimport time\n\n\n\ndef get_piece(id):\n if id == 10:\n return LPiece()\n if id == 40:\n return OPiece()\n if id == 70:\n return IPiece()\n if id == 100:\n return JPiece()\n if id == 130:\n return SPiece()\n if id == 160:\n return TPiece()\n if id == 190:\n return ZPiece()\n\n\n# using a neural network is as good as using a random agent as\n# the number of states is huge\n# I thought to use heuristics to train a neural network and help it converge\n# As it gains expertise it may aid the heuristic component by lowering the branching\n# factor relying on the neural net to choose the top k\ndef deep_q_search(child_conn, move_set, enc, rew, id):\n branching_factor = 75\n branches = 81 # total number of actions\n \n game = None\n if child_conn.poll(10):\n game = child_conn.recv()\n \n \n # game = Game()\n # game.piece = get_piece(piece)\n # game.nextPiece = get_piece(piecen)\n lines = TETTree((game.piece._id, 0), (game, 0))\n queue = [(lines.root, game.get_pieces())]\n \n \n with open('botasdf-'+id+'.txt', 'w') as out:\n out.write('move: '+ str(game) + '\\n')\n \n state_size = enc.get_state_size(game)\n deep_Q = DeepQ(state_size, branches, id=id)\n \n first = True\n \n while True:\n \n #with open('botasdf-'+id+'.txt', 'a') as out:\n #out.write('itr: '+ str(len(queue)) + ', ' + str(len(lines.root.children)) + '\\n')\n # BFS the states while waiting\n if len(queue) == 0: continue\n cur_node = queue[0][0]\n piece = queue[0][1][0]\n if len(queue[0][1]) == 1:\n queue = queue[1:]\n else:\n queue[0] = (queue[0][0], queue[0][1][1:])\n cur_game = deepcopy(cur_node.value[0])\n cur_game.piece = piece\n state = enc.get_state(cur_game)\n for viable in deep_Q.choosek(branching_factor, state):\n line = cur_game.simulate_game(move_set[viable[0]])\n if line is None: continue\n reward = rew.get_reward(line)\n deep_Q.learn(state, viable[0], enc.get_state(line), reward)\n new_node = cur_node.create_child((piece._id, viable[0]), (line, reward), parent=cur_node)\n new_node.bubble_up(reward)\n queue.append((new_node, line.get_pieces()))\n \n \n if child_conn.poll() or first:\n if first:\n first = False\n else:\n game = child_conn.recv() # Read from the output pipe\n \n if game.won == 1:\n deep_Q.win()\n break\n elif game.won == 0:\n deep_Q.lost()\n break\n \n piecenext = game.nextPiece._id\n lines.filter_for_next_piece(piecenext)\n move = lines.max_move()\n child_conn.send(move)\n with open('botasdf-'+id+'.txt', 'a') as out:\n out.write('move: '+ str(move) + '\\n')\n \n lines = TETTree((piece, 0), (game, 0))\n queue = [(lines.root, game.get_pieces())]\n \n child_conn.close()\n \n \n\nclass SearchDeepQStrategy(AbstractStrategy):\n def __init__(self, game, encoder, rewarder):\n AbstractStrategy.__init__(self, game, encoder, rewarder)\n # the method is integral to the encoder\n # nn could do topheights, but topheights is better on sa\n if encoder == 'flat':\n method = 'lnn'\n elif encoder == 'topheights':\n method = 'sa'\n elif encoder == 'flatplus':\n method = 'lnn'\n self.move_set = self.build_action_list()\n \n self.first_turn = True\n \n enc = deepcopy(self._encoder)\n rew = deepcopy(self._rewarder)\n self.parent_conn, child_conn = multiprocessing.Pipe()\n search = multiprocessing.Process(target=deep_q_search, args=(child_conn, self.move_set, enc, rew, self._game.id,))\n search.daemon = True\n search.start()\n\n def choose(self):\n self.parent_conn.send(self._game)\n with open('botasdf-'+self._game.id+'.txt', 'a') as out:\n out.write('pieces: '+ str(self._game.nextPiece._id) + '\\n')\n time.sleep(.6)\n move = 0\n if self.parent_conn.poll(.1):\n move = int(self.parent_conn.recv()) # Read from the output pipe\n return self.move_set[move]\n \n def get_reward(self):\n return self._rewarder.get_reward(self._game)\n \n def get_state_size(self):\n return self._encoder.get_state_size(self._game)\n \n \n def get_num_states(self):\n return self._encoder.get_num_states()\n \n def end(self, won):\n self._game.won = won\n self.parent_conn.send(self._game)\n time.sleep(.1)\n self.parent_conn.close()\n \n \n ","sub_path":"TETbot/asdfBot/Bot/Strategies/SearchDeepQStrategy.py","file_name":"SearchDeepQStrategy.py","file_ext":"py","file_size_in_byte":5178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"321266864","text":"from __future__ import print_function\nimport struct\nimport logging\nlogger = logging.getLogger(__name__)\nimport json\nfrom pprint import pprint\nimport os\nimport itertools\nimport math\nfrom binascii import hexlify\nfrom locators.core_dump import locate as locate_core_dump\nfrom dwarf import decode_object, Structure\nfrom dwarf import Array as darray\nfrom hansei_utils import *\nfrom targ_spec_config import *\nimport csv\nfrom summary import chip_version\nimport xml.etree.ElementTree as ET\nimport pdb\n\n\ndrvList = [\"SENSORS\",\"COMPUTE\",\"MODEM\",\"APPS\"]\nhwioName = [\"SSC\",\"TURING\",\"MSS\",\"APSS\"]\n\ndic = {}\n\ndef readReg(address):\n \n address2 = int(address, 16)\n data = memory.read(address2, 4)\n value = struct.unpack('>0x15\n offset = (voteCmp&0xffff)>>0x0\n \n print(\"Last Acked. --> \"+str(hex(voteCmp)) + \" (Slave: \" + str(slvId) +\", Offset: \" +str(hex(offset))+\" )\", file=pdc2_file)\n \n epcbRxAddr = dic[epcbRxAddrReg]\n slvId = (epcbRxAddr&0xE00000)>>0x15\n offset = (epcbRxAddr&0xffff)>>0x0\n \n print(\"Last Rcvd. Addr. --> \"+str(hex(epcbRxAddr)) + \" (Slave: \" + str(slvId) +\", Offset: \" +str(hex(offset))+\" )\", file=pdc2_file)\n print(\"Last Rcvd. Data. --> \"+str(hex(dic[epcbRxDataReg])), file=pdc2_file)\n \n \n rscParamReg=\"RPMH_PDC_\"+image+\"_PDC_PARAM_RESOURCE_DRV0\"\n\n numCmd=(dic[rscParamReg]&0xe0)>>0x5\n numTcs=(dic[rscParamReg]&0xf00)>>0x8\n \n for i in range(numTcs):\n print(\"===========================================\", file=pdc_file)\n print(\"TCS no. : \" +str(i), file=pdc_file)\n\n controlReg=\"RPMH_PDC_\"+image+\"_TCS\"+str(i)+\"_CONTROL\"\n #print(controlReg)\n isAmc=(dic[controlReg]&0x10000)>>0x10\n if(isAmc==0):\n print(\"Type : PDC Sleep/Wake TCS\", file=pdc_file)\n else:\n print(\"Type : PDC Active TCS\", file=pdc_file)\n\n idleReg=\"RPMH_PDC_\"+image+\"_TCS\"+str(i)+\"_DRV\"+str(j)+\"_STATUS\"\n isIdle=(dic[idleReg]&0x1)>>0x0\n if(isIdle==0):\n print(\"Status : Busy\", file=pdc_file)\n else:\n print(\"Status : Idle\", file=pdc_file)\n \n print(\"=============================================\", file=pdc_file)\n print(\"No Enbld R/W Resp Len Complete Issue Trigger Address Data\", file=pdc_file)\n print(\"---------------------------------------------------------------------\", file=pdc_file)\n for k in range(numCmd):\n commandEnableReg=\"RPMH_PDC_\"+image+\"_TCS\"+str(i)+\"_CMD_ENABLE_BANK\"\n \n #print(dic[commandEnableReg])\n isEnabled=dic[commandEnableReg]&(1<>0x8\n if(respReq==0):\n resp=\"F&F\"\n else:\n resp=\"Req\"\n\n readWrite=(msgId&0x10000)>>0x10\n if(readWrite==0):\n read=\" Read\"\n else:\n read=\"Write\"\n\n msgLength=(msgId&0xf)>>0x00\n\n cmdStatusReg=\"RPMH_PDC_\"+image+\"_TCS\"+str(i)+\"_CMD\"+str(k)+\"_DRV\"+str(j)+\"_STATUS\"\n #print(cmdStatusReg)\n cmdStatus=dic[cmdStatusReg]\n\n #print(cmdStatus)\n\n completedVal=(cmdStatus&0x10000)>>0x10\n issuedVal=(cmdStatus&0x100)>>0x8\n triggeredVal=(cmdStatus&0x1)>>0x0\n \n \n\n print(str(k)+ \" \" + enabledStr +\" \" +read +\" \" + resp + \" \"+ str(msgLength) +\" \" + str(completedVal) +\" \"+ str(issuedVal) + \" \" + str(triggeredVal)+ \" \"+ '{:8s}'.format(str(hex(cmdAddress))) + \" \"+ str(hex(cmdData)), file=pdc_file)\n\n \n \n except Exception as e:\n dump_error = 1\n \n if dump_error != 0:\n debug_data['printer'].p(\"\\t...Non-critical errors occured in processing dump, continuing\")\n else:\n debug_data['printer'].p(\"\\t...DONE\")\n","sub_path":"aop_proc/core/bsp/aop/scripts/hansei/dumpers/pdc_tcs.py","file_name":"pdc_tcs.py","file_ext":"py","file_size_in_byte":8133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"455107778","text":"import librosa\nimport numpy as np\nfrom keras import models\nimport os\nimport argparse\nimport time#\n\ndef load(file_name):\n print(\"load 실행\")#\n wav = file_name\n file_sr = librosa.get_samplerate(wav)\n y, sr = librosa.load(wav, sr=file_sr)\n \n if(sr != 16000):\n print(\"resampling 진행\")\n y = librosa.resample(y, sr, 16000)\n \n return y\n\ndef make_patches(y):\n print(\"make_patches 실행\")#\n \n test = []\n for i in range(int((len(y)/1600))-19):\n p = i * 1600\n q = p + 32000\n split = y[p:q]\n \n max_mine = np.max(split)\n ratio = 0.46202388 / max_mine\n split = split * ratio\n \n mfcc = librosa.feature.mfcc(split, sr=16000)\n test.append(mfcc)\n test = np.array(test)\n test_X = np.expand_dims(test, -1)\n \n return test_X\n\ndef predict(test_audio, model):\n print(\"predict 실행\")#\n test_X = make_patches(load(test_audio))\n \n Y_pred = model.predict(test_X)\n y_pred = np.argmax(Y_pred,axis=1)\n \n return y_pred\n\ndef get_time(fire_predict):\n for i in range(len(fire_predict)):\n k = round(fire_predict[i] * 0.1,2)\n print(str(k) , \"초 ~\", str((k+2)) , \"초 불이야 감지\")\n \n \ndef get_result(y_pred):\n fire_count = 0\n non_count = 0\n fire_predict = []\n temp_predict = []\n \n for i in range(len(y_pred)):\n \n if(y_pred[i] == 0):\n non_count = non_count + 1\n \n if(non_count >= 4):\n fire_count = 0\n \n else :\n fire_count = fire_count + 1\n non_count = 0\n if(fire_count >= 6):\n temp_predict.append(i)\n n = 0\n for i in range(len(temp_predict)):\n if(temp_predict[i] > n):\n fire_predict.append(temp_predict[i])\n n = temp_predict[i] + 20\n \n if(fire_predict):\n print(\"갯수\",len(fire_predict))\n get_time(fire_predict)\n else:\n print(\"불이야 감지 못함\")\n\ndef main():\n start = time.time()#\n print(\"main 실행\")#\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--test_audio\", type=str, help=\"input audio, wav file\", required = True)\n parser.add_argument(\"--model_dir\", type=str, help=\"model, h5 file\", required = True)\n \n args = parser.parse_args()\n test_audio = args.test_audio\n model_dir = args.model_dir\n \n model = models.load_model(model_dir)\n \n get_result(predict(test_audio, model))\n print(\"time :\", time.time() - start)#\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"src/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"282498340","text":"# %%\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport datetime\nimport os\nimport json \nimport urllib.request as req\nimport urllib\n # For this to run you will first need to install the following: \n # conda install urllib3\n # conda install json\n\n# %%\n# Mesonet Example\n# Here are some helpful links for getting started\n# https: // developers.synopticdata.com/about/station-variables/\n# https: // developers.synopticdata.com/mesonet/explorer/\n\n# First Create the URL for the rest API\n# Insert your token here\nmytoken = 'demotoken'\n\n# This is the base url that will be the start our final url\nbase_url = \"http://api.mesowest.net/v2/stations/timeseries\"\n\n# Specific arguments for the data that we want\nargs = {\n 'start': '199701010000',\n 'end': '202010230000',\n 'obtimezone': 'UTC',\n 'vars': 'air_temp,precip_accum',\n 'stids': 'QVDA3',\n 'units': 'temp|C,precip|mm',\n 'token': mytoken}\n\n# Takes your arguments and paste them together\n# into a string for the api\n# (Note you could also do this by hand, but this is better)\napiString = urllib.parse.urlencode(args)\nprint(apiString)\n\n# add the API string to the base_url\nfullUrl = base_url + '?' + apiString\nprint(fullUrl, '\\n')\n\n# Now we are ready to request the data\n# this just gives us the API response... not very useful yet\nresponse = req.urlopen(fullUrl)\n\n# What we need to do now is read this data\n# The complete format of this \nresponseDict = json.loads(response.read())\n\n# This creates a dictionary for you \n# The complete format of this dictonary is descibed here: \n# https://developers.synopticdata.com/mesonet/v2/getting-started/\n# Keys shows you the main elements of your dictionary\nresponseDict.keys()\n# You can inspect sub elements by looking up any of the keys in the dictionary\nresponseDict['UNITS']\n# Each key in the dictionary can link to differnt data structures\n# For example 'UNITS is another dictionary'\ntype(responseDict['UNITS'])\nresponseDict['UNITS'].keys()\nresponseDict['UNITS']['position']\n\n# where as STATION is a list \ntype(responseDict['STATION'])\n# If we grab the first element of the list that is a dictionary\ntype(responseDict['STATION'][0])\n# And these are its keys\nresponseDict['STATION'][0].keys()\n\n# Long story short we can get to the data we want like this: \ndateTime = responseDict['STATION'][0]['OBSERVATIONS']['date_time']\nairT = responseDict['STATION'][0]['OBSERVATIONS']['air_temp_set_1']\nprecip = responseDict['STATION'][0]['OBSERVATIONS']['precip_accum_set_1']\n\n# Now we can combine this into a pandas dataframe\ndata = pd.DataFrame({'Temperature': airT, 'Precipitation': precip}, index=pd.to_datetime(dateTime))\n\n# Now convert this to daily data using resample\ndata_daily = data.resample('D').mean().round(2)\ndata_weekly = data.resample('W').mean().round(2)\n\n\n# %%\n# Daymet Example:\n# You can get Daymet data for a single pixle form this site:\n# https: // daymet.ornl.gov/single-pixel/ \n# You can also experiment with their API Here: \n# https: // daymet.ornl.gov/single-pixel/api \n\n# Example reading it as a json file\nurl = \"https://daymet.ornl.gov/single-pixel/api/data?lat=34.9455&lon=-113.2549\" \\\n \"&vars=prcp&start=1989-01-01&end=2020-10-23&format=json\"\nresponse = req.urlopen(url)\n# Look at the kesy and use this to grab out the data\nresponseDict = json.loads(response.read())\nresponseDict['data'].keys()\nyear = responseDict['data']['year']\nyearday = responseDict['data']['yday']\nprecip = responseDict['data']['prcp (mm/day)']\n\n# make a dataframe from the data\ndata2 = pd.DataFrame({'year': year,\n 'yearday': yearday, \"precip\": precip})\n\n\n# Example accessing it as a csv\nurl = \"https://daymet.ornl.gov/single-pixel/api/data?lat=34.9455&lon=-113.2549\" \\\n \"&vars=prcp&years=&format=csv\"\ndata2 = pd.read_table(url, delimiter=',', skiprows=6)\n\n\n# %%\n# Xenia\n\nargs = {\n 'token': 'demotoken',\n 'radius': '34.44833333,-111.78916667,10',\n 'limit': 10,\n 'start': '199701010000',\n 'end': '202010230000',\n 'obtimezone': 'UTC',\n 'vars': 'air_temp,precip_accum',\n 'stids': 'QVDA3',\n 'units': 'temp|C,precip|mm'}\n\napiString = urllib.parse.urlencode(args)\nprint(apiString)\n\nurlXbase = 'https://api.synopticdata.com/v2/stations/timeseries'\n\n# add the API string to the base_url\nfullUrl = urlXbase + '?' + apiString\nprint(fullUrl)\n\n# Now we are ready to request the data\n# this just gives us the API response... not very useful yet\nresponse = req.urlopen(fullUrl)\n\n# What we need to do now is read this data\n# The complete format of this\nresponseDict = json.loads(response.read())\n\n# %%\n","sub_path":"assignment_9/Week9_API_DataReading_starter.py","file_name":"Week9_API_DataReading_starter.py","file_ext":"py","file_size_in_byte":4600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"573448931","text":"import vmware.common.global_config as global_config\nimport vmware.common.utilities as utilities\nimport vmware.linux.cmd.linux_os_impl as linux_os_impl\n\npylogger = global_config.pylogger\n\n\nclass DefaultOSImpl(linux_os_impl.LinuxOSImpl):\n\n # NOTE: Different netcat versions have different flags/usage. Choosing this\n # as the default version. In case some templates have a different version,\n # they should override this method in corresponding impl file for that OS.\n @classmethod\n def start_netcat_server(cls, client_object, ip=None, port=None, udp=None,\n wait=None):\n \"\"\"\n Starts a listening process for inbound connections using netcat.\n\n @type client_object: VMCMDClient\n @param client_object: Client object\n @type ip: string\n @param ip: IP address to bind the listening process.\n @type port: integer\n @param port: port to start the listening on.\n @type udp: boolean\n @param udp: Use UDP instead of the default option of TCP\n @type wait: boolean\n @param wait: If True, run cmd as blocking call, else as non-blocking\n @rtype: vmware.common.result.Result object\n @return: result object.\n \"\"\"\n if not port:\n raise ValueError(\"Missing port number to listen using netcat\")\n # Set default behavior to blocking call.\n wait = utilities.get_default(wait, True)\n cmd = 'nc -l'\n if ip:\n cmd = '%s %s' % (cmd, ip)\n cmd = '%s %s' % (cmd, int(port))\n if udp:\n cmd = '%s -u' % cmd\n if not wait:\n cmd = \"%s >> /dev/null 2>&1 &\" % cmd\n return client_object.connection.request(cmd)\n","sub_path":"SystemTesting/pylib/vmware/vsphere/vm/cmd/default_os_impl.py","file_name":"default_os_impl.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"276567668","text":"import urllib, urllib.request\nimport requests\nimport shutil\nimport time\nimport os\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom UserClass import UserInfo, PostDownload\n\n#res.status_code == requests.codes.ok/200\n\n'''The code written in here is the firt version of the\n Instagram Image Downloader (InstaLoad) app.'''\n\ndef get_username():\n url = 'https://www.instagram.com/'\n username = str(input('Enter username: @'))\n userpage = url + username + '/'\n\n return username, userpage\n\ndef open_userpage(userpage):\n driver = webdriver.PhantomJS(executable_path = r'C:\\Users\\Wahhaj\\AppData\\Roaming\\npm\\node_modules\\phantomjs-prebuilt\\lib\\phantom\\bin\\phantomjs')\n #driver = webdriver.Chrome(executable_path = r'C:\\Users\\Wahhaj\\AppData\\Local\\Programs\\Python\\Python35\\Lib\\site-packages\\selenium\\webdriver\\chrome\\chromedriver.exe')\n driver.get(userpage)\n driver.set_window_size(1920, 1200)\n time.sleep(3)\n element = driver.find_element_by_xpath('/html/body')\n element.send_keys(Keys.END)\n time.sleep(3)\n driver.find_element_by_link_text('Load more').click()\n \n return driver\n\ndef scroll_to_end(driver):\n \n soup = BeautifulSoup(driver.page_source, 'lxml')\n holder = []\n for span in soup.findAll('span', {'class':'_bkw5z'}):\n posts = span.text\n holder.append(posts)\n\n posts = holder[0].replace(',', '') \n hrefs = get_image_links(soup)\n\n \n while len(hrefs) < int(posts):\n element = driver.find_element_by_xpath('/html/body')\n driver.execute_script(\"window.scrollTo(0,document.body.scrollHeight);\")\n #element.send_keys(Keys.END)\n time.sleep(3)\n soup_1 = BeautifulSoup(driver.page_source, 'lxml')\n time.sleep(2)\n hrefs = get_image_links(soup_1)\n\n return hrefs\n\ndef get_image_links(soup):\n \n hrefs = []\n for a in soup.findAll('a'):\n href = a.get('href')\n if href.startswith('/p/'):\n hrefs.append(href)\n\n return hrefs \n\ndef get_url(hrefs, driver):\n\n img_links = []\n vid_links = []\n url = 'https://www.instagram.com'\n for href in hrefs:\n post_url = url + href\n driver.get(post_url)\n time.sleep(3)\n soup = BeautifulSoup(driver.page_source, 'lxml')\n album_check = soup.findAll('a', {'class':'_90kqf _qwk2e coreSpriteRightChevron'})\n\n if album_check:\n for img in soup.findAll('img', {'class':'_icyx7'}):\n img_link = img.get('src')\n img_links.append(img_link)\n\n for vid in soup.findAll('video', {'class':'_c8hkj'}):\n vid_link = vid.get('src')\n vid_links.append(vid_link)\n \n while album_check:\n print('In album loop')\n driver.find_element_by_css_selector('._90kqf._qwk2e.coreSpriteRightChevron').click()\n time.sleep(5)\n soup_2 = BeautifulSoup(driver.page_source, 'lxml')\n time.sleep(2)\n \n for img in soup_2.findAll('img', {'class':'_icyx7'}):\n img_link = img.get('src')\n img_links.append(img_link)\n\n for vid in soup_2.findAll('video', {'class':'_c8hkj'}):\n vid_link = vid.get('src')\n vid_links.append(vid_link)\n \n album_check = soup_2.findAll('a', {'class':'_90kqf _qwk2e coreSpriteRightChevron'})\n\n else: \n for img in soup.findAll('img', {'class':'_icyx7'}):\n img_link = img.get('src')\n img_links.append(img_link)\n\n for vid in soup.findAll('video', {'class':'_c8hkj'}):\n vid_link = vid.get('src')\n vid_links.append(vid_link)\n\n return img_links, vid_links\n\ndef make_file(username):\n path = os.getcwd()\n filename = username\n full_path = os.path.join(path, filename)\n os.mkdir(full_path)\n\ndef make_cat_file(username):\n path = os.getcwd() + '\\\\' + username\n image_file = 'Images'\n video_file = 'Videos'\n video = os.path.join(path, video_file) \n image = os.path.join(path, image_file)\n os.mkdir(image)\n os.mkdir(video)\n\ndef save_images(username, img_links):\n \n num_list = list(range(1,len(img_links)+1))\n num_list = [str(x) for x in num_list]\n for x,y in zip(img_links, num_list):\n filename = y\n path = os.getcwd() + '\\\\' + username + '\\\\Images\\\\'\n fullpath = os.path.join(path, filename) + '.jpg'\n urllib.request.urlretrieve(x, fullpath)\n \ndef save_videos(username, vid_links):\n \n num_list = list(range(1,len(vid_links)+1))\n num_list = [str(x) for x in num_list]\n for x,y in zip(vid_links, num_list):\n filename = y\n path = os.getcwd() + '\\\\' + username + '\\\\Videos\\\\'\n fullpath = os.path.join(path, filename) + '.mp4'\n #urllib.request.urlretrieve(x, fullpath)\n #urllib.request.FancyURLopener().retrieve(x, fullpath)\n r = requests.get(x, stream=True)\n with open(fullpath, 'wb') as f_obj:\n shutil.copyfileobj(r.raw, f_obj)\n\ndef main(): \n username, userpage = get_username()\n account = UserInfo(username, userpage)\n driver = account.open_userpage(userpage)\n hrefs = account.scroll_to_end(driver)\n img_links, vid_links = account.get_url(hrefs, driver)\n download = PostDownload(username, img_links, vid_links)\n download.make_file(username)\n download.make_cat_file(username)\n download.save_images(username, img_links)\n download.save_videos(username, vid_links)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Source/v1.0.py","file_name":"v1.0.py","file_ext":"py","file_size_in_byte":5865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"513426739","text":"import pyaudio\nimport speech_recognition as sr\nimport pyttsx3\nimport os\n\nos.system('cls')\n\nprint('Liquor 2.0')\n\nengine = pyttsx3.init()\n\nr = sr.Recognizer() \nmic = sr.Microphone(device_index=0) \n\ndef main():\n audio = None\n with mic as source:\n print('listening...')\n try:\n audio = r.listen(source, 1, 2)\n except sr.WaitTimeoutError:\n pass\n if audio is not None:\n try:\n result = (r.recognize_google(audio)).split()\n print('running')\n\n for i in result:\n if len(i) > 4:\n s = i\n \n if(s == 'terminate'):\n engine.say(\"late her? I barely even knew her!\")\n engine.runAndWait()\n exit()\n\n if i.endswith('s'):\n s = str(s[:-1]) \n \n if s.endswith(('er', 'or', 'ur')):\n print(\"{0} her? I barely even knew her!\".format(s[:-2]))\n engine.say(\"{0} her? I barely even knew her!\".format(s[:-2]))\n engine.runAndWait()\n print('done')\n except sr.UnknownValueError:\n print('???')\n main()\n\nmain()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"493343559","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: build/bdist.macosx-10.11-x86_64/egg/reviewbot/tools/pmd.py\n# Compiled at: 2018-07-31 04:26:56\nfrom __future__ import unicode_literals\nimport csv, logging\nfrom os.path import splitext\nfrom reviewbot.config import config\nfrom reviewbot.tools import Tool\nfrom reviewbot.utils.filesystem import make_tempfile\nfrom reviewbot.utils.process import execute, is_exe_in_path\n\nclass PMDTool(Tool):\n \"\"\"Review Bot tool to run PMD.\"\"\"\n name = b'PMD'\n version = b'1.0'\n description = b'Checks code for errors using the PMD source code checker.'\n timeout = 90\n options = [\n {b'name': b'rulesets', \n b'field_type': b'django.forms.CharField', \n b'default': b'', \n b'field_options': {b'label': b'Rulesets', \n b'help_text': b'A comma-separated list of rulesets to apply or an XML configuration starting with \"
\" % (url, img_url))\n \n # handle book information\n title = book['title']\n author = book['author']\n isbn = book['isbn10']\n\n if len(title) > cutoff: title = title[0:cutoff] + \"...\"\n if len(author) > cutoff: author = author[0:cutoff] + \"...\"\n if len(isbn) > cutoff: isbn = isbn[0:cutoff] + \"...\"\n \n amount = \"amount_low\"\n if int(book[\"num_sellers\"]) > 3: amount = \"amount_medium\"\n elif int(book[\"num_sellers\"]) > 7: amount = \"amount_high\"\n\n html = \"%s
\" % (url, title)\n html += \"ISBN-10: %s
\" % isbn\n html += \"%s
\" % author\n if self.type == \"wish\":\n html += \"Sellers: %s\" % (amount, book[\"num_sellers\"])\n else:\n html += \"Watchers: %s\" % (amount, book[\"num_watchers\"])\n\n html_entry = HTML(html)\n\n # remove button\n btn_remove_book = ListButton(\"x\", self.remove_book, book[\"asin\"], book[\"title\"], row)\n \n self.setWidget(row, 0, img_html)\n self.setWidget(row, 1, html_entry)\n self.getCellFormatter().addStyleName(row, 1, \"entry_text\")\n self.setWidget(row, 2, btn_remove_book)\n self.getCellFormatter().addStyleName(row, 2, \"entry_button\")\n self.getRowFormatter().addStyleName(row, \"userlist_entry\")\n\n def remove_book(self, sender):\n \"\"\" remove a book from this list AND from the database\n \"\"\"\n if self.type == \"sell\":\n self.context.remote.remove_from_sell_list(self.context, sender.asin)\n elif self.type == \"wish\":\n self.context.remote.remove_from_wish_list(self.context, sender.asin)\n self.removeRow(sender.row)\n\n # add event\n params = {}\n params['title'] = sender.title\n params['fbid'] = self.context.facebook_user['facebook_id']\n params['name'] = self.context.facebook_user['full_name']\n params['type'] = self.type\n params['gender'] = self.context.facebook_user['gender']\n self.context.remote.add_event(self.context, 'remove_book', params)\n\nclass PageIndex:\n def onModuleLoad(self):\n # JSON RPC response containers\n self.facebook_user = {}\n self.app_info = {}\n self.wl_books = []\n self.sl_books = []\n self.events = []\n\n # setup JSON RPC\n self.remote = DataService()\n\n # make JSON RPC calls\n self.remote.get_app_info(self, \"index\")\n self.remote.get_wish_list(self)\n self.remote.get_sell_list(self)\n\n self.remote.get_events(self, 10)\n\n # panels\n self.main_panel = HorizontalPanel()\n self.feed_panel = VerticalPanel()\n self.list_panel = VerticalPanel()\n\n self.feed_panel.addStyleName(\"feed_panel\")\n self.list_panel.addStyleName(\"list_panel\")\n\n # labels\n self.html_feed_title = HTML(\"

Recent Activity

\")\n self.html_wish_title = HTML(\"

Your Wishlist

\")\n self.html_sell_title = HTML(\"

Your Selllist

\")\n\n # user lists\n self.wish_list = UserList(\"wish\", self)\n self.sell_list = UserList(\"sell\", self)\n\n self.wish_list.addStyleName(\"userlist\")\n self.sell_list.addStyleName(\"userlist\")\n\n self.feed_panel.add(self.html_feed_title)\n\n self.list_panel.add(self.html_wish_title)\n self.list_panel.add(self.wish_list)\n\n self.list_panel.add(HTML(\"
\"))\n self.list_panel.add(self.html_sell_title)\n self.list_panel.add(self.sell_list)\n\n # add everything together\n self.main_panel.add(self.feed_panel)\n self.main_panel.add(self.list_panel)\n self.main_panel.setWidth(\"100%\")\n\n RootPanel(\"page_index\").add(self.main_panel)\n\n show_events = self.show_events\n class EventTimer(Timer):\n def run(self):\n show_events()\n et = EventTimer()\n self.show_events()\n et.scheduleRepeating(5000)\n\n def populate_book_lists(self):\n \"\"\" check the JSON RPC containers and fill the UserLists if\n it finds them to be non-empty\n \"\"\"\n for b in self.wl_books:\n Window.alert(str(b))\n self.wish_list.add_book(b)\n \n for b in self.sl_books:\n self.sell_list.add_book(b)\n return True\n\n def show_events(self):\n \"\"\" create events on the recent activity feed \n \"\"\"\n for e in self.events:\n self.add_event(e)\n self.events = []\n\t\n def add_event(self, event):\n \"\"\" add an event to the recent activity feed\n \"\"\"\n event_panel = HorizontalPanel()\n mid_panel = VerticalPanel()\n book_panel = HorizontalPanel()\n\n # profile picture\n pic_url = \"https://graph.facebook.com/\" + event['fbid'] + \"/picture\"\n pic_html = HTML(\"\" % pic_url)\n\n # event string\n event_html = HTML(\"%s\" % event['string'])\n url = self.app_info['url'] + \"book?asin=\" + event['book']['asin']\n\n cutoff = 40\n # book thumbnail\n img_url = event['book']['thumbnail']\n if event['book'][\"thumbnail\"] == \"N/A\":\n img_url = self.app_info['url'] + \"static/images/default_thumbnail.png\"\n img_html = HTML(\"\" % (url, img_url))\n\n # handle book information\n title = event['book']['title']\n author = event['book']['author']\n isbn = event['book']['isbn10']\n\n if len(title) > cutoff: title = title[0:cutoff] + \"...\"\n if len(author) > cutoff: author = author[0:cutoff] + \"...\"\n if len(isbn) > cutoff: isbn = isbn[0:cutoff] + \"...\"\n\n html = \"%s
\" % (url, title)\n html += \"ISBN-10: %s
\" % isbn\n html += \"%s
\" % author\n html_entry = HTML(html)\n\n book_panel.add(img_html)\n book_panel.add(html_entry)\n\n mid_panel.add(event_html)\n mid_panel.add(book_panel)\n \n event_panel.add(pic_html)\n event_panel.add(mid_panel)\n\n# html = \"%s
\" % unicode(event['time'])\n# event_panel.add(HTML(html))\n self.feed_panel.add(event_panel)\n\t\n def onRemoteResponse(self, response, request_info):\n \"\"\" Called when a response is received from an RPC\n \"\"\"\n if request_info.method == \"get_facebook_user\":\n for k, v in response.items():\n self.facebook_user[k] = v\n elif request_info.method == \"get_app_info\":\n for k, v in response.items():\n self.app_info[k] = v\n elif request_info.method == \"get_wish_list\":\n self.wl_books = response\n for b in self.wl_books:\n self.wish_list.add_book(b)\n elif request_info.method == \"get_sell_list\":\n self.sl_books = response\n for b in self.sl_books:\n self.sell_list.add_book(b)\n elif request_info.method == \"add_event\":\n self.events.append(response)\n elif request_info.method == \"get_events\":\n self.events = response\n\n def onRemoteError(self, code, message, request_info):\n \"\"\" Called when a returned response is invalid or Server Error\n \"\"\"\n code = str(code)\n message = str(message)\n\n if len(code) > 200: code = code[0:200] + \"...\"\n if len(message) > 200: message = message[0:200] + \"...\"\n\n err_msg = Label(\"Server Error or invalid response: ERROR \" + str(code) + \" - \" + str(message))\n err_msg.addStyleName(\"status\")\n Window.alert(err_msg.getText())\n \nclass DataService(JSONProxy):\n methods = ['get_facebook_user', 'get_app_info', 'get_wish_list', 'get_sell_list', 'remove_from_wish_list', 'remove_from_sell_list', 'add_event', 'get_events']\n\n def __init__(self):\n JSONProxy.__init__(self, 'services/', DataService.methods)\n\nif __name__ == '__main__':\n app = PageIndex()\n app.onModuleLoad()\n","sub_path":"pyjamas_files/page_index.py","file_name":"page_index.py","file_ext":"py","file_size_in_byte":9897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"432306490","text":"# Copyright 2021 AI Singapore\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# https://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\"\"\"\nDisplays info from dabble nodes such as fps, object count and zone counts in a legend box\n\"\"\"\n\nfrom typing import Any, Dict, List\nfrom peekingduck.pipeline.nodes.node import AbstractNode\nfrom peekingduck.pipeline.nodes.draw.utils.legend import Legend\n\n\nclass Node(AbstractNode):\n \"\"\"Draw node for drawing Legend box and info on image\n\n The draw legend node dynamically pulls the output results of previous nodes\n And uses it to draw the information into a legend box. Currently draws fps,\n object counts and object count in zones.\n\n all_legend_item: config is all possible items that can be drawn in legend box\n include: is used to select which information would be drawn\n This is so we can have the outputs but choose not to drawn on screen\n\n Inputs:\n\n all (:obj:`Any`): Receives inputs from all preceding outputs to use\n ass dynamic input for legend creation.\n\n Outputs:\n |none|\n\n Configs:\n position (:obj:`str`): **default = \"bottom\"**\n Position to draw legend box. \"top\" draws it at the top-left position\n while \"bottom\" draws it at bottom-left.\n\n include (:obj:`list`): **default = [\"all_legend_items\"]**\n List of information to draw. Current can draw \"fps\", \"count\" and/or\n \"zone_count\". The default value \"all_legend_items\" draws everything\n dynamically depending on inputs.\n \"\"\"\n\n def __init__(self, config: Dict[str, Any] = None, **kwargs: Any) -> None:\n super().__init__(config, node_path=__name__, **kwargs)\n self.legend_items: List[str] = []\n\n def run(self, inputs: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"Draws legend box with information from nodes\n\n Args:\n inputs (dict): Dict with all available keys\n\n Returns:\n outputs (dict): Dict with keys \"none\"\n \"\"\"\n if len(self.legend_items) == 0:\n # Check inputs to set legend items to draw\n if self.include[0] == 'all_legend_items': # type: ignore\n self.include = self.all_legend_items # type: ignore\n self._include(inputs)\n if len(self.legend_items) != 0:\n Legend().draw(inputs, self.legend_items, self.position) # type: ignore\n else:\n return {}\n # cv2 weighted does not update the referenced image. Need to return and replace.\n return {'img': inputs['img']}\n\n def _include(self, inputs: Dict[str, Any]) -> None:\n for item in self.all_legend_items:\n if item in inputs.keys() and item in self.include:\n self.legend_items.append(item)\n","sub_path":"peekingduck/pipeline/nodes/draw/legend.py","file_name":"legend.py","file_ext":"py","file_size_in_byte":3208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"573312422","text":"# Copyright 2019 Ram Rachum and collaborators.\n# This program is distributed under the MIT license.\n\nimport abc\nimport sys\n\nfrom .pycompat import ABC\n\ndef _check_methods(C, *methods):\n mro = C.__mro__\n for method in methods:\n for B in mro:\n if method in B.__dict__:\n if B.__dict__[method] is None:\n return NotImplemented\n break\n else:\n return NotImplemented\n return True\n\n\nclass WritableStream(ABC):\n @abc.abstractmethod\n def write(self, s):\n pass\n\n @classmethod\n def __subclasshook__(cls, C):\n if cls is WritableStream:\n return _check_methods(C, 'write')\n return NotImplemented\n\n\nfile_reading_errors = (\n IOError,\n OSError,\n ValueError # IronPython weirdness.\n)\n\n\ndef shitcode(s):\n return ''.join(\n (c if (0 < ord(c) < 256) else '?') for c in s\n )\n","sub_path":"pysnooper/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"340874208","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/joel/Workspace/templ8/templ8/models.py\n# Compiled at: 2020-03-04 08:43:07\n# Size of source mod 2**32: 2758 bytes\nimport os, subprocess\nfrom pyimport import path_guard\npath_guard(__file__, '..')\nfrom exceptions import MissingConfig\nfrom utils import get_child_files\nfrom dataclasses import dataclass, field\nfrom typing import List, Tuple, Any, Callable, Dict, Iterator, Union\nfrom jinja2 import Environment, FileSystemLoader, Template\n\n@dataclass\nclass Context:\n name: str\n default: Any = None\n\n def emit_from_config(self, config: dict) -> Tuple[(str, Any)]:\n if config:\n if self.name in config:\n return (\n self.name, config[self.name])\n if self.default:\n return (\n self.name, self.default)\n raise MissingConfig(self.name)\n\n\n@dataclass\nclass Alias:\n context: Context\n formatter = lambda x: str(x).replace('-', '_')\n formatter: Callable[([Any], str)]\n\n def resolve(self, config: dict) -> str:\n name, value = self.context.emit_from_config(config)\n return self.formatter(value)\n\n\n@dataclass\nclass Callback:\n call: List[Union[(str, Alias)]]\n\n def run(self, config: dict, output_dir: str) -> None:\n resolved_call = [i.resolve(config) if isinstance(i, Alias) else i for i in self.call]\n subprocess.run(resolved_call, cwd=output_dir)\n\n\n@dataclass\nclass Spec:\n root_name: str\n dependencies = field(default_factory=list)\n dependencies: List[str]\n context_set = field(default_factory=list)\n context_set: List[Context]\n folder_aliases = field(default_factory=dict)\n folder_aliases: Dict[(str, Alias)]\n callbacks = field(default_factory=list)\n callbacks: List[Callback]\n\n def check_condition(self, config: dict) -> bool:\n required_names = [self.root_name] + self.dependencies\n if not config or not all(name in config for name in required_names):\n return False\n else:\n return all(config[name] for name in required_names)\n\n def load_templates(self, config: dict, template_dir: str, output_dir: str) -> Iterator[Tuple[(Template, str)]]:\n spec_root = os.path.join(template_dir, self.root_name)\n loader = Environment(loader=(FileSystemLoader(spec_root)),\n trim_blocks=True,\n lstrip_blocks=True,\n keep_trailing_newline=True)\n for file in get_child_files(spec_root):\n rel_input_path = os.path.relpath(file, spec_root)\n folder_path, filename = os.path.split(rel_input_path)\n for folder_name in self.folder_aliases:\n folder_path = folder_path.replace(folder_name, self.folder_aliases[folder_name].resolve(config))\n\n output_path = os.path.join(output_dir, folder_path, filename)\n template = loader.get_template(rel_input_path)\n yield (template, output_path)","sub_path":"pycfiles/templ8-0.6.17-py3-none-any/models.cpython-36.py","file_name":"models.cpython-36.py","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"274154904","text":"import logging\nfrom logging.handlers import RotatingFileHandler\nimport datetime\nprint(datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S'))\nSTYLE = {\n 'fore':\n { # 前景色\n 'black' : 30, # 黑色\n 'red' : 31, # 红色\n 'green' : 32, # 绿色\n 'yellow' : 33, # 黄色\n 'blue' : 34, # 蓝色\n 'purple' : 35, # 紫红色\n 'cyan' : 36, # 青蓝色\n 'white' : 37, # 白色\n },\n\n 'back' :\n { # 背景\n 'black' : 40, # 黑色\n 'red' : 41, # 红色\n 'green' : 42, # 绿色\n 'yellow' : 43, # 黄色\n 'blue' : 44, # 蓝色\n 'purple' : 45, # 紫红色\n 'cyan' : 46, # 青蓝色\n 'white' : 47, # 白色\n },\n\n 'mode' :\n { # 显示模式\n 'mormal' : 0, # 终端默认设置\n 'bold' : 1, # 高亮显示\n 'underline' : 4, # 使用下划线\n 'blink' : 5, # 闪烁\n 'invert' : 7, # 反白显示\n 'hide' : 8, # 不可见\n },\n\n 'default' :\n {\n 'end' : 0,\n },\n}\n\n\ndef UseStyle(string, mode = '', fore = '', back = ''):\n\n mode = '%s' % STYLE['mode'][mode] if STYLE['mode'].get(mode) else ''\n\n fore = '%s' % STYLE['fore'][fore] if STYLE['fore'].get(fore) else ''\n\n back = '%s' % STYLE['back'][back] if STYLE['back'].get(back) else ''\n\n style = ';'.join([s for s in [mode, fore, back] if s])\n\n style = '\\033[%sm' % style if style else ''\n\n end = '\\033[%sm' % STYLE['default']['end'] if style else ''\n\n return '%s%s%s' % (style, string, end)\n\n\n'''\ndebug:最细微的信息记录到debug中,这个级别就是用来debug的,看程序在哪一次迭代中发生了错误,比如每次循环都输出一些东西用debug级别\ninfo:级别用于routines,也就是输出start finish 状态改变等信息\nwarn:输出一些相对重要,但是不是程序bug的信息,比如输入了错误的密码,或者连接较慢\nerror:输出程序bug,打印异常信息\ncritical:用于处理一些非常糟糕的事情,比如内存溢出、磁盘已满,这个一般较少使用\n'''\nclass Logger:\n def __init__(self,inLevel='DEBUG',inName=__name__):\n self.logger = logging.getLogger(inName)\n self.logger.setLevel(inLevel)\n self.formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n def addHand(self,source):\n self.logger.addHandler(source)\n\n def debug(self, msg):\n self.logger.debug(msg)\n\n def info(self, msg):\n self.logger.info(msg)\n\n def warning(self, msg):\n self.logger.warning(msg)\n\n def error(self, msg):\n self.logger.error(msg)#\n\n def critical(self, msg):\n self.logger.critical(msg)\n\nclass FileLogger(Logger):#log文件输出类\n\n def __init__(self, logName):\n Logger.__init__(self, inLevel='DEBUG', inName=__name__)\n self.loggerName = logName\n self.rHandler = RotatingFileHandler(\"{}_{}.log\".format(self.loggerName,datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')),maxBytes = 1*1024,backupCount = 3,encoding='utf-8')\n self.rHandler.setFormatter(self.formatter)\n self.addHand(self.rHandler)\n\nclass ConsoleLogger(Logger):#控制台输出日志类\n\n def __init__(self):\n Logger.__init__(self, inLevel='DEBUG', inName=__name__)\n self.console = logging.StreamHandler()\n self.console.setFormatter(self.formatter)\n self.addHand(self.console)\n def debug(self, msg):\n self.logger.debug(UseStyle(msg, fore = 'black'))#黑色\n\n def info(self, msg):\n self.logger.info(UseStyle(msg, fore = 'blue'))#蓝色\n\n def warning(self, msg):\n self.logger.warning(UseStyle(msg, fore = 'yellow'))#黄色\n\n def error(self, msg):\n self.logger.error(UseStyle(msg, fore = 'red'))#红色\n\n def critical(self, msg):\n self.logger.critical(UseStyle(msg, fore = 'purple'))#紫红色\n\n\n\nlog = ConsoleLogger()#控制台日志\n#log = FileLogger('songqin_vip_xt')#文件日志\nlog.debug('调试')\nlog.info('信息')\nlog.warning('警告')\nlog.error('错误')\nlog.critical('糟糕')\n","sub_path":"waimaiProject/tools/类继承封装log.py","file_name":"类继承封装log.py","file_ext":"py","file_size_in_byte":4387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"393301174","text":"# -*- coding: utf-8 -*-\nimport utils, os, pandas, numpy, MasterData\nimport excel_template_utils, GLO_from_regional\nfrom copy import copy\n\nbase_folder = r'C:\\Dropbox (ecoinvent)\\ei-int\\technical\\external\\SRI\\data collection\\SRI_refinery\\Technical\\SRI-UPRs 2018-03-19'\nsub_folders = ['Brazil', 'Colombia', 'India', 'Peru', 'South Africa']\ntemplate = {'meta': [], 'exchanges': []}\nocean = .8\ndef correct_PV_amount(x):\n if not utils.is_empty(x):\n x = str(x)\n if 'mt' in x:\n x = float(x.replace(',', '').replace(' mt', ''))*1e9\n x = float(x)\n return x\nrefinery_test = []\nfor sub_folder in sub_folders:\n folder = os.path.join(base_folder, sub_folder)\n filelist = utils.build_file_list(folder, 'xls')\n for filename in filelist:\n f = pandas.read_excel(os.path.join(folder, filename), None)\n f['meta'] = f['meta'][~f['meta']['activityName'].apply(utils.is_empty)]\n \n #correction of typos\n f['meta'] = f['meta'].replace(to_replace = {\n 'activityName': {'petroleum refineryoperation': 'petroleum refinery operation'}, \n 'dataGeneratorAndPublication_personName': {'Axel Liebich': 'Axel Lieblich'}, \n 'dataEntryBy_personName': {'Axel Liebich': 'Axel Lieblich'}, \n })\n \n #setting of a few meta info to default\n f['meta']['dataGeneratorAndPublication_accessRestrictedTo'] = 'Licensees'\n f['meta']['dataGeneratorAndPublication_dataPublishedIn'] = 'The data of some unit processes or subsystems are published'\n f['meta']['fileAttributes_majorRelease'] = 3\n f['meta']['fileAttributes_minorRelease'] = 0\n f['meta']['fileAttributes_majorRevision'] = 1\n f['meta']['fileAttributes_minorRevision'] = 0\n \n #removing geographical activityLinks\n f['exchanges']['activityLink_geography'] = ''\n \n #if the PV amount contains \"mt\", convert to kg\n f['exchanges']['PV_amount'] = f['exchanges']['PV_amount'].apply(correct_PV_amount)\n ref = f['exchanges'][f['exchanges']['group'] == 'ReferenceProduct'].iloc[0]\n ref_ratio = ref['PV_amount']/ref['amount']\n \n #calculation of the PV amount based on amount ratio for byproducts and adding a dummy comment\n for i, sel in f['exchanges'].iterrows():\n if sel['group'] == 'ByProduct':\n f['exchanges'].loc[i, 'PV_amount'] = abs(sel['amount'] * ref_ratio)\n f['exchanges'].loc[i, 'PV_comment'] = 'Production volume was calculated with the reference product production volume and amount, and the byproduct amount.'\n elif sel['group'] == 'ReferenceProduct' and utils.is_empty(sel['PV_comment']):\n f['exchanges'].loc[i, 'PV_comment'] = '(comment mandatory)'\n \n #adding a dummy PV if missing\n if 1:\n ref = list(set(f['exchanges']['reference product']))\n c = (f['exchanges']['group'].isin(['ReferenceProduct', 'ByProduct'])) & (\n f['exchanges']['PV_amount'].apply(utils.is_empty))\n if any(list(c)):\n f['exchanges'].loc[c, 'PV_amount'] = 42.\n if numpy.nan in ref:\n ref.remove(numpy.nan)\n for key in f:\n f[key]['reference product'] = ref[0]\n template[key].append(f[key])\n d = f['exchanges'][f['exchanges']['name'] == 'crude oil']\n d['filename'] = filename\n d['folder'] = sub_folder\n d['product'] = filename.replace('.xls', '').split('_')[2]\n refinery_test.append(d.copy())\n\ndfs = []\nfolder = r'C:\\Dropbox (ecoinvent)\\ei-int\\technical\\external\\SRI\\data collection\\SRI_refinery\\Technical\\conversion'\nfilename = 'mapping.xlsx'\nmapping = utils.read_excel(folder, filename, 'Sheet1')\nprices = mapping[~mapping['price'].apply(utils.is_empty)]\nprices.set_index('name', inplace = True)\nmapping = mapping[mapping['original name'] != mapping['name']]\nmapping.set_index('original name', inplace = True)\ncatalyst = utils.read_excel(folder, filename, 'Catalyst')\ncatalyst = catalyst[catalyst['include']]\ncatalyst['proportion'] = catalyst['proportion']/catalyst['proportion'].sum()\nactivityNames = utils.read_excel(folder, filename, 'activityNames').set_index('reference product')\ndef water_correction(x):\n return x[0] == 'Water' and x[1] == 'air' and x[2] == 'kg'\naggregation_weights = []\nfor key in ['meta', 'exchanges']:\n template[key] = pandas.concat(template[key])\n template[key] = utils.add_empty_columns(template[key], excel_template_utils.columns_for_excel[key])\n if key == 'exchanges':\n #replacement of the catalyst by actual inputs from technosphere\n to_replace = template[key][template[key]['name'] == 'catalysts']\n template[key] = template[key][template[key]['name'] != 'catalysts']\n replaced_catalyst = []\n for i, sel in to_replace.iterrows():\n a = copy(sel['amount'])\n sel = sel.to_dict()\n for j, c in catalyst.iterrows():\n sel['name'] = copy(c['name'])\n sel['amount'] = a*c['proportion']\n replaced_catalyst.append(copy(sel))\n replaced_catalyst = utils.list_to_df(replaced_catalyst)\n \n #some exchanges need to be mapped, using the spreadsheet\n mapped_exchanges = template[key][template[key]['name'].isin(list(mapping.index))]\n template[key] = template[key][~template[key]['name'].isin(list(mapping.index))]\n mapped_exchanges.rename(columns = {'name': 'original name'}, inplace = True)\n mapped_exchanges.set_index('original name', inplace = True)\n del mapped_exchanges['unitName']\n mapped_exchanges = mapped_exchanges.join(mapping[['name', 'conversion', 'unitName']])\n mapped_exchanges['amount'] = mapped_exchanges['amount']*mapped_exchanges['conversion']\n mapped_exchanges['PV_amount'] = mapped_exchanges['PV_amount']*mapped_exchanges['conversion']\n mapped_exchanges.reset_index(inplace = True)\n del mapped_exchanges['conversion'], mapped_exchanges['original name']\n template[key] = pandas.concat([template[key], replaced_catalyst, mapped_exchanges])\n #deleting the refinery sulfur, as hydrogen sulfide exchanges\n template[key] = template[key][template[key]['name'] != 'refinery sulfur, as hydrogen sulfide']\n \n #some water exchanges are in kg, they need to be forced to m3\n c = template[key][['name', 'compartment', 'unitName']].apply(\n water_correction, axis = 1)\n template[key].loc[c, 'amount'] = template[key].loc[c, 'amount'] / 1000.\n template[key].loc[c, 'unitName'] = 'm3'\n del template[key]['activityName']\n template[key] = template[key].set_index('reference product').join(activityNames).reset_index()\n set(template[key][template[key]['activityName'].apply(utils.is_empty)]['reference product'])\n \n #fix some meta data\n if key == 'meta':\n template[key]['dataGeneratorAndPublication_accessRestrictedTo'] = 'Licensees'\n template[key]['technologyLevel'] = 'Current'\n template[key] = template[key].replace(to_replace = {'reference product': dict(zip(\n list(mapping.index), list(mapping['name'])))})\n if key == 'exchanges':\n #many exhanges get mapped to water, so then need to be merged\n c = (template[key]['name'] == 'Water')\n water = template[key][c]\n template[key] = template[key][~c]\n water = pandas.pivot_table(water, values = 'amount', index = ['activityName', 'geography', 'reference product', \n 'group', 'name', 'compartment', 'subcompartment'], aggfunc = numpy.sum).reset_index()\n water['unitName'] = 'm3'\n water['uncertainty type'] = 'lognormal'\n water['variance'] = .04\n water['reliability'] = 3\n water['completeness'] = 2\n water['temporalCorrelation'] = 2\n water['geographicalCorrelation'] = 1\n water['furtherTechnologyCorrelation'] = 2\n template[key] = pandas.concat([template[key], water])\n template[key] = template[key].replace(to_replace = {'uncertainty type': {'unspecified': ''}})\n template[key].index = range(len(template[key]))\n c = list(template[key][template[key]['variance'] == 0.].index)\n template[key].loc[c, ['variance', 'uncertainty type']] = ''\n \n #split water\n c = (template[key]['name'] == 'Water') & (template[key]['compartment'] == 'water')\n water = template[key][c]\n template[key] = template[key][~c]\n water['amount'] = water['amount'] * ocean\n water['subcompartment'] = 'ocean'\n template[key] = pandas.concat([template[key], water.copy()])\n water['amount'] = water['amount'] / ocean * (1.-ocean)\n water['subcompartment'] = 'surface water'\n \n #add to the other dataframes\n template[key] = pandas.concat([template[key], water.copy()])\n \n #merge datasets\n present = []\n template[key].index = range(len(template[key]))\n template[key]['duplicate id'] = ''\n template[key] = utils.replace_empty_in_df(template[key])\n k = ['activityName', 'geography', 'group', 'name', \n 'compartment', 'subcompartment', 'activityLink_activityName', 'activityLink_geography']\n for i in range(len(template[key])):\n v = ''.join(template[key].loc[i, k])\n present.append(v)\n template[key].loc[i, 'duplicate id'] = present.count(v)\n have_duplicates = template[key][template[key]['duplicate id'] == 2]\n have_duplicates = utils.df_value_set(have_duplicates, ['activityName', 'geography'])\n all_datasets = utils.df_value_set(template[key], ['activityName', 'geography'])\n grouped = template[key].groupby(['activityName', 'geography'])\n template[key] = []\n for name, group in grouped:\n if name in have_duplicates:\n ref = group[group['group'] == 'ReferenceProduct'][['duplicate id', 'PV_amount']]\n if ref['PV_amount'].sum() == 0.:\n ref['PV_amount'] = 1.\n ref['weight'] = ref['PV_amount'] / ref['PV_amount'].sum()\n ref['activityName'] = name[0]\n ref['geography'] = name[1]\n aggregation_weights.append(ref)\n ref = ref.set_index('duplicate id')\n d = pandas.pivot_table(group, values = 'amount', index = k, columns = 'duplicate id', \n aggfunc = numpy.sum).reset_index()\n d = d.replace(to_replace = {1: {numpy.nan: 0.}, 2: {numpy.nan: 0.}})\n d['average'] = d[1]*ref.loc[1, 'weight'] + d[2]*ref.loc[2, 'weight']\n d = d.set_index(k)\n group = group.set_index(k)\n group = group[group['duplicate id'] == 1]\n group['amount'] = d['average'].copy()\n group = group.reset_index()\n group.index = range(len(group))\n i = group[group['group'] == 'ReferenceProduct'].index[0]\n group.loc[i, 'PV_amount'] = ref['PV_amount'].sum()\n template[key].append(group)\n template[key] = pandas.concat(template[key])\n if key == 'meta':\n template[key] = template[key].drop_duplicates(['activityName', 'geography'])\n dfs.append((template[key], key, excel_template_utils.columns_for_excel[key]))\nfor tab in ['ElementaryExchanges', 'ElementaryExchanges prop.', 'Persons', \n 'IntermediateExchanges', 'IntermediateExchanges prop.', 'Sources']:\n df = utils.read_excel(folder, filename, tab)\n dfs.append((df, tab, MasterData.excel_columns[tab]))\n if tab == 'Sources':\n sourceId = df.iloc[0]['id']\nds = utils.df_value_set(dfs[0][0], ['activityName', 'geography', 'reference product'])\ndf = []\nfor activityName, geography, ref in ds:\n to_add = dict(zip(excel_template_utils.columns_for_excel['property'], \n ['']*len(excel_template_utils.columns_for_excel['property'])))\n to_add['activityName'] = activityName\n to_add['geography'] = geography\n to_add['amount'] = prices.loc[ref, 'price']\n to_add['group'] = 'ReferenceProduct'\n to_add['name'] = ref\n to_add['propertyName'] = 'price'\n to_add['unitName'] = 'EUR2005'\n to_add['comment'] = 'price comment required'\n to_add['reference product'] = ref\n df.append(copy(to_add))\ndf = utils.list_to_df(df)\ndfs.append((df, 'property', excel_template_utils.columns_for_excel['property']))\nfilename = 'GLO_PV.xlsx'\ndf = utils.read_excel(folder, filename, 'Sheet1')\ndf = utils.add_empty_columns(df, excel_template_utils.columns_for_excel['GLO_PV'])\ndfs.append((df, 'GLO_PV', excel_template_utils.columns_for_excel['GLO_PV']))\naggregation_weights = pandas.concat(aggregation_weights)\ncolumns = ['activityName', 'geography', 'PV_amount', 'weight']\ndfs.append((aggregation_weights, 'aggregation weights', columns))\nrefinery_test = pandas.concat(refinery_test)\ndfs.append((refinery_test, 'petroleum test', ['folder', 'filename', 'product', 'name', 'amount']))\nfilename = 'all.xlsx'\nfor i in range(len(dfs)):\n dfs[i][0]['productInformation'] = ''\nutils.dataframe_to_excel(folder, filename, dfs, feedback = True)\nresult_filename = 'all_with_GLO.xlsx'\nGLO_from_regional.GLO_from_regional(folder, result_filename, \n excel_folder = folder, excel_filename = filename)\ndf = utils.read_excel(folder, result_filename, None)\ndfs = []\nfor tab in df:\n if tab == 'exchanges':\n #add activityLink\n c = (df[tab]['name'] == 'refinery sulfur, as hydrogen sulfide'\n ) & (df[tab]['group'] == 'ByProduct')\n df[tab].loc[c, 'activityLink_activityName'] = 'sulfur production, petroleum refinery operation'\n df[tab].loc[c, 'activityLink_geography'] = df[tab].loc[c, 'geography']\n df[tab].loc[c, 'comment'] = 'This exchange represents a hydrogen sulfide-laden gas produced, for example, in the hydro-desulfurization of refinery naphthas and other petroleum oils. This is considered an intermediate product flow for the recovery of elemental sulfur within the petroleum refinery operation.'\n if tab == 'meta':\n df[tab]['dataGeneratorAndPublication_dataPublishedIn'] = 'The data of some unit processes or subsystems are published'\n df[tab]['dataGeneratorAndPublication_publishedSourceId'] = sourceId\n df[tab]['dataGeneratorAndPublication_personName'] = 'Axel Liebich'\n df[tab]['dataEntryBy_personName'] = 'Axel Liebich'\n if tab in MasterData.excel_columns:\n df[tab] = utils.add_empty_columns(df[tab], MasterData.excel_columns[tab])\n dfs.append((df[tab], tab, MasterData.excel_columns[tab]))\n elif tab in excel_template_utils.columns_for_excel:\n dfs.append((df[tab], tab, excel_template_utils.columns_for_excel[tab]))\nutils.dataframe_to_excel(folder, result_filename, dfs, feedback = True)","sub_path":"projects/refinery/01_combine.py","file_name":"01_combine.py","file_ext":"py","file_size_in_byte":14909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"456914766","text":"#!/usr/bin/env python\n##############################################################################\n#\n# xpdacq by Billinge Group\n# Simon J. L. Billinge sb2896@columbia.edu\n# (c) 2016 trustees of Columbia University in the City of\n# New York.\n# All rights reserved\n#\n# File coded by: Timothy Liu, Simon Billinge, Tom Caswell\n#\n# See AUTHORS.txt for a list of people who contributed.\n# See LICENSE.txt for license information.\n#\n##############################################################################\nimport sys\nimport os\nimport datetime\nimport shutil\nimport yaml\nfrom time import strftime\nfrom xpdacq.utils import _graceful_exit\nfrom xpdacq.beamtime import Beamtime, XPD, Experiment, Sample, ScanPlan\nfrom xpdacq.beamtime import export_data, _clean_md_input, _get_hidden_list\nfrom xpdacq.glbl import glbl\nfrom shutil import ReadError\n\nhome_dir = glbl.home\nall_folders = glbl.allfolders\n\ndef _any_input_method(inp_func):\n return inp_func()\n\ndef _make_clean_env():\n '''Make a clean environment for a new user\n\n 3. look for a __config.yml and load it. Ask the user if\n this is the right one before loading it. If yes, load, if no exit\n telling user to manually delete the yml file stall the correct one in\n dUser directory, if it exists.\n\n 4. ask a series of questions to help set up the environment. Save them\n in the __config.yml file. Create this if it does not\n already exist.\n\n Parameters\n ----------\n datapath : ??\n Base directory to work in\n '''\n out = []\n for d in all_folders:\n os.makedirs(d, exist_ok=True)\n out.append(d)\n return out\n\ndef _end_beamtime(base_dir=None,archive_dir=None,bto=None):\n if archive_dir is None:\n archive_dir = glbl.archive_dir\n if base_dir is None:\n base_dir = glbl.base\n # get bt by loading the yaml.\n if bto is None:\n btoname = os.path.join(glbl.yaml_dir,'bt_bt.yml')\n with open(btoname, 'r') as fi:\n bto = yaml.load(fi)\n files = os.listdir(glbl.home)\n if len(files)==1:\n print('It appears that end_beamtime may have been run. If so, do not run again but proceed to _start_beamtime')\n return\n try:\n piname = bto.md['bt_piLast']\n except AttributeError:\n piname = input('Please enter PI last name for this beamtime: ')\n try:\n safn = bto.md['bt_safN']\n except AttributeError:\n safn = input('Please enter your SAF number to this beamtime: ')\n try:\n btuid = bto.md['bt_uid'][:7]\n except AttributeError:\n btuid = ''\n archive_f = _execute_end_beamtime(piname, safn, btuid, base_dir, archive_dir, bto)\n _confirm_archive(archive_f)\n _delete_home_dir_tree(base_dir,archive_f, bto)\n\ndef _execute_end_beamtime(piname, safn, btuid, base_dir, archive_dir, bto):\n '''cleans up at the end of a beamtime\n\n Function takes all the user-generated tifs and config files, etc.,\n and archives them to a directory in the remote file-store with\n filename B_DIR/useriD\n\n This function does three things:\n\n 1. runs export_data to get all of the current data\n 2. copies the tarball off to an archive location\n 3. removes all the un-tarred data\n\n '''\n tar_ball = export_data(base_dir, end_beamtime=True)\n ext = get_full_ext(tar_ball)\n os.makedirs(archive_dir, exist_ok=True)\n\n full_info = '_'.join([piname.strip().replace(' ', ''),\n str(safn).strip(), strftime('%Y-%m-%d-%H%M'), btuid]\n )\n archive_f_name = os.path.join(archive_dir, full_info) + ext\n shutil.copyfile(tar_ball, archive_f_name) # remote archive'\n return archive_f_name\n\ndef _get_user_confirmation():\n conf = input(\"Please confirm data are backed up. Are you ready to continue with xpdUser directory contents deletion (y,[n])?: \")\n return conf\n\ndef _confirm_archive(archive_f_name):\n print(\"tarball archived to {}\".format(archive_f_name))\n conf = _any_input_method(_get_user_confirmation)\n if conf in ('y','Y'):\n return\n else:\n sys.exit(_graceful_exit('xpdUser directory delete operation cancelled at Users request'))\n\ndef _delete_home_dir_tree(base_dir, archive_f_name, bto):\n #dp = DataPath(base_dir)\n os.chdir(glbl.base) # don't remember the name, but move up one directory out of xpdUser before deleting it!\n shutil.rmtree(glbl.home)\n os.makedirs(glbl.home, exist_ok=True)\n shutil.copy(archive_f_name, glbl.home)\n os.chdir(glbl.home) # now move back into xpdUser so everyone is not confused....\n final_path = os.path.join(glbl.home, os.path.basename(archive_f_name)) # local archive\n #print(\"Final archive file at {}\".format(final_path))\n return 'local copy of tarball for user: '+final_path\n\ndef get_full_ext(path, post_ext=''):\n path, ext = os.path.splitext(path)\n if ext:\n return get_full_ext(path, ext + post_ext)\n return post_ext\n\ndef _check_empty_environment(base_dir=None):\n if base_dir is None:\n base_dir = glbl.base\n if os.path.exists(home_dir):\n if not os.path.isdir(home_dir):\n sys.exit(_graceful_exit(\"Expected a folder, got a file. \"\n \"Please Talk to beamline staff\"))\n files = os.listdir(home_dir) # that also list dirs that have been created\n if len(files) > 1:\n sys.exit(_graceful_exit(\"Unexpected files in {}, you need to run _end_beamtime(). Please Talk to beamline staff\".format(home_dir)))\n elif len(files) == 1:\n tf, = files\n if 'tar' not in tf:\n sys.exit(_graceful_exit(\"Expected a tarball of some sort, found {} \"\n \"Please talk to beamline staff\"\n .format(tf)))\n os.unlink(os.path.join(home_dir, tf))\n else:\n sys.exit(_graceful_exit(\"The xpdUser directory appears not to exist \"\n \"Please Talk to beamline staff\"))\n\ndef _init_dark_yaml():\n dark_scan_list = []\n with open(glbl.dk_yaml, 'w') as f:\n yaml.dump(dark_scan_list, f)\n\ndef _start_beamtime(safn,home_dir=None):\n if home_dir is None:\n home_dir = glbl.home\n if not os.path.exists(home_dir):\n os.makedirs(home_dir)\n _check_empty_environment()\n configfile = os.path.join(glbl.xpdconfig,'saf{}.yml'.format(str(safn)))\n if os.path.isfile(configfile):\n with open(configfile, 'r') as fin:\n setup_dict = yaml.load(fin)\n else:\n sys.exit(_graceful_exit('the saf config file {} appears to be missing'.format(configfile)))\n try:\n piname = setup_dict['PI last name']\n safn = setup_dict['saf number']\n explist = setup_dict['experimenter list']\n except KeyError:\n sys.exit(_graceful_exit('Cannot load input info. File syntax in {} maybe corrupted.'.format(configfile)))\n bt = _execute_start_beamtime(piname, safn, explist, home_dir=home_dir)\n _init_dark_yaml()\n\n return bt\n\ndef _execute_start_beamtime(piname,safn,explist,wavelength=None,home_dir=None):\n PI_name = piname\n saf_num = safn\n _make_clean_env()\n os.chdir(home_dir)\n bt = Beamtime(PI_name,saf_num,experimenters=explist)\n\n # now populate the database with some lazy-user objects\n ex = Experiment('l-user',bt)\n sa = Sample('l-user',ex)\n sc01 = ScanPlan('ct.1s','ct',{'exposure':0.1})\n sc05 = ScanPlan('ct.5s','ct',{'exposure':0.5})\n sc1 = ScanPlan('ct1s','ct',{'exposure':1.0})\n sc5 = ScanPlan('ct5s','ct',{'exposure':5.0})\n sc10 = ScanPlan('ct10s','ct',{'exposure':10.0})\n sc30 = ScanPlan('ct30s','ct',{'exposure':30.0})\n return bt\n\ndef import_yaml():\n '''\n import user pre-defined files from ~/xpdUser/Import\n\n Files can be compreesed or .yml, once imported, bt.list() should show updated acquire object list\n '''\n src_dir = glbl.import_dir\n dst_dir = glbl.yaml_dir\n f_list = os.listdir(src_dir)\n if len(f_list) == 0:\n print('INFO: There is no pre-defined user objects in {}'.format(src_dir))\n return \n # two possibilites: .yml or compressed files; shutil should handle all compressed cases\n moved_f_list = []\n for f in f_list:\n full_path = os.path.join(src_dir, f)\n (root, ext) = os.path.splitext(f)\n if ext == '.yml':\n shutil.copy(full_path, dst_dir)\n moved_f_list.append(f)\n # FIXME - do we want user confirmation?\n os.remove(full_path)\n else:\n try:\n shutil.unpack_archive(full_path, dst_dir)\n moved_f_list.append(f)\n # FIXME - do we want user confirmation?\n os.remove(full_path)\n except ReadError:\n print('Unrecongnized file type {} is found inside {}'.format(f, src_dir))\n pass\n return moved_f_list\n\nif __name__ == '__main__':\n print(glbl.home)\n","sub_path":"xpdacq/beamtimeSetup.py","file_name":"beamtimeSetup.py","file_ext":"py","file_size_in_byte":9034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"398179779","text":"from django import forms\nimport datetime\n\nclass EventForm(forms.Form):\n modulator = forms.FloatField(min_value=1, label=\"Modulator (> 1)\",help_text=\"How much is a price of a product important\", initial=1.2)\n #random_sample_size = forms.IntegerField(label=\"How big random sample of users/products should be (recommended: 200)\")\n random_sample_size = forms.IntegerField(\n label=\"Random Sample Size\", \n help_text=\"For how many random users we should look for recommendations\", initial=200)\n top_n = forms.IntegerField(label=\"Number of emails\", help_text=\"How many most perspective customers you want to sent an emai\", initial=100)\n date_of_event = forms.DateTimeField(label=\"Date of event\", initial=datetime.date.today, help_text=\"Date when mails should be send\" )\n title = forms.CharField(max_length=30, label=\"Title of event\", help_text=\"How the event should be called\", initial=\"Recommendations\")\n subject = forms.CharField(max_length=30, label=\"Subject\", help_text=\"Subject of emails\", initial=\"Recommendations for you!\")\n","sub_path":"event/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"305960078","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Plotting waveforms.\"\"\"\n\n\n#------------------------------------------------------------------------------\n# Imports\n#------------------------------------------------------------------------------\n\nimport numpy as np\n\nfrom vispy import gloo\nfrom vispy.gloo import Texture2D\n\nfrom ._panzoom import PanZoom\nfrom ._vispy_utils import (BaseSpikeVisual,\n BaseSpikeCanvas,\n _enable_depth_mask,\n _wrap_vispy,\n )\nfrom ..utils._types import _as_array\nfrom ..utils._color import _selected_clusters_colors\nfrom ..utils.array import _index_of, _normalize, _unique\nfrom ..electrode.mea import linear_positions\n\n\n#------------------------------------------------------------------------------\n# Waveform visual\n#------------------------------------------------------------------------------\n\nclass WaveformVisual(BaseSpikeVisual):\n \"\"\"Display waveforms with probe geometry.\"\"\"\n\n _shader_name = 'waveforms'\n _gl_draw_mode = 'line_strip'\n\n def __init__(self, **kwargs):\n super(WaveformVisual, self).__init__(**kwargs)\n\n self._waveforms = None\n self.n_channels, self.n_samples = None, None\n self._channel_order = None\n self._channel_positions = None\n\n self.program['u_data_scale'] = (.05, .05)\n self.program['u_channel_scale'] = (1., 1.)\n self.program['u_overlap'] = 0.\n self.program['u_alpha'] = 0.5\n _enable_depth_mask()\n\n # Data properties\n # -------------------------------------------------------------------------\n\n @property\n def waveforms(self):\n \"\"\"Displayed waveforms.\n\n This is a `(n_spikes, n_samples, n_channels)` array.\n\n \"\"\"\n return self._waveforms\n\n @waveforms.setter\n def waveforms(self, value):\n # WARNING: when setting new data, waveforms need to be set first.\n # n_spikes will be set as a function of waveforms.\n value = _as_array(value)\n # TODO: support sparse structures\n assert value.ndim == 3\n self.n_spikes, self.n_samples, self.n_channels = value.shape\n self._waveforms = value\n self._empty = self.n_spikes == 0\n self.set_to_bake('spikes', 'spikes_clusters', 'color')\n\n @property\n def channel_positions(self):\n \"\"\"Positions of the channels.\n\n This is a `(n_channels, 2)` array.\n\n \"\"\"\n return self._channel_positions\n\n @channel_positions.setter\n def channel_positions(self, value):\n value = _as_array(value)\n self._channel_positions = value\n self.set_to_bake('channel_positions')\n\n @property\n def channel_order(self):\n return self._channel_order\n\n @channel_order.setter\n def channel_order(self, value):\n self._channel_order = value\n\n @property\n def alpha(self):\n \"\"\"Alpha transparency (between 0 and 1).\"\"\"\n return self.program['u_alpha']\n\n @alpha.setter\n def alpha(self, value):\n self.program['u_alpha'] = value\n\n @property\n def box_scale(self):\n \"\"\"Scale of the waveforms.\n\n This is a pair of scalars.\n\n \"\"\"\n return tuple(self.program['u_data_scale'])\n\n @box_scale.setter\n def box_scale(self, value):\n assert len(value) == 2\n self.program['u_data_scale'] = value\n\n @property\n def probe_scale(self):\n \"\"\"Scale of the probe.\n\n This is a pair of scalars.\n\n \"\"\"\n return tuple(self.program['u_channel_scale'])\n\n @probe_scale.setter\n def probe_scale(self, value):\n assert len(value) == 2\n self.program['u_channel_scale'] = value\n\n @property\n def overlap(self):\n \"\"\"Whether to overlap waveforms.\"\"\"\n return True if self.program['u_overlap'][0] > .5 else False\n\n @overlap.setter\n def overlap(self, value):\n assert value in (True, False)\n self.program['u_overlap'] = 1. if value else 0.\n\n def channel_hover(self, position):\n \"\"\"Return the channel id closest to the mouse pointer.\n\n Parameters\n ----------\n\n position : tuple\n The normalized coordinates of the mouse pointer, in world\n coordinates (in `[-1, 1]`).\n\n \"\"\"\n mouse_pos = position / self.probe_scale\n # Normalize channel positions.\n positions = self.channel_positions.astype(np.float32)\n positions = _normalize(positions, keep_ratio=True)\n positions = .1 + .8 * positions\n positions = 2 * positions - 1\n # Find closest channel.\n d = np.sum((positions - mouse_pos[None, :]) ** 2, axis=1)\n idx = np.argmin(d)\n # if self.channel_order is not None:\n # channel_id = self.channel_order[idx]\n # WARNING: by convention this is the relative channel index.\n return idx\n\n # Data baking\n # -------------------------------------------------------------------------\n\n def _bake_channel_positions(self):\n # WARNING: channel_positions must be in [0,1] because we have a\n # texture.\n positions = self.channel_positions.astype(np.float32)\n positions = _normalize(positions, keep_ratio=True)\n positions = positions.reshape((1, self.n_channels, -1))\n # Rescale a bit and recenter.\n positions = .1 + .8 * positions\n u_channel_pos = np.dstack((positions,\n np.zeros((1, self.n_channels, 1))))\n u_channel_pos = (u_channel_pos * 255).astype(np.uint8)\n # TODO: more efficient to update the data from an existing texture\n self.program['u_channel_pos'] = Texture2D(u_channel_pos,\n wrapping='clamp_to_edge')\n\n def _bake_spikes(self):\n\n # Bake masks.\n # WARNING: swap channel/time axes in the waveforms array.\n waveforms = np.swapaxes(self._waveforms, 1, 2)\n assert waveforms.shape == (self.n_spikes,\n self.n_channels,\n self.n_samples,\n )\n masks = np.repeat(self._masks.ravel(), self.n_samples)\n data = np.c_[waveforms.ravel(), masks.ravel()].astype(np.float32)\n # TODO: more efficient to update the data from an existing VBO\n self.program['a_data'] = data\n\n # TODO: SparseCSR, this should just be 'channel'\n self._channels_per_spike = np.tile(np.arange(self.n_channels).\n astype(np.float32),\n self.n_spikes)\n\n # TODO: SparseCSR, this should be np.diff(spikes_ptr)\n self._n_channels_per_spike = self.n_channels * np.ones(self.n_spikes,\n dtype=np.int32)\n\n self._n_waveforms = np.sum(self._n_channels_per_spike)\n\n # TODO: precompute this with a maximum number of waveforms?\n a_time = np.tile(np.linspace(-1., 1., self.n_samples),\n self._n_waveforms).astype(np.float32)\n\n self.program['a_time'] = a_time\n self.program['n_channels'] = self.n_channels\n\n def _bake_spikes_clusters(self):\n # WARNING: needs to be called *after* _bake_spikes().\n if not hasattr(self, '_n_channels_per_spike'):\n raise RuntimeError(\"'_bake_spikes()' needs to be called before \"\n \"'bake_spikes_clusters().\")\n # Get the spike cluster indices (between 0 and n_clusters-1).\n spike_clusters_idx = self.spike_clusters\n # We take the cluster order into account here.\n spike_clusters_idx = _index_of(spike_clusters_idx, self.cluster_order)\n # Generate the box attribute.\n assert len(spike_clusters_idx) == len(self._n_channels_per_spike)\n a_cluster = np.repeat(spike_clusters_idx,\n self._n_channels_per_spike * self.n_samples)\n a_channel = np.repeat(self._channels_per_spike, self.n_samples)\n a_box = np.c_[a_cluster, a_channel].astype(np.float32)\n # TODO: more efficient to update the data from an existing VBO\n self.program['a_box'] = a_box\n self.program['n_clusters'] = self.n_clusters\n\n\nclass WaveformView(BaseSpikeCanvas):\n \"\"\"A VisPy canvas displaying waveforms.\"\"\"\n _visual_class = WaveformVisual\n _arrows = ('Left', 'Right', 'Up', 'Down')\n _pm = ('+', '-')\n _events = ('channel_click',)\n _key_pressed = None\n _show_mean = False\n\n def _create_visuals(self):\n super(WaveformView, self)._create_visuals()\n self.mean = WaveformVisual()\n self.mean.alpha = 1.\n\n def _create_pan_zoom(self):\n self._pz = PanZoom()\n self._pz.add(self.visual.program)\n self._pz.add(self.mean.program)\n self._pz.attach(self)\n\n def set_data(self,\n waveforms=None,\n masks=None,\n spike_clusters=None,\n channel_positions=None,\n channel_order=None,\n colors=None,\n **kwargs\n ):\n\n if waveforms is not None:\n assert isinstance(waveforms, np.ndarray)\n if waveforms.ndim == 2:\n waveforms = waveforms[None, ...]\n assert waveforms.ndim == 3\n else:\n waveforms = self.visual.waveforms\n n_spikes, n_samples, n_channels = waveforms.shape\n\n if spike_clusters is None:\n spike_clusters = np.zeros(n_spikes, dtype=np.int32)\n spike_clusters = _as_array(spike_clusters)\n cluster_ids = _unique(spike_clusters)\n n_clusters = len(cluster_ids)\n\n if masks is None:\n masks = np.ones((n_spikes, n_channels), dtype=np.float32)\n\n if colors is None:\n colors = _selected_clusters_colors(n_clusters)\n\n if channel_order is None:\n channel_order = self.visual.channel_order\n if channel_order is None:\n channel_order = np.arange(n_channels)\n\n if channel_positions is None:\n channel_positions = self.visual.channel_positions\n if channel_positions is None:\n channel_positions = linear_positions(n_channels)\n\n self.visual.waveforms = waveforms.astype(np.float32)\n\n if masks is not None:\n self.visual.masks = masks\n\n self.visual.spike_clusters = spike_clusters\n assert spike_clusters.shape == (n_spikes,)\n\n self.visual.cluster_colors = colors\n self.visual.channel_positions = channel_positions\n self.visual.channel_order = channel_order\n\n # Extra parameters.\n for k, v in kwargs.items():\n setattr(self, k, v)\n\n self.update()\n\n @property\n def box_scale(self):\n \"\"\"Scale of the waveforms.\n\n This is a pair of scalars.\n\n \"\"\"\n return self.visual.box_scale\n\n @box_scale.setter\n def box_scale(self, value):\n self.visual.box_scale = value\n self.mean.box_scale = value\n self.update()\n\n @property\n def probe_scale(self):\n \"\"\"Scale of the probe.\n\n This is a pair of scalars.\n\n \"\"\"\n return self.visual.probe_scale\n\n @probe_scale.setter\n def probe_scale(self, value):\n self.visual.probe_scale = value\n self.mean.probe_scale = value\n self.update()\n\n @property\n def alpha(self):\n \"\"\"Opacity.\"\"\"\n return self.visual.alpha\n\n @alpha.setter\n def alpha(self, value):\n self.visual.alpha = value\n self.mean.alpha = value\n self.update()\n\n @property\n def overlap(self):\n \"\"\"Whether to overlap waveforms.\"\"\"\n return self.visual.overlap\n\n @overlap.setter\n def overlap(self, value):\n self.visual.overlap = value\n self.mean.overlap = value\n self.update()\n\n @property\n def show_mean(self):\n \"\"\"Whether to show_mean waveforms.\"\"\"\n return self._show_mean\n\n @show_mean.setter\n def show_mean(self, value):\n self._show_mean = value\n self.update()\n\n keyboard_shortcuts = {\n 'waveform_scale_increase': ('ctrl+',\n 'ctrl+up',\n 'shift+wheel up',\n ),\n 'waveform_scale_decrease': ('ctrl-',\n 'ctrl+down',\n 'shift+wheel down',\n ),\n 'waveform_width_increase': ('ctrl+right', 'ctrl+wheel up'),\n 'waveform_width_decrease': ('ctrl+left', 'ctrl+wheel down'),\n 'probe_width_increase': ('shift+right', 'ctrl+alt+wheel up'),\n 'probe_width_decrease': ('shift+left', 'ctrl+alt+wheel down'),\n 'probe_height_increase': ('shift+up', 'shift+alt+wheel up'),\n 'probe_height_decrease': ('shift+down', 'shift+alt+wheel down'),\n 'select_channel': ('ctrl+left click', 'ctrl+right click', 'num+click'),\n }\n\n def on_key_press(self, event):\n \"\"\"Handle key press events.\"\"\"\n key = event.key\n\n self._key_pressed = key\n\n ctrl = 'Control' in event.modifiers\n shift = 'Shift' in event.modifiers\n\n # Box scale.\n if ctrl and key in self._arrows + self._pm:\n coeff = 1.1\n u, v = self.box_scale\n if key == 'Left':\n self.box_scale = (u / coeff, v)\n elif key == 'Right':\n self.box_scale = (u * coeff, v)\n elif key in ('Down', '-'):\n self.box_scale = (u, v / coeff)\n elif key in ('Up', '+'):\n self.box_scale = (u, v * coeff)\n\n # Probe scale.\n if shift and key in self._arrows:\n coeff = 1.1\n u, v = self.probe_scale\n if key == 'Left':\n self.probe_scale = (u / coeff, v)\n elif key == 'Right':\n self.probe_scale = (u * coeff, v)\n elif key == 'Down':\n self.probe_scale = (u, v / coeff)\n elif key == 'Up':\n self.probe_scale = (u, v * coeff)\n\n def on_key_release(self, event):\n self._key_pressed = None\n\n def on_mouse_wheel(self, event):\n \"\"\"Handle mouse wheel events.\"\"\"\n ctrl = 'Control' in event.modifiers\n shift = 'Shift' in event.modifiers\n alt = 'Alt' in event.modifiers\n coeff = 1. + .1 * event.delta[1]\n\n # Box scale.\n if ctrl and not alt:\n u, v = self.box_scale\n self.box_scale = (u * coeff, v)\n if shift and not alt:\n u, v = self.box_scale\n self.box_scale = (u, v * coeff)\n\n # Probe scale.\n if ctrl and alt:\n u, v = self.probe_scale\n self.probe_scale = (u * coeff, v)\n if shift and alt:\n u, v = self.probe_scale\n self.probe_scale = (u, v * coeff)\n\n def on_mouse_press(self, e):\n key = self._key_pressed\n if 'Control' in e.modifiers or key in map(str, range(10)):\n box_idx = int(key.name) if key in map(str, range(10)) else None\n # Normalise mouse position.\n position = self._pz._normalize(e.pos)\n position[1] = -position[1]\n zoom = self._pz._zoom_aspect()\n pan = self._pz.pan\n mouse_pos = ((position / zoom) - pan)\n # Find the channel id.\n channel_idx = self.visual.channel_hover(mouse_pos)\n self.emit(\"channel_click\",\n channel_idx=channel_idx,\n ax='x' if e.button == 1 else 'y',\n box_idx=box_idx,\n )\n\n def on_draw(self, event):\n \"\"\"Draw the visual.\"\"\"\n gloo.clear(color=True, depth=True)\n if self._show_mean:\n self.mean.draw()\n else:\n self.visual.draw()\n\n\n#------------------------------------------------------------------------------\n# Plotting functions\n#------------------------------------------------------------------------------\n\n@_wrap_vispy\ndef plot_waveforms(waveforms, **kwargs):\n \"\"\"Plot waveforms.\n\n Parameters\n ----------\n\n waveforms : ndarray\n The waveforms to plot. A `(n_spikes, n_samples, n_channels)` array.\n spike_clusters : ndarray (optional)\n A `(n_spikes,)` int array with the spike clusters.\n masks : ndarray (optional)\n A `(n_spikes, n_channels)` float array with the spike masks.\n channel_positions : ndarray\n A `(n_channels, 2)` array with the channel positions.\n\n \"\"\"\n c = WaveformView(keys='interactive')\n c.set_data(waveforms, **kwargs)\n return c\n","sub_path":"phy/plot/waveforms.py","file_name":"waveforms.py","file_ext":"py","file_size_in_byte":16698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"12982045","text":"# !usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Licensed under a 3-clause BSD license.\n#\n# @Author: Brian Cherinka\n# @Date: 2017-08-07 13:28:13\n# @Last modified by: Brian Cherinka\n# @Last Modified time: 2017-08-30 10:52:53\n\nfrom __future__ import print_function, division, absolute_import\nimport pytest\nimport sys\nimport os\n\nSciDrive_Directory = \"SciScriptPython\"\nSciDrive_FileName = \"TestFile.csv\"\nSciDrive_FileContent = \"Column1,Column2\\n4.5,5.5\\n\"\n\n\n@pytest.fixture()\ndef noscidrive(sci):\n responseDelete = sci.delete(SciDrive_Directory)\n assert responseDelete is True\n yield responseDelete\n # delete again after test is done\n responseDelete = sci.delete(SciDrive_Directory)\n\n\n@pytest.fixture()\ndef newfile(tmpdir):\n file = tmpdir.mkdir(SciDrive_Directory).join(SciDrive_FileName)\n file.write(SciDrive_FileContent)\n isfile = file.check(file=1)\n assert isfile is True\n yield file\n\n\n@pytest.mark.usefixtures('token')\nclass TestSciDrive(object):\n\n def test_createContainer_directoryList_delete(self, sci, noscidrive):\n responseCreate = sci.createContainer(SciDrive_Directory)\n assert responseCreate is True\n\n dirList = sci.directoryList(SciDrive_Directory)\n assert dirList[\"path\"].__contains__(SciDrive_Directory) is True\n\n def test_publicUrl(self, sci, noscidrive):\n responseCreate = sci.createContainer(SciDrive_Directory)\n url = sci.publicUrl(SciDrive_Directory)\n isUrl = url.startswith(\"http\")\n assert responseCreate is True\n assert isUrl is True\n\n def test_upload(self, sci, newfile, noscidrive):\n remotepath = os.path.join(SciDrive_Directory, SciDrive_FileName)\n localpath = str(newfile)\n responseUpload = sci.upload(path=remotepath, localFilePath=localpath)\n assert responseUpload is not None\n assert remotepath in responseUpload['path']\n\n @pytest.mark.parametrize('datatype, outformat',\n [('file', 'StringIO'),\n ('data', 'text')])\n def test_download(self, sci, newfile, noscidrive, datatype, outformat):\n # open a file in Python 2 or 3\n\n remotepath = os.path.join(SciDrive_Directory, SciDrive_FileName)\n localpath = str(newfile)\n\n if datatype == 'file':\n responseUpload = sci.upload(path=remotepath, localFilePath=localpath)\n stringio = sci.download(path=remotepath, outformat=outformat)\n data = fileContent = stringio.read()\n elif datatype == 'data':\n responseUpload = sci.upload(path=remotepath, data=SciDrive_FileContent)\n data = sci.download(path=remotepath, outformat=outformat)\n\n assert remotepath in responseUpload[\"path\"]\n assert data == SciDrive_FileContent\n","sub_path":"python/sciserver/tests/test_scidrive.py","file_name":"test_scidrive.py","file_ext":"py","file_size_in_byte":2785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"653780178","text":"\"\"\"\nGiven a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.\n\nDo not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.\n\nThe solution is based on two-finger swapping.\n\"\"\"\nclass Solution:\n def removeDuplicates(self, nums):\n nums_len = len(nums)\n\n if(nums_len < 0):\n return 0\n\n current_indx = 0\n while current_indx < len(nums) - 1:\n if(nums[current_indx] == nums[current_indx + 1]):\n del nums[current_indx + 1]\n else:\n current_indx += 1\n\n return len(nums)\n","sub_path":"Array/RemoveDuplicates.py","file_name":"RemoveDuplicates.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"194110774","text":"# -*- coding: utf-8 -*-\n# Needs suds_jurko\nimport base64\nimport binascii\nimport logging\nimport os\n\nfrom django.utils.encoding import force_text, force_bytes\nfrom suds import WebFault\nfrom suds.client import Client\nfrom suds.plugin import MessagePlugin\n\nfrom .containers import BdocContainer\n\n\nclass DigiDocException(Exception):\n \"\"\" Unknown errors\n \"\"\"\n\n def __init__(self, command, params, *args, **kwargs):\n self.command = command\n self.params = params\n\n super().__init__(*args, **kwargs)\n\n\nclass DigiDocError(Exception):\n \"\"\" Known errors\n \"\"\"\n\n def __init__(self, error_code, *args, **kwargs):\n self.error_code = error_code\n\n super().__init__(*args, **kwargs)\n\n\nclass PreviouslyCreatedContainer(object):\n pass\n\n\nclass DataFile(object):\n def __init__(self, file_name, mimetype, content_type, size, content, info=None):\n self.file_name = file_name\n self.mimetype = mimetype\n self.content_type = content_type or DigiDocService.HASHCODE\n self.size = size\n self.content = content\n\n self.info = info\n\n\nclass SoapFixer(MessagePlugin):\n def marshalled(self, context):\n context.envelope.nsprefixes = {\n 'ns1': \"http://www.sk.ee/DigiDocService/DigiDocService_2_3.wsdl\",\n 'SOAP-ENV': \"http://schemas.xmlsoap.org/soap/envelope/\",\n }\n\n if context.envelope.attributes:\n context.envelope.attributes = list(filter(lambda attr: attr.prefix != 'SOAP-ENV' and attr.name != 'encodingStyle',\n context.envelope.attributes))\n\n context.envelope.walk(self.fix_namespaces)\n\n def fix_namespaces(self, element):\n if element.prefix:\n if element.prefix != 'ns1' and element.prefix[:2] == 'ns':\n element.prefix = 'ns1'\n\n if element.name == 'Header':\n del element\n\n elif element.name == 'Body':\n element.prefix = 'SOAP-ENV'\n\n elif element.attributes:\n element.attributes = list(filter(lambda attr: attr.prefix != 'xsi' and attr.name != 'type', element.attributes))\n\n\nclass DigiDocService(object):\n HOST_TEST = 'TEST'\n HOST_LIVE = 'LIVE'\n\n WSDL_HOSTS = {\n HOST_TEST: \"https://tsp.demo.sk.ee/?wsdl\",\n HOST_LIVE: \"https://www.sk.ee/DigiDocService/DigiDocService_2_3.wsdl\",\n }\n\n RESPONSE_STATUS_OK = \"OK\"\n\n ERROR_CODES = {\n 100: 'Üldine viga.',\n 101: 'Vigased sissetulevad parameetrid.',\n 102: 'Mõned sissetulevad parameetrid on puudu.',\n 103: 'Teenuse omanikul puudub õigus teha päringuid allkirja-kontrolli teenusesse (OCSP: AUTORISEERIMATA)',\n 200: 'Üldine teenuse viga.',\n 201: 'Kasutaja sertifikaat on puudu.',\n 202: 'Sertifikaadi korrektsust polnud võimalik valideerida.',\n 203: 'Sessioon on lukustatud teise SOAPi pärginu poolt.',\n 300: 'Üldine viga seoses kasutaja telefoniga.',\n 301: 'Pole Mobiil-ID kasutaja.',\n 302: 'Sertifikaat ei kehti (OCSP: TAGASI VÕETUD).',\n 303: 'Sertifikaat ei ole aktiveeritud ja/ või selle staatus on teadmata (OCSP: TEADMATA).',\n 304: 'Sertifikaat on peatatud.',\n 305: 'Sertifikaat on aegunud.',\n 413: 'Sissetulev päring ületab teenuse lubatud mahupiiranguid.',\n 503: 'Teenuse üheaegselt esitatud päringute piirang on ületatud.',\n }\n\n MID_STATUS_ERROR_CODES = {\n 'EXPIRED_TRANSACTION': 'MobiilID allkirjastamise ajapiirang sai läbi.',\n 'USER_CANCEL': 'Kasutaja katkestas allkirjastamise.',\n 'NOT_VALID': 'Allkiri ei kehti.',\n 'MID_NOT_READY': 'Mobiil-ID ei ole veel sellel telefonil aktiveeritud. Palun proovige hiljem uuesti.',\n 'PHONE_ABSENT': 'Telefon ei ole kättesaadav.',\n 'SENDING_ERROR': 'Ei suutnud telefonile Mobiil-ID päringut saata.',\n 'SIM_ERROR': 'Telefoni SIM-kaardiga tekkis probleem.',\n 'OCSP_UNAUTHORIZED': 'Mobiil-ID kasutajal ei ole lubatud teha OSCP päringuid.',\n 'INTERNAL_ERROR': 'Serveri viga Mobiil-ID allkirjastamisel.',\n 'REVOKED_CERTIFICATE': 'Allkirjastaja sertifikaat ei kehti.'\n }\n\n LANGUAGE_ET = 'EST'\n LANGUAGE_EN = 'ENG'\n LANGUAGE_RU = 'RUS'\n LANGUAGE_LT = 'LIT'\n\n HASHCODE = 'HASHCODE'\n EMBEDDED_BASE64 = 'EMBEDDED_BASE64'\n\n def __init__(self, service_name, mobile_message='Signing via python', client_type=None, debug=False):\n self.service_name = service_name\n self.mobile_message = mobile_message\n\n self.session_code = None\n self.data_files = []\n self.container = None\n\n if client_type is None:\n client_type = self.HOST_TEST\n\n assert client_type in [self.HOST_TEST, self.HOST_LIVE]\n\n if client_type == self.HOST_TEST:\n assert service_name == 'Testimine'\n\n plugin = SoapFixer()\n self.client = Client(self.WSDL_HOSTS[client_type], xstq=False, prefixes=True, prettyxml=True, plugins=[plugin])\n\n self.debug = debug\n\n def start_session(self, b_hold_session, signing_profile=None, sig_doc_xml=None, datafile=None):\n response = self.__invoke('StartSession', {\n 'bHoldSession': b_hold_session,\n 'SigningProfile': signing_profile,\n 'SigDocXML': sig_doc_xml,\n 'datafile': datafile,\n })\n\n if response['Sesscode']:\n self.data_files = []\n self.session_code = response['Sesscode']\n\n if sig_doc_xml:\n self.container = PreviouslyCreatedContainer()\n\n return True\n\n return False\n\n def mobile_authenticate(self, phone_nr, message=None, language=None):\n if language is None:\n language = self.LANGUAGE_ET\n\n assert language in [self.LANGUAGE_ET, self.LANGUAGE_EN, self.LANGUAGE_RU, self.LANGUAGE_LT]\n\n response = self.__invoke('MobileAuthenticate', {\n 'PhoneNo': phone_nr,\n 'Language': language,\n 'ServiceName': self.service_name,\n 'MessageToDisplay': message or self.mobile_message,\n 'SPChallenge': force_text(binascii.hexlify(os.urandom(10))),\n 'MessagingMode': 'asynchClientServer',\n })\n\n return response\n\n def get_mobile_authenticate_status(self, wait=False):\n response = self.__invoke('GetMobileAuthenticateStatus', {\n 'WaitSignature': 'TRUE' if wait else 'FALSE',\n }, no_raise=True)\n\n return response\n\n def create_signed_document(self, file_format='BDOC'):\n if self.container and isinstance(self.container, PreviouslyCreatedContainer):\n raise DigiDocException('CreateSignedDoc', {}, 'PreviouslyCreatedContainer already in session')\n\n versions = {\n # 'DIGIDOC-XML': '1.3',\n 'BDOC': '2.1',\n }\n containers = {\n 'BDOC': BdocContainer,\n }\n\n assert file_format in versions, 'File format should be one of: %s' % versions.keys()\n\n self.__invoke('CreateSignedDoc', {\n 'Format': file_format,\n 'Version': versions[file_format],\n })\n\n self.container = containers[file_format]\n\n return True\n\n def add_datafile(self, file_name, mimetype, content_type, size, content):\n if self.container and isinstance(self.container, PreviouslyCreatedContainer):\n raise DigiDocException('AddDataFile', {}, 'Cannot add files to PreviouslyCreatedContainer')\n\n assert self.container, 'Must create a signed document before adding files'\n assert content_type in [self.HASHCODE, self.EMBEDDED_BASE64]\n assert content_type == self.HASHCODE, 'Currently only HASHCODE mode works'\n\n digest_type = self.container.DEFAULT_HASH_ALGORITHM\n digest_value = force_text(self.container.hash_code(content))\n\n args = {\n 'FileName': file_name,\n 'MimeType': mimetype,\n 'ContentType': content_type,\n 'Size': size,\n\n 'DigestType': digest_type,\n 'DigestValue': digest_value,\n }\n\n if content_type == self.EMBEDDED_BASE64:\n args['Content'] = base64.b64encode(content)\n\n response = self.__invoke('AddDataFile', args)\n\n info = None\n for file in response['SignedDocInfo']['DataFileInfo']:\n if file['Filename'] == file_name:\n info = file\n break\n\n self.data_files.append(DataFile(file_name, mimetype, content_type, size, content, info))\n\n return self.data_files\n\n def mobile_sign(self, id_code, phone_nr, language=None):\n \"\"\" This can be used to add a signature to existing data files\n\n WARNING: Must have at least one datafile in the session\n \"\"\"\n\n if not (self.container and isinstance(self.container, PreviouslyCreatedContainer)):\n assert self.data_files, 'To use MobileSign endpoint the application must add at least one data file to users session'\n\n if language is None:\n language = self.LANGUAGE_ET\n\n assert language in [self.LANGUAGE_ET, self.LANGUAGE_EN, self.LANGUAGE_RU, self.LANGUAGE_LT]\n\n response = self.__invoke('MobileSign', {\n 'SignerIDCode': id_code,\n 'SignerPhoneNo': phone_nr,\n 'Language': language,\n\n 'ServiceName': self.service_name,\n 'AdditionalDataToBeDisplayed': self.mobile_message,\n\n 'MessagingMode': 'asynchClientServer',\n 'ReturnDocInfo': '',\n 'ReturnDocData': '',\n })\n\n return response\n\n def prepare_signature(self, certificate, token_id, role='', city='', state='', postal_code='', country=''):\n if not (self.container and isinstance(self.container, PreviouslyCreatedContainer)):\n assert self.data_files, 'To use PrepareSignature endpoint the application must add at least one data file to users session'\n\n response = self.__invoke('PrepareSignature', {\n 'SignersCertificate': certificate,\n 'SignersTokenId': token_id,\n 'Role': role,\n 'City': city,\n 'State': state,\n 'PostalCode': postal_code,\n 'Country': country,\n })\n\n if response['Status'] == self.RESPONSE_STATUS_OK:\n return {\n 'id': response['SignatureId'],\n 'digest': response['SignedInfoDigest'],\n }\n\n return None\n\n def finalize_signature(self, signature_id, signature_value):\n response = self.__invoke('FinalizeSignature', {\n 'SignatureId': signature_id,\n 'SignatureValue': signature_value,\n })\n\n return response['Status'] == self.RESPONSE_STATUS_OK\n\n def close_session(self):\n response = self.__invoke('CloseSession')\n\n self.data_files = []\n self.session_code = None\n\n return response\n\n def get_signed_doc(self):\n response = self.__invoke('GetSignedDoc')\n\n if response['Status'] == self.RESPONSE_STATUS_OK:\n return base64.b64decode(force_bytes(response['SignedDocData']))\n\n else:\n return None\n\n def get_signed_doc_info(self):\n response = self.__invoke('GetSignedDocInfo')\n\n return response\n\n def get_status_info(self, wait=False):\n response = self.__invoke('GetStatusInfo', {\n 'ReturnDocInfo': False,\n 'WaitSignature': wait,\n })\n\n return response\n\n def __invoke(self, command, params=None, no_raise=False):\n params = params or {}\n\n if command != 'StartSession':\n params.update({'Sesscode': self.session_code})\n\n try:\n response = getattr(self.client.service, command)(**params)\n if self.debug:\n logging.info('%s:Response: %s', command, response)\n\n if response == self.RESPONSE_STATUS_OK:\n return True\n\n elif response['Status'] == self.RESPONSE_STATUS_OK:\n return response\n\n if no_raise:\n return response\n\n raise Exception(response)\n\n except WebFault as e:\n error_code = e.fault.faultstring\n known_fault = self.ERROR_CODES.get(int(error_code), None)\n\n if self.debug:\n logging.info('Response body [/%s - %s]: %s', command, error_code, e.document.str())\n\n if known_fault is not None:\n raise DigiDocError(error_code, \"Server result [/%s - %s]: %s\" % (command, error_code, known_fault))\n\n else:\n logging.exception('Request to %s with params %s caused an error', command, params)\n raise DigiDocException(command, params, e)\n\n except Exception as e:\n logging.exception('Request to %s with params %s caused an error', command, params)\n\n raise DigiDocException(command, params, e)\n\n def get_file_data(self, the_files):\n # Add all files to memory\n for file in the_files:\n assert isinstance(file, DataFile)\n self.data_files.append(file)\n\n # Get bdoc container from DigidocService\n file_data = self.get_signed_doc()\n\n with self.to_bdoc(file_data) as container:\n file_data = container.data_files_format()\n\n return file_data\n\n def to_bdoc(self, file_data):\n return BdocContainer(file_data, self.data_files)\n","sub_path":"esteid/digidocservice/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":13411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"599922020","text":"#!/usr/bin/env python\n#this script needs 2 inputs [1] fin= host_uniq.tsv & [2] cOff= the cut-off Percentage\n#this gives us a output .tsv file with only those hosts in Patric that are above\n#the cutoff. Super chill!\n\n#now can run the HcheckinP.py script\n\nimport sys\nfin=sys.argv[1] #for ex : host_SelcOff.in.tsv\ncOff=sys.argv[2] #like 70 or 80\nfout=\"host_SelcOff\"+str(cOff)+\".tsv\"\n\nln=[]\nwith open(fin, \"r\") as f:\n for line in f:\n line = line.rstrip()\n words = line.split('\\t')\n genomeID = words[0]\n score = words[1]\n if score >= cOff:\n ln.append(genomeID)\n\nthefile = open(fout, \"w\")\nfor item in ln:\n print>>thefile, item\nthefile.close()\n","sub_path":"PatricHostFound/PMI_host/host_SelcOff.py","file_name":"host_SelcOff.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"372783511","text":"\nimport pandas as pd\nimport time\nimport numpy as np\nimport random\nfrom numpy import *\n#调用分类器\nfrom sklearn.ensemble import RandomForestClassifier\nimport xgboost as xgb \n\nimport lightgbm as lgb\nfrom sklearn import ensemble\n#from GCForest import gcForest\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn import svm\n#import catboost as cb\nfrom keras.models import Sequential, Model,load_model\nfrom keras.layers import LSTM, Dense,Bidirectional,BatchNormalization,Input,Permute,merge,RepeatVector,Lambda\nfrom keras.utils import np_utils,to_categorical\nfrom keras.backend import reshape\nimport keras.backend as K\nfrom keras_self_attention import SeqSelfAttention\n\n\n#评价指标\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import matthews_corrcoef # MCC\nfrom sklearn.metrics import confusion_matrix #混淆矩阵\nfrom sklearn.preprocessing import StandardScaler\n\nfrom sklearn.model_selection import StratifiedKFold\n\nfrom sklearn.model_selection import StratifiedKFold\nimport matplotlib.pyplot as plt\n\n\n\n# 提取测试集,训练集\n\ndef kappa(matrix):\n n = np.sum(matrix)\n sum_po = 0\n sum_pe = 0\n for i in range(len(matrix[0])):\n sum_po += matrix[i][i]\n row = np.sum(matrix[i, :])\n col = np.sum(matrix[:, i])\n sum_pe += row * col\n po = sum_po / n\n pe = sum_pe / (n * n)\n # print(po, pe)\n return (po - pe) / (1 - pe)\n\n\ndef evaluating_indicator(y_true, y_test, y_test_value): #计算预测结果的各项指标\n c_m = confusion_matrix(y_true, y_test)\n TP=c_m[0,0]\n FN=c_m[0,1]\n FP=c_m[1,0]\n TN=c_m[1,1]\n \n TPR=TP/ (TP+ FN) #敏感性\n TNR= TN / (FP + TN) #特异性\n BER=1/2*((FP / (FP + TN) )+FN/(FN+TP))\n \n ACC = accuracy_score(y_true, y_test)\n MCC = matthews_corrcoef(y_true, y_test)\n F1score = f1_score(y_true, y_test)\n AUC = roc_auc_score(y_true,y_test_value[:,1])\n KAPPA=kappa(c_m)\n \n c={\"TPR\" : TPR,\"TNR\" : TNR,\"BER\" : BER\n ,\"ACC\" : ACC,\"MCC\" : MCC,\"F1_score\" : F1score,\"AUC\" : AUC,'KAPPA':KAPPA}\n return c\n\n\ndef blo(pro_comm_Pre,jj): #根据预测概率与最优分类阈值对患者进行生死预测\n blo_Pre=zeros(len(pro_comm_Pre))\n for i in range(len(pro_comm_Pre)):\n blo_Pre[i] = 1\n blo_Pre[(pro_comm_Pre[:,1]>(jj*0.01))]=0\n return blo_Pre\n\n\ndef RUN(para_val): #根据训练集与验证集获取最优分类阈值\n EVA_ACC_TEST=[]\n EVA_AUC_TEST=[]\n EVA_MCC_TEST=[]\n EVA_F1_score_TEST=[]\n EVA_BER_TEST=[]\n EVA_KAPPA_TEST=[]\n EVA_TPR_TEST=[]\n EVA_TNR_TEST=[]\n CUT_OFF=[]\n# tiaocan_train, ceshi_train, tiaocan_train_test, ceshi_true = cross_validation.train_test_split(comtest.iloc[0:len(comtest),1:comtest.shape[1]-1],comtest.iloc[0:len(comtest),-1], test_size = 0.2,random_state = 0) \n position=[];\n skf=StratifiedKFold(n_splits=3) #设置十折交叉验证\n\n comtest = pd.read_csv(\"D:/Work/autokeras_model/new_12h_dropna_lack_lgbm_allcom_sign_result_work.csv\")\n comtest=comtest.dropna()\n comtest = comtest.iloc[:,3:comtest.shape[1]]\n scaler = StandardScaler() #对病例数据进行标准化处理\n comtest.iloc[:,0:comtest.shape[1]-1] = scaler.fit_transform(comtest.iloc[:,0:comtest.shape[1]-1])\n tiaocan_train=np.array(comtest.iloc[:,:comtest.shape[1]-1],dtype=np.float16)\n tiaocan_train_test=np.array(comtest.iloc[:,-1],dtype=np.float16)\n\n comtest_t = pd.read_csv(\"D:/Work/autokeras_model/new_0_12h_dropna_lack_lgbm_allcom_sign_result_work.csv\")\n comtest_t=comtest_t.dropna()\n comtest_t = comtest_t.iloc[:,3:comtest_t.shape[1]]\n scaler = StandardScaler() #对病例数据进行标准化处理\n comtest_t.iloc[:,0:comtest_t.shape[1]-1] = scaler.fit_transform(comtest_t.iloc[:,0:comtest_t.shape[1]-1])\n x_t=np.array(comtest_t.iloc[:,:comtest_t.shape[1]-1],dtype=np.float16)\n y_t=np.array(comtest_t.iloc[:,-1],dtype=np.float16)\n\n para_times=0\n\n for param in para_val:\n para_times+=1\n print('第%s个参数值结果验证, 共 %s 个参数值 '%(para_times ,para_val.shape[0]))\n position=[]\n EVA_ACC_TEST_cv=[]\n EVA_AUC_TEST_cv=[]\n EVA_MCC_TEST_cv=[]\n EVA_F1_score_TEST_cv=[]\n EVA_BER_TEST_cv=[]\n EVA_KAPPA_TEST_cv=[]\n EVA_TPR_TEST_cv=[]\n EVA_TNR_TEST_cv=[]\n CUT_OFF_cv=[]\n times=0\n for train, test in skf.split(tiaocan_train,tiaocan_train_test):\n times+=1\n x_train=tiaocan_train[train]\n y_train=tiaocan_train_test[train]\n x_test=tiaocan_train[test]\n y_true=tiaocan_train_test[test] \n \n # x_train, y_train = RandomUnderSampler().fit_sample(x_train, y_train) #使用欠采样的方法进行类平衡\n data_dim = x_train.shape[1]\n timesteps = 1\n num_classes = 2\n batch_size = 36\n num_cells=190\n epoch=9\n \n ##########################################################################################################################\n\n if batch_size>x_test.shape[0]:\n batch_size=32\n\n x_train=x_train.reshape(-1, timesteps, data_dim)\n x_train=x_train[0:int(x_train.shape[0]/batch_size)*batch_size, :, :] \n y_train=y_train[0:int(y_train.shape[0]/batch_size)*batch_size]\n y_Train = np_utils.to_categorical(y_train, num_classes=num_classes)\n \n x_test=x_test.reshape(-1, timesteps, data_dim)\n x_test=x_test[0:int(x_test.shape[0]/batch_size)*batch_size, :, :] \n y_true=y_true[0:int(y_true.shape[0]/batch_size)*batch_size]\n \n \n##########################################################################################################################\n lgbm = lgb.LGBMClassifier(max_bin = 1200,num_leaves=400,learning_rate =0.002,n_estimators=840,n_jobs=-1,\n reg_alpha=0.56,max_depth=12, min_child_weight=27) \n lgbm.fit(x_train.reshape(-1, data_dim) , y_train) #对机器学习模型进行训练\n# pro_lgbm_Pre = lgbm.predict_proba(x_test.reshape(-1, data_dim) ) \n\n \n########################################### Attention ####################################################### \n model = Sequential()\n model.add(Bidirectional(LSTM(num_cells, return_sequences=True, stateful=True),batch_input_shape=(batch_size, timesteps, data_dim)))\n model.add(BatchNormalization())\n model.add(SeqSelfAttention(attention_activation='sigmoid',name=\"Dense_0\"))\n model.add(Bidirectional(LSTM(int(num_cells*1.5), return_sequences=True, stateful=True)))\n model.add(BatchNormalization())\n model.add(SeqSelfAttention(attention_activation='sigmoid',name=\"Dense_1\"))\n model.add(Bidirectional(LSTM(int(num_cells*0.5), return_sequences=True, stateful=True)))\n model.add(BatchNormalization())\n model.add(SeqSelfAttention(attention_activation='sigmoid',name=\"Dense_2\")) \n model.add(Dense(2, activation='softmax')) \n model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n y_Train=y_Train.reshape(-1, timesteps, num_classes)\n \n model.fit(x_train, y_Train, epochs=epoch, batch_size=batch_size)\n# pro_att_Pre = model.predict_proba(x_test, batch_size=batch_size)\n# pro_att_Pre=pro_att_Pre.reshape(-1,num_classes)\n#################################################################################################################\n\n from sklearn.neural_network import MLPClassifier\n comm = MLPClassifier(solver='lbfgs', alpha=1e-5,hidden_layer_sizes=(4, 1))\n lgbm_train_pre = lgbm.predict_proba(x_train.reshape(-1, data_dim) )\n att_train_pre = model.predict_proba(x_train, batch_size=batch_size); att_train_pre = att_train_pre.reshape(-1,num_classes)\n comm_train=np.hstack((lgbm_train_pre,att_train_pre)); comm_train=comm_train[:,[1,3]]\n comm.fit(comm_train,y_train)\n \n \n lgbm_test_pre = lgbm.predict_proba(x_test.reshape(-1, data_dim) )\n att_test_pre = model.predict_proba(x_test, batch_size=batch_size); att_train_pre = att_test_pre.reshape(-1,num_classes)\n comm_test=np.hstack((lgbm_test_pre,att_train_pre)); comm_test=comm_test[:,[1,3]] \n pro_comm_Pre = comm.predict_proba(comm_test)\n \n##########################################################################################################################\n\n RightIndex=[]\n for jj in range(100): #计算模型在不同分类阈值下的各项指标\n blo_comm_Pre = blo(pro_comm_Pre,jj)\n eva_comm = evaluating_indicator(y_true=y_true, y_test=blo_comm_Pre, y_test_value=pro_comm_Pre)\n RightIndex.append(abs(eva_comm['TPR'] - eva_comm['TNR']))\n RightIndex=np.array(RightIndex,dtype=np.float16)\n position=np.argmin(RightIndex) #选择出使得敏感性特异性最小的阈值作为分类阈值输出\n position=position.mean()\n CUT_OFF_cv.append(position)\n blo_comm_Pre = blo(pro_comm_Pre,position)\n eva_comm = evaluating_indicator(y_true=y_true, y_test=blo_comm_Pre, y_test_value=pro_comm_Pre)\n \n EVA_ACC_TEST_cv.append(eva_comm['ACC'])\n EVA_AUC_TEST_cv.append(eva_comm['AUC'])\n EVA_MCC_TEST_cv.append(eva_comm['MCC'])\n EVA_F1_score_TEST_cv.append(eva_comm['F1_score'])\n EVA_BER_TEST_cv.append(eva_comm['BER'])\n EVA_KAPPA_TEST_cv.append(eva_comm['KAPPA'])\n EVA_TPR_TEST_cv.append(eva_comm['TPR'])\n EVA_TNR_TEST_cv.append(eva_comm['TNR'])\n \n \n# pro_comm_Pre = model.predict_proba(x_train, batch_size=batch_size)\n# blo_comm_Pre = blo(pro_comm_Pre,position)\n# eva_comm = evaluating_indicator(y_true=y_train, y_test=blo_comm_Pre, y_test_value=pro_comm_Pre)\n# EVA_ACC_TRAIN_cv.append(eva_comm['ACC'])\n# EVA_AUC_TRAIN_cv.append(eva_comm['AUC'])\n# EVA_MCC_TRAIN_cv.append(eva_comm['MCC'])\n# EVA_F1_score_TRAIN_cv.append(eva_comm['F1_score'])\n# EVA_BER_TRAIN_cv.append(eva_comm['BER'])\n# EVA_KAPPA_TRAIN_cv.append(eva_comm['KAPPA'])\n# EVA_TPR_TRAIN_cv.append(eva_comm['TPR'])\n# EVA_TNR_TRAIN_cv.append(eva_comm['TNR'])\n# alltime_end=time.time()\n# print('第%s个参数值结果验证, 共 %s 个参数值. done , 第%s次交叉验证 , time: %s s '%(para_times ,para_val.shape[0],times ,alltime_end-alltime_start))\n## print(' done , 第%s次验证 , time: %s s '%(times ,alltime_end-alltime_start)) \n# \n EVA_ACC_TEST.append(np.array(EVA_ACC_TEST_cv).mean())\n EVA_AUC_TEST.append(np.array(EVA_AUC_TEST_cv).mean())\n EVA_MCC_TEST.append(np.array(EVA_MCC_TEST_cv).mean())\n EVA_F1_score_TEST.append(np.array(EVA_F1_score_TEST_cv).mean())\n EVA_BER_TEST.append(np.array(EVA_BER_TEST_cv).mean())\n EVA_KAPPA_TEST.append(np.array(EVA_KAPPA_TEST_cv).mean()) \n EVA_TPR_TEST.append(np.array(EVA_TPR_TEST_cv).mean()) \n EVA_TNR_TEST.append(np.array(EVA_TNR_TEST_cv).mean()) \n CUT_OFF.append(np.array(CUT_OFF_cv).mean()) \n# C_TRAIN={\"TPR\" : EVA_TPR_TRAIN,\"TNR\" : EVA_TNR_TRAIN,\"BER\" : EVA_BER_TRAIN,\"ACC\" : EVA_ACC_TRAIN,\"MCC\" : EVA_MCC_TRAIN,\"F1_score\" : EVA_F1_score_TRAIN,\"AUC\" : EVA_AUC_TRAIN,'KAPPA':EVA_KAPPA_TRAIN,'CUT_OFF':CUT_OFF}\n C_TEST={\"TPR\" : EVA_TPR_TEST,\"TNR\" : EVA_TNR_TEST,\"BER\" : EVA_BER_TEST,\"ACC\" : EVA_ACC_TEST,\"MCC\" : EVA_MCC_TEST,\"F1_score\" : EVA_F1_score_TEST,\"AUC\" : EVA_AUC_TEST,'KAPPA':EVA_KAPPA_TEST,'CUT_OFF':CUT_OFF}\n\n\n tiaocan_train=tiaocan_train.reshape(-1, timesteps, tiaocan_train.shape[1])\n tiaocan_train=tiaocan_train[0:int(tiaocan_train.shape[0]/batch_size)*batch_size, :, :] \n tiaocan_train_test=tiaocan_train_test[0:int(tiaocan_train_test.shape[0]/batch_size)*batch_size]\n y_Train = np_utils.to_categorical(tiaocan_train_test, num_classes=num_classes)\n y_Train=y_Train.reshape(-1, timesteps, num_classes)\n \n lgbm.fit(tiaocan_train.reshape(-1, data_dim),tiaocan_train_test)\n model.fit(tiaocan_train, y_Train, epochs=epoch, batch_size=batch_size)\n \n x_t=x_t.reshape(-1, timesteps, x_t.shape[1])\n x_t=x_test[0:int(x_t.shape[0]/batch_size)*batch_size, :, :] \n y_t=y_true[0:int(y_t.shape[0]/batch_size)*batch_size]\n \n \n lgbm_train_pre = lgbm.predict_proba(tiaocan_train.reshape(-1, data_dim) )\n att_train_pre = model.predict_proba(tiaocan_train, batch_size=batch_size); att_train_pre = att_train_pre.reshape(-1,num_classes)\n comm_train=[]\n comm_train=np.hstack((lgbm_train_pre,att_train_pre)); comm_train=comm_train[:,[1,3]]\n comm.fit(comm_train,tiaocan_train_test)\n \n \n lgbm_test_pre = lgbm.predict_proba(x_t.reshape(-1, data_dim) )\n att_test_pre = model.predict_proba(x_t, batch_size=batch_size); att_train_pre = att_test_pre.reshape(-1,num_classes)\n comm_test=np.hstack((lgbm_test_pre,att_train_pre)); comm_test=comm_test[:,[1,3]] \n pro_comm_Pre = comm.predict_proba(comm_test) \n \n blo_comm_Pre = blo(pro_comm_Pre,5)\n eva_comm = evaluating_indicator(y_true=y_t, y_test=blo_comm_Pre, y_test_value=pro_comm_Pre) \n \n \n\n\n\n\n\n######################################################################################\n return C_TEST,eva_comm\n #计算交叉验证输出的多个阈值的平均值作为最优分类阈值\n\npara_val=np.array([1])\n#para_val=para_val/1000\nC_train,C_test = RUN(para_val)\n\n#TEST_STA='AUC'\n#plt.plot(para_val,C_TRAIN[TEST_STA],'o-',color = 'r',label = 'training')\n#plt.plot(para_val,C_TEST[TEST_STA],'o-',color = 'g',label = 'testing')\n#\n#plt.xlabel('para_val')\n#plt.ylabel(TEST_STA)\n#plt.show()\n#\n#print(np.array(C_TRAIN['TPR'])-np.array(C_TRAIN['TNR']))\n#print(np.array(C_TEST['TPR'])-np.array(C_TEST['TNR']))\n#print(C_TRAIN['CUT_OFF'])\n\n\n","sub_path":"pre_code/Model_fusion.py","file_name":"Model_fusion.py","file_ext":"py","file_size_in_byte":14557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"243448706","text":"\"\"\"\r\nKindly install these libraries before executing this code:\r\n 1. numpy\r\n 2. matplotlib\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport math\r\nimport matplotlib.pyplot as plt\r\nfrom functools import reduce\r\nimport operator as op\r\nimport time\r\n\r\n\r\n# if using a Jupyter notebook, kindly uncomment the following line:\r\n# %matplotlib inline\r\n\r\n\r\ndef nCr(n, r):\r\n r = min(r, n-r)\r\n numer = reduce(op.mul, range(n, n-r, -1), 1)\r\n denom = reduce(op.mul, range(1, r+1), 1)\r\n return numer // denom \r\n \r\n\r\ndef plot_fixed(x, y, x_axis, y_axis, title):\r\n plt.plot(x, y)\r\n plt.xlabel(x_axis)\r\n plt.ylabel(y_axis) \r\n plt.title(title)\r\n plt.show()\r\n\r\n\r\n# returns True if arbitrage opportunity exists\r\ndef arbitrage_condition(u, d, r, t):\r\n if d < math.exp(r*t) and math.exp(r*t) < u:\r\n return False\r\n else:\r\n return True\r\n\r\n\r\ndef compute_option_price(i, S0, u, d, M):\r\n path = format(i, 'b').zfill(M)\r\n curr_max = S0\r\n\r\n for idx in path:\r\n if idx == '1':\r\n S0 *= d\r\n else:\r\n S0 *= u\r\n \r\n return S0\r\n\r\n\r\ndef binomial_method_efficient(S0, K, T, M, r, sigma, display):\r\n curr_time = time.time()\r\n t = T/M\r\n u = math.exp(sigma*math.sqrt(t) + (r - 0.5*sigma*sigma)*t)\r\n d = math.exp(-sigma*math.sqrt(t) + (r - 0.5*sigma*sigma)*t)\r\n\r\n R = math.exp(r*t)\r\n p = (R - d)/(u - d);\r\n\r\n result = arbitrage_condition(u, d, r, t)\r\n if result:\r\n if display == 1:\r\n print(\"Arbitrage Opportunity exists for M = {}\".format(M))\r\n return\r\n else:\r\n if display == 1:\r\n print(\"No arbitrage exists for M = {}\".format(M))\r\n\r\n C = [[0 for i in range(M + 1)] for j in range(M + 1)]\r\n\r\n for i in range(0, M + 1):\r\n C[M][i] = max(0, S0*math.pow(u, M - i)*math.pow(d, i) - K)\r\n\r\n for j in range(M - 1, -1, -1):\r\n for i in range(0, j + 1):\r\n C[j][i] = (p*C[j + 1][i] + (1 - p)*C[j + 1][i + 1]) / R;\r\n \r\n if display == 1: \r\n print(\"European Call Option \\t\\t= {}\".format(C[0][0]))\r\n print(\"Execution Time \\t\\t\\t= {} sec\\n\".format(time.time() - curr_time))\r\n\r\n if display == 2:\r\n for i in range(M + 1):\r\n print(\"At t = {}\".format(i))\r\n for j in range(i + 1):\r\n print(\"Index no = {}\\tPrice = {}\".format(j, C[i][j]))\r\n print()\r\n \r\n return C[0][0]\r\n\r\n\r\ndef binomial_method_most_efficient(S0, K, T, M, r, sigma, display):\r\n curr_time = time.time()\r\n u, d = 0, 0\r\n t = T/M\r\n\r\n u = math.exp(sigma*math.sqrt(t) + (r - 0.5*sigma*sigma)*t)\r\n d = math.exp(-sigma*math.sqrt(t) + (r - 0.5*sigma*sigma)*t) \r\n\r\n R = math.exp(r*t)\r\n p = (R - d)/(u - d);\r\n result = arbitrage_condition(u, d, r, t)\r\n\r\n if result:\r\n if display == 1:\r\n print(\"Arbitrage Opportunity exists for M = {}\".format(M))\r\n return 0, 0\r\n else:\r\n if display == 1:\r\n print(\"No arbitrage exists for M = {}\".format(M))\r\n\r\n option_price = 0\r\n for j in range(0, M + 1):\r\n option_price += nCr(M, j) * math.pow(p, j) * math.pow(1 - p, M - j) * max(S0 * math.pow(u, j) * math.pow(d, M - j) - K, 0)\r\n \r\n option_price /= math.pow(R, M)\r\n\r\n\r\n if display == 1: \r\n print(\"European Call Option \\t\\t= {}\".format(option_price))\r\n print(\"Execution Time \\t\\t\\t= {} sec\\n\".format(time.time() - curr_time))\r\n\r\n\r\n return option_price\r\n\r\n\r\ndef binomial_method_unoptimised(S0, K, T, M, r, sigma, display):\r\n curr_time = time.time()\r\n \r\n u, d = 0, 0\r\n t = T/M\r\n u = math.exp(sigma*math.sqrt(t) + (r - 0.5*sigma*sigma)*t)\r\n d = math.exp(-sigma*math.sqrt(t) + (r - 0.5*sigma*sigma)*t) \r\n\r\n R = math.exp(r*t)\r\n p = (R - d)/(u - d);\r\n result = arbitrage_condition(u, d, r, t)\r\n\r\n if result:\r\n if display == 1:\r\n print(\"Arbitrage Opportunity exists for M = {}\".format(M))\r\n return 0, 0\r\n else:\r\n if display == 1:\r\n print(\"No arbitrage exists for M = {}\".format(M))\r\n\r\n option_price = []\r\n for i in range(0, M + 1):\r\n D = []\r\n for j in range(int(pow(2, i))):\r\n D.append(0)\r\n option_price.append(D)\r\n \r\n for i in range(int(pow(2, M))):\r\n req_price = compute_option_price(i, S0, u, d, M)\r\n option_price[M][i] = max(req_price - K, 0)\r\n \r\n for j in range(M - 1, -1, -1):\r\n for i in range(0, int(pow(2, j))):\r\n option_price[j][i] = (p*option_price[j + 1][2*i] + (1 - p)*option_price[j + 1][2*i + 1]) / R;\r\n\r\n if display == 1: \r\n print(\"European Call Option \\t\\t= {}\".format(option_price[0][0]))\r\n print(\"Execution Time \\t\\t\\t= {} sec\\n\".format(time.time() - curr_time))\r\n \r\n return option_price[0][0]\r\n\r\n\r\ndef main():\r\n # sub-part (a)\r\n print(\"----------------------- sub-part(a) -----------------------\\n\")\r\n M1 = [5, 10, 25]\r\n M2 = [5, 10, 25, 50]\r\n prices1, prices2, prices3 = [], [], []\r\n \r\n print('###################### Unoptimised Binomial Algorithm executing ######################')\r\n for m in M1:\r\n prices1.append(binomial_method_unoptimised(S0 = 100, T = 1, K = 100, M = m, r = 0.08, sigma = 0.20, display = 1))\r\n\r\n\r\n print('\\n\\n###################### Efficient Binomial Algorithm executing (Markov Based) ######################')\r\n for m in M2:\r\n prices2.append(binomial_method_efficient(S0 = 100, T = 1, K = 100, M = m, r = 0.08, sigma = 0.20, display = 1))\r\n\r\n\r\n print('\\n\\n###################### Most Efficient Binomial Algorithm executing (Markov Based) ######################')\r\n for m in M2:\r\n prices3.append(binomial_method_most_efficient(S0 = 100, T = 1, K = 100, M = m, r = 0.08, sigma = 0.20, display = 1))\r\n\r\n\r\n # sub-part (b)\r\n print(\"\\n\\n----------------------- sub-part(b) -----------------------\")\r\n plot_fixed(M2, prices2, \"M\", \"Initial Option Prices\", \"Initial Option Prices vs M\")\r\n M = [i for i in range(1, 21)]\r\n prices1.clear()\r\n for m in M:\r\n prices1.append(binomial_method_most_efficient(S0 = 100, T = 1, K = 100, M = m, r = 0.08, sigma = 0.20, display = 0))\r\n\r\n plot_fixed(M, prices1, \"M\", \"Initial Option Prices\", \"Initial Option Prices vs M (Variation with more data-points for M)\")\r\n\r\n\r\n # sub-part (c)\r\n print(\"\\n\\n----------------------- sub-part(c) -----------------------\")\r\n binomial_method_efficient(S0 = 100, T = 1, K = 100, M = 5, r = 0.08, sigma = 0.20, display = 2)\r\n\r\n\r\nif __name__==\"__main__\":\r\n main()","sub_path":"Lab 3/Submission Files/180123053_VishishtPriyadarshi_q3.py","file_name":"180123053_VishishtPriyadarshi_q3.py","file_ext":"py","file_size_in_byte":6129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"640745000","text":"import requests\nfrom bs4 import BeautifulSoup\n\n# get company info - Recruit subject, Name, Location\n\npages = [\n'https://kr.indeed.com/data-scientist%EC%A7%81-%EC%B7%A8%EC%97%85-%EC%84%9C%EC%9A%B8%ED%8A%B9%EB%B3%84%EC%8B%9C-%EC%A7%80%EC%97%AD',\n'https://kr.indeed.com/jobs?q=data+scientist&l=%EC%84%9C%EC%9A%B8%ED%8A%B9%EB%B3%84%EC%8B%9C&start=10',\n'https://kr.indeed.com/jobs?q=data+scientist&l=%EC%84%9C%EC%9A%B8%ED%8A%B9%EB%B3%84%EC%8B%9C&start=20',\n'https://kr.indeed.com/jobs?q=data+scientist&l=%EC%84%9C%EC%9A%B8%ED%8A%B9%EB%B3%84%EC%8B%9C&start=30']\n\nfor pIdx, page in enumerate(pages, 1):\n url = page\n link = requests.get(url)\n soup = BeautifulSoup(link.text, 'html.parser')\n elems = soup.select('.resultContent')\n print(f\"Company Number {len(elems)} of Page {pIdx}\")\n for elem in elems:\n Jobtitle = elem.find('h2' , class_= 'jobTitle').text.strip()\n CompanyName = elem.find('span' , class_= 'companyName').text.strip()\n CompanyLocation = elem.find('div' , class_= 'companyLocation').text.strip()\n\n if None in (Jobtitle, CompanyName, CompanyLocation):\n print()\n print(\"# -------------- FOund Missing data !! ------------- #\")\n print()\n continue\n\n print(f\"Page : {pIdx} \")\n print(f\"Jobtitle: {Jobtitle} , CompanyName : {CompanyName}, CompanyLocation : {CompanyLocation}\")\n print()\n\n# get company reviews\nurl = 'https://kr.indeed.com/cmp/Lg-Electronics/reviews' # reviewers link\nlink = requests.get(url)\nsoup = BeautifulSoup(link.text, 'html.parser')\ntitles = soup.find_all('div' , 'css-r0sr81 e37uo190')\nreviews = soup.find_all('span', 'css-1cxc9zk e1wnkr790')\nreviews = reviews[1:]\n\nfor t, r in zip(titles, reviews):\n title = t.find('span', class_='css-82l4gy eu4oa1w0')\n review = r.find_all('span', 'css-82l4gy eu4oa1w0')\n\n if None in (title, review):\n print(\"# ----------------------------------- #\")\n print(\"# ----- Missing data is found ------- # \")\n print(\"# ----------------------------------- #\")\n continue\n\n print(\"Title : \", title.text.strip())\n print()\n print(\"Review :\", end='\\n\\n')\n for k in review:\n print(k.getText())\n\n print(\"# -------------- #\")\n print()\n print()\n","sub_path":"DataScience/LAB 2/crawling_indeed.py","file_name":"crawling_indeed.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"331093671","text":"#use Flask and Mongo to begin creating\n#Robin's web app\n\n#import dependencies\nfrom flask import Flask, render_template\nfrom flask_pymongo import PyMongo\nimport scraping\n\napp = Flask(__name__)\n\n# Use flask_pymongo to set up mongo connection\napp.config[\"MONGO_URI\"] = \"mongodb://localhost:27017/mars_app\"\nmongo = PyMongo(app)\n\n#Define our route\n@app.route(\"/\")\ndef index():\n mars = mongo.db.mars.find_one()\n return render_template(\"index.html\", mars=mars)\n\n#add next route and function to our code\n#this is the button of the web application\n#the \"scraping\" button\n@app.route(\"/scrape\")\ndef scrape():\n mars = mongo.db.mars\n mars_data = scraping.scrape_all()\n mars.update({}, mars_data, upsert=True)\n return \"Scraping Successful!\"\n\n#tell Flask to run\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"283949905","text":"\n# @Title: 下一个排列 (Next Permutation)\n# @Author: 18015528893\n# @Date: 2021-02-18 11:59:22\n# @Runtime: 40 ms\n# @Memory: 14.7 MB\n\nclass Solution:\n def nextPermutation(self, nums: List[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n n = len(nums)\n if n < 2:\n return\n\n i = n - 2\n j = n - 1\n while i >= 0 and nums[i] >= nums[j]:\n i -= 1\n j -= 1\n\n if i >= 0:\n for k in range(n-1, j-1, -1):\n if nums[k] > nums[i]:\n nums[k], nums[i] = nums[i], nums[k]\n break\n\n nums[j:n] = nums[j:n][::-1]\n\n\n\n","sub_path":"Problemset/next-permutation/next-permutation.py","file_name":"next-permutation.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"500232516","text":"## File: ds4ua-assignment-5-solns.py\n## Topic: Assignment 5 Solutions\n## Name: David Smith\n## Section Time: 5:00-6:15\n## Grading Group: 5\n\n\nimport pandas as pd\n\nfood = pd.read_csv('fastfood2.csv', index_col=0) # Read in the fast food data as\n# a DataFrame\n\n## 1a.\n\nlunch = food.loc[food['meal'] == 'Lunch'] # Get the meals that were for lunch\nlunch_ct = len(lunch) # Count the meals that were for lunch\nall_ct = len(food) # Count the total number of meals\nlunch_prop = lunch_ct / all_ct # Calculate the proportion of meals that were for lunch\nprint('The proportion of meals that were for lunch is %f' % lunch_prop)\n\n\"\"\"\n# 1a\nThe proportion of meals that were for lunch is 0.516522\n\"\"\"\n\n## 1b.\n\nweek_gp = food['secs'].groupby(food['dayofweek']) # Group the time data by day of the week\nweek_gp.mean() # Calculate and print the mean amount of time for each day of the week\n\n\"\"\"\n# 1b\ndayofweek\nFri 216.234941\nMon 216.774747\nThur 216.605129\nTues 215.742300\nWed 216.282449\nName: secs, dtype: float64\n\"\"\"\n\n## 1c.\n\n# Function that returns a 95% confidence interval for the proportion of drink only\n# orders for DataFrame x\ndef confint(x):\n drink = x.loc[x['drinkonly'] == 'Yes'] # Get the drink only orders\n drink_ct = len(drink) # Count the drink only orders\n meal_ct = len(x) # Count all of the orders in x\n p_hat = drink_ct / meal_ct # Get the proportion of drink only orders\n upper = p_hat + 1.96*((p_hat*(1-p_hat)/meal_ct)**0.5) # Calculate the upper bound\n # of the CI\n lower = p_hat - 1.96*((p_hat*(1-p_hat)/meal_ct)**0.5) # Calculate the lower bound\n # of the CI\n return \"(\" + str(lower) + \", \" + str(upper) + \")\" # Return the confidence interval\n # as a string\n\nmeals = food.groupby(food['meal']) # Group the data by meal type\nmeals.apply(confint) # Calculate and return the confidence interval for each of the\n# three meal types\n\n\"\"\"\n# 1c\nmeal\nBreakfast (0.2211740665675427, 0.23613394334162327)\nDinner (0.12730476118757109, 0.1342341232723899)\nLunch (0.12675719458238568, 0.13254281893086697)\ndtype: object\n# There is definitely is strong difference for breakfast, with breakfast orders\n# being much likelier to be drink only. Lunch and dinner orders have roughly the\n# same chance of being drink only.\n\"\"\"\n\n## 1d.\n\ncost_gp = food['cost'].groupby(food['meal']) # Group the cost data by meal type\ncost_gp.mean() # Calculate and print the mean cost for each meal type\n\n\"\"\"\n# 1d\nmeal\nBreakfast 292.079191\nDinner 502.017676\nLunch 372.363622\nName: cost, dtype: float64\n\"\"\"\n\n## 1e.\n\n# Function that returns the proportion of breakfast orders for a DataFrame x\ndef breakfast(x):\n bf = x.loc[x['meal'] == 'Breakfast'] # Get the breakfast orders\n bf_ct = len(bf) # Count the breakfast orders\n day_ct = len(x) # Count the total number of orders in x\n prop = bf_ct / day_ct # Get the proportion of breakfast orders\n return \"The prop. of breakfast orders is \" + str(prop) # Return the proportion\n # as a string\n\n# Function that returns the proportion of lunch orders for a DataFrame x\ndef lunch(x):\n lun = x.loc[x['meal'] == 'Lunch'] # Get the lunch orders\n lun_ct = len(lun) # Count the lunch orders\n day_ct = len(x) # Count the total number of orders in x\n prop = lun_ct / day_ct # Get the proportion of lunch orders\n return \"The prop. of lunch orders is \" + str(prop) # Return the proportion as\n # a string\n\n# Function that returns the proportion of dinner orders for a DataFrame x\ndef dinner(x):\n din = x.loc[x['meal'] == 'Dinner'] # Get the dinner orders\n din_ct = len(din) # Count the dinner orders\n day_ct = len(x) # Count the total number of orders in x\n prop = din_ct / day_ct # Get the proportion of dinner orders\n return \"The prop. of dinner orders is \" + str(prop) # Return the proportion as\n # a string\n\nmealprop_gp = food.groupby(food['dayofweek']) # Group the data by day of the week\nmealprop_gp.apply(breakfast) # Calculate and print the proportion of breakfast orders\n# for each day of the week\nmealprop_gp.apply(lunch) # Calculate and print the proportion of lunch orders for each\n# day of the week\nmealprop_gp.apply(dinner) # Calculate and print the proportion of dinner orders for\n# each day of the week\n\n\"\"\"\n# 1e\ndayofweek\nFri The prop. of breakfast orders is 0.12141828474...\nMon The prop. of breakfast orders is 0.12016464987...\nThur The prop. of breakfast orders is 0.12245411113...\nTues The prop. of breakfast orders is 0.11983757551...\nWed The prop. of breakfast orders is 0.11990154711...\ndtype: object\n\ndayofweek\nFri The prop. of lunch orders is 0.5200377414709242\nMon The prop. of lunch orders is 0.5155723070819281\nThur The prop. of lunch orders is 0.5160673874779985\nTues The prop. of lunch orders is 0.516440526889175\nWed The prop. of lunch orders is 0.5144665461121157\ndtype: object\n\ndayofweek\nFri The prop. of dinner orders is 0.35854397377960967\nMon The prop. of dinner orders is 0.36426304304701446\nThur The prop. of dinner orders is 0.36147850138295196\nTues The prop. of dinner orders is 0.36372189759334456\nWed The prop. of dinner orders is 0.36563190677114726\ndtype: object\n\"\"\"\n\n## 1f.\n\navetime_means = food['secs'].groupby(food.index).mean() # Get the average fill time\n# for each of the 892 stores\nmean_all = avetime_means.mean() # Get the mean of the averages of all the stores\nstd_all = avetime_means.std(ddof=1) # Get the sample standard deviation of the averages\nupper_bound = mean_all + 2*std_all # Get the low-performing cutoff point\nlower_bound = mean_all - 2*std_all # Get the high-performing cutoff point\nprint('The high-performing stores are:')\navetime_means.loc[avetime_means.values <= lower_bound] # Find and print all of the\n# high-performing stores\nprint('The low-performing stores are:')\navetime_means.loc[avetime_means.values >= upper_bound] # Find and print all of the\n# low-performing stores\n\n\"\"\"\n# 1f\nThe high-performing stores are:\nstorenum\n27 184.487179\n43 188.419643\n53 188.631148\n122 180.400000\n201 185.615385\n243 173.637931\n312 187.411765\n500 187.403509\n511 175.470000\n514 184.151786\n550 180.363636\n570 183.800000\n651 186.946429\n699 186.082192\n722 188.973451\n852 189.460674\n859 187.463158\nName: secs, dtype: float64\n\nThe low-performing stores are:\nstorenum\n30 247.413534\n47 245.446809\n59 244.228571\n128 247.854167\n149 254.926316\n154 247.103774\n155 244.339130\n231 255.208696\n233 245.375000\n281 249.500000\n318 245.991453\n387 248.477064\n392 245.058252\n402 246.212598\n422 254.519231\n452 243.153846\n474 243.724771\n528 250.406250\n614 243.913793\n621 250.213592\n657 264.463918\n718 248.175000\n723 248.692308\n725 245.333333\n726 244.935780\n887 250.571429\nName: secs, dtype: float64\n\"\"\"\n\n## 1g.\n\navetime_med = food['secs'].groupby(food.index).median() # Get the median fill time\n# for each of the 892 stores\nmed_all = avetime_med.mean() # Get the mean of the medians of all the stores\nstd_med = avetime_med.std(ddof=1) # Get the sample standard deviation of all the medians\nupper_bd = med_all + 2*std_med # Get the low-performing cutoff point\nlower_bd = med_all - 2*std_med # Get the high-perofrming cutoff point\nhigh_perf = avetime_med.loc[avetime_med.values <= lower_bd] # Get the high-performing\n# stores according to the medians\nlow_perf = avetime_med.loc[avetime_med.values >= upper_bd] # Get the low-performing\n# stores accordinfg to the medians\nhigh = [] # Create a list to hold the high-performing stores in both methods\n# Loop through the high-performing stores from both methods, if they match and are\n# thus in both lists, add those stores to the combined list\nfor x in high_perf.index:\n for y in avetime_means.loc[avetime_means.values <= lower_bound].index:\n if x == y:\n high.append(y)\nlow = [] # Create a list to hold the low-performing stores in both methods\n# Loop through the low-performing stores from both methods, if they match and are\n# thus in both lists, add those stores to the combined list\nfor x in low_perf.index:\n for y in avetime_means.loc[avetime_means.values >= upper_bound].index:\n if x == y:\n low.append(y)\nprint('The stores in both high-performing groups are:')\nprint(list(high)) # Print the list of high-performing stores in both methods\nprint('The stores in both low-performing groups are:')\nprint(list(low)) # Print the list of low-performing stores in both methods\n\n\"\"\"\n# 1g\nThe stores in both high-performing groups are:\n[27, 243, 312, 722]\nThe stores in both low-performing groups are:\n[59, 149, 233, 318, 402, 452, 528, 657, 718, 723, 725, 726, 887]\n\"\"\"\n\nfood2 = pd.read_csv('fastfood3.csv', index_col=0) # Read in the fast food data as\n# a DataFrame\n\n## 2a.\n\nhighest = food2.loc[food2['satisfaction'] == 10] # Get the orders with the highest\n# possible rating\nhighest_ct = len(highest) # Count the customers that gave the highest possible rating\nlowest = food2.loc[food2['satisfaction'] == 1] # Get the orders with the lowest\n# possible rating\nlowest_ct = len(lowest) # Count the customers that gave the lowest possible rating\nall_ct = len(food2) # Count the total number of customers\nhighest_perc = 100 * (highest_ct/all_ct) # Get the percentage of customers that\n# gave the highest possible rating\nlowest_perc = 100 * (lowest_ct/all_ct) # Get the percentage of customers that gave\n# the lowest possible rating\nprint('%f percent of customers gave the highest possible satisfaction rating.' % highest_perc)\nprint('%f percent of customers gave the lowest possible satisfaction rating.' % lowest_perc) \n\n\"\"\"\n# 2a\n0.129627 percent of customers gave the highest possible satisfaction rating.\n0.004986 percent of customers gave the lowest possible satisfaction rating.\n\"\"\"\n\n## 2b.\n\nsatis_gp = food2['satisfaction'].groupby(food2['dayofweek']) # Group the satisfaction\n# ratings by day of the week\nsatis_gp.mean() # Calculate and print the mean satisfaction for each day of the week\n\n\"\"\"\n# 2b\ndayofweek\nFri 6.116154\nMon 6.132017\nThur 6.118582\nTues 6.142121\nWed 6.141752\nName: satisfaction, dtype: float64\n\"\"\"\n\n## 2c.\n\n# Function that returns a 95% confidence interval for the proportion of satisfied\n# customers for a DataFrame x\ndef conf(x):\n satis = x.loc[x['satisfaction'] >= 7] # Get the satisfied customers\n satis_ct = len(satis) # Count the satisfied customers\n meal_ct = len(x) # Count the total number of customers\n p_hat = satis_ct / meal_ct # Calculate the proportion of satisifed customers\n upper = p_hat + 1.96*((p_hat*(1-p_hat)/meal_ct)**0.5) # Get the upper bound for\n # the CI\n lower = p_hat - 1.96*((p_hat*(1-p_hat)/meal_ct)**0.5) # Get the lower bound for\n # the CI\n return \"(\" + str(lower) + \", \" + str(upper) + \")\" # Return the CI as a string\n\nsatisfied_gp = food2.groupby(food2['meal']) # Group the data by meal type\nsatisfied_gp.apply(conf) # Find and print the confidence interval for each meal type\n\n\"\"\"\n# 2c\nmeal\nBreakfast (0.5439933589067114, 0.5617044115309435)\nDinner (0.4330352502477782, 0.443232721272688)\nLunch (0.35876723189754983, 0.3670488720386676)\ndtype: object\n\"\"\"\n\n## 2d.\n\nquick_satis = food2.loc[(food2['secs'] <= 180) & (food2['satisfaction'] >= 7)]\n# Get the orders that took no more than 180 seconds and satified their customers\nquick_satis_ct = len(quick_satis) # Count these orders\nquick = food2.loc[food2['secs'] <= 180] # Get the orders that took no more than 180\n# seconds\nquick_ct = len(quick) # Count the orders that took no more than 180 seconds\np_hat = quick_satis_ct / quick_ct # Get the proportion of satisfied customers among\n# orders that took no more than 180 seconds\nupper = p_hat + 1.96*((p_hat*(1-p_hat)/quick_ct)**0.5) # Get the upper bound of the CI\nlower = p_hat - 1.96*((p_hat*(1-p_hat)/quick_ct)**0.5) # Get the lower bound of the CI\nlong_satis = food2.loc[(food2['secs'] >= 360) & (food2['satisfaction'] >= 7)]\n# Get the orders that took at least 360 seconds and satified their customers\nlong_satis_ct = len(long_satis) # Count these orders\nlong = food2.loc[food2['secs'] >= 360] # Get the orders that took at least 360 seconds\nlong_ct = len(long) # Count the orders that took at least 360 seconds\np_hat2 = long_satis_ct / long_ct # Get the proportion of satisfied customers among\n# orders that took at least 360 seconds\nupper2 = p_hat2 + 1.96*((p_hat2*(1-p_hat2)/long_ct)**0.5) # Get the upper bound of\n# the CI\nlower2 = p_hat2 - 1.96*((p_hat2*(1-p_hat2)/long_ct)**0.5) # Get the lower bound of\n# the CI\nprint('The CI for quick orders is (%f, %f).' % (lower, upper))\nprint('The CI for long orders is (%f, %f).' % (lower2, upper2))\n\n\"\"\"\n# 2d\nThe CI for quick orders is (0.532175, 0.540387).\nThe CI for long orders is (0.102436, 0.111396).\n\"\"\"\n\n## 2e.\n\n# Function that returns 1 if the order is breakfast, and 0 otherwise\ndef bf(x):\n if x == 'Breakfast':\n return(1)\n else:\n return(0)\n \nbf_ind = food2['meal'].apply(bf) # Get a series of 1s and 0s corresponding to orders\n# that were breakfast or not, respectively\nfood2['predsatis'] = 4 + 0.002*food2['cost'] - 0.005*food2['secs'] + bf_ind\n# Create a column called 'predsatis', and fill it with the result of the formula\n# for each order\nmean_pred = food2['predsatis'].mean() # Calculate the mean predicted satisfaction rating\nprint('The mean predicted rating is %f.' % mean_pred)\n\n\"\"\"\n# 2e\nThe mean predicted rating is 3.858513.\n\"\"\"\n\n## 2f.\n\ndiff = food2['satisfaction'] - food2['predsatis'] # Find the difference between\n# the actual satisfaction rating and the predicted rating\ndiff = diff.abs() # Get the absolute value of this difference\nmax_diff = diff.max() # Find the maximum difference\nmin_diff = diff.min() # Find the minimum difference\nave_diff = diff.mean() # Find the average difference\nprint('The maximum difference is %f.' % max_diff)\nprint('The minimum difference is %f.' % min_diff)\nprint('The average difference is %f.' % ave_diff)\n\n\"\"\"\n# 2f\nThe maximum difference is 4.896000.\nThe minimum difference is 0.000000.\nThe average difference is 2.272899.\n\"\"\"","sub_path":"ds4ua-assignment-5-solns.py","file_name":"ds4ua-assignment-5-solns.py","file_ext":"py","file_size_in_byte":14119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"519603608","text":"#Learn Tkinter in 20 minutes\n#https://www.youtube.com/watch?v=_lSNIrR1nZU\n\nfrom tkinter import * \n\n#key down function\ndef click():\n entered_text = text_entry.get() #this will collect the text from the next entry box\n output.delete(0.0, END)#0.0 means everthing before the first character\n try:\n definition = comp_dictionary[entered_text]\n except:\n definition = \"Sorry there is no word like that please try again\"\n output.insert(END, definition)\n\n#exit function\ndef close_window():\n window.destroy()\n exit()\n### main:\nwindow = Tk()\nwindow.title(\"My computer Science Glossary\")\nwindow.configure(background=\"black\")\n## My photo\nphoto1 = PhotoImage(file=\"working_with_xml/images.gif\")\nLabel(window, image=photo1, bg = \"black\").grid(row=0, column=0, sticky=W)\n#Create label\nLabel(window, text=\"Enter the word you would like a definition for: \", bg=\"black\", fg=\"white\", font=\"none 12 bold\").grid(row=1, column=0, sticky=W)\n#create a text entry box\ntext_entry = Entry(window, width=20, bg=\"white\")\ntext_entry.grid(row=2, column=0, sticky=W)\n#add a submit button\nButton(window, text=\"SUBMIT\", width=6, command=click).grid(row=3, column=0, sticky=W) #Command calls a function click()\n#create another label\nLabel(window, text=\"\\nDefinition:\", bg=\"black\", fg=\"white\", font=\"none 12 bold\").grid(row=4, column=0, sticky=W)\n#create a text box\noutput = Text(window, width=75, height=6, wrap=WORD, background=\"white\")\noutput.grid(row=5, column=0, columnspan=2, sticky=W)\n#the dictionary\ncomp_dictionary = {\n 'algorithm': 'Step by step instructions to complete a task', 'bug': 'Piece of code that causes a program to fail'\n}\n#exit label\nLabel(window, text=\"Click to exit:\", bg=\"black\", fg=\"white\", font=\"none 12 bold\").grid(row=6, column=0, sticky=W)\n#exit button\nButton(window, text=\"EXIT\", width=14, command=close_window).grid(row=7, column=0, sticky=W) #Command calls a function click()\n### run the main loop\nwindow.mainloop()","sub_path":"working_with_xml/graphical_panel.py","file_name":"graphical_panel.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"223442606","text":"import datetime\n\nfrom django.shortcuts import render\nfrom django.views.generic import ListView\nfrom django.views.decorators.http import require_POST\nfrom django.http.response import JsonResponse\nfrom django.core.exceptions import ValidationError, SuspiciousOperation\nfrom django.contrib.auth.models import User\n\nfrom .models import TimeOffRequest\nfrom apps.organizations.views import OrganizationOwnedRequired, UserProfileRequiredMixin\nfrom apps.ui.models import UserProfile\n\n\nclass TimeOffRequestListingBaseMixin(object):\n model = TimeOffRequest\n\n def get_queryset(self):\n return TimeOffRequest.objects.filter(organization=self.request.user.userprofile.organization)\n\n\ndef list_of_employees(request):\n # FIXME move to core app module, also has a ref in shifts/views.py ~106\n ups = UserProfile.objects.filter(organization=request.user.userprofile.organization)\n employees = []\n for user in ups:\n if user.user.first_name:\n name = user.user.first_name + ' ' + (user.user.last_name[0] if user.user.last_name else '')\n employees.append({\n 'name': name,\n 'id': user.user.pk\n })\n else:\n # fall back to using their username if no first_name in profile\n # FIXME: we need to require first_name for all accounts and remove this code\n employees.append({\n 'name': user.user.username,\n 'id': user.user.pk\n })\n return employees\n\n\nclass TimeOffRequestListing(UserProfileRequiredMixin, TimeOffRequestListingBaseMixin, ListView):\n template_name = 'availability/requests.html'\n\n def get_context_data(self, **kwargs):\n context = super(TimeOffRequestListing, self).get_context_data(**kwargs)\n context['users'] = list_of_employees(request=self.request)\n context['admin_or_manager'] = str(True if self.request.user.userprofile.admin_or_manager else False)\n if self.request.user.userprofile.admin_or_manager:\n context['pending'] = TimeOffRequest.objects.filter(organization=self.request.user.userprofile.organization,\n status='P', start_date__gte=datetime.datetime.now().date())\n context['approved'] = TimeOffRequest.objects.filter(organization=self.request.user.userprofile.organization,\n status='A', start_date__gte=datetime.datetime.now().date())\n return context\n\n def get_queryset(self):\n qs = super(TimeOffRequestListing, self).get_queryset()\n return qs.filter(user=self.request.user, start_date__gte=datetime.datetime.now().date()).order_by('start_date')\n\n\n@require_POST\ndef submit_time_off_request(request):\n try:\n year, month, day = request.POST['start_date'].split('-')\n start_date = datetime.date(int(year), int(month), int(day))\n eyear, emonth, eday = request.POST['end_date'].split('-')\n end_date = datetime.date(int(eyear), int(emonth), int(eday))\n user = request.POST['user']\n note = request.POST.get('note', '')\n\n except ValueError:\n return JsonResponse({\"result\": \"invalid data\"}, status=400)\n\n # if not admin or manager, request must be for the user him or herself\n if not request.user.userprofile.admin_or_manager and request.user.pk != user:\n raise SuspiciousOperation\n\n time_off_request = TimeOffRequest(\n organization=request.user.userprofile.organization,\n start_date=start_date,\n end_date=end_date,\n user=User.objects.get(pk=user),\n request_note=note\n )\n\n try:\n time_off_request.clean()\n time_off_request.save()\n return JsonResponse({\"result\": \"ok\"})\n except ValidationError as e:\n return JsonResponse({\"result\": e.__str__()}, status=422)\n\n@require_POST\ndef cancel_time_off_request(request):\n time_off_request = request.POST['request_pk']\n time_off_request = TimeOffRequest.objects.get(pk=time_off_request)\n if not request.user.userprofile.admin_or_manager and time_off_request.user != request.user:\n raise SuspiciousOperation\n else:\n time_off_request.cancel_away()\n return JsonResponse({\"result\": \"ok\"})\n\n@require_POST\ndef approve_time_off_request(request):\n time_off_request = request.POST['request_pk']\n time_off_request = TimeOffRequest.objects.get(pk=time_off_request)\n # must be admin or manager\n if not request.user.userprofile.admin_or_manager:\n raise SuspiciousOperation\n else:\n time_off_request.approve()\n return JsonResponse({\"result\": \"ok\"})\n\n@require_POST\ndef reject_time_off_request(request):\n time_off_request = request.POST['request_pk']\n time_off_request = TimeOffRequest.objects.get(pk=time_off_request)\n # must be admin or manager\n if not request.user.userprofile.admin_or_manager:\n raise SuspiciousOperation\n else:\n time_off_request.reject()\n return JsonResponse({\"result\": \"ok\"})","sub_path":"apps/availability/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"335060743","text":"#encoding:utf-8\r\n\r\nfrom multiprocessing import Process\r\nfrom redis import StrictRedis\r\nredis = StrictRedis(host='170.106.3.212', port=6378, db=0,password='prado999')\r\n\r\nfrom calc_data import clean_data\r\nfrom calc_1_need_to_change import need_change_price_sale,need_change_price_buy\r\nfrom calc_2_need_top import need_top_sale,need_top_buy\r\nfrom calc_3_need_lose import need_lose_sale,need_lose_buy\r\nfrom calc_4_need_add import need_add_sale,need_add_buy\r\nfrom calc_5_redis_rw_init import get_coins_key,get_coins_agreement,get_coins_Z,get_coins_Y,get_coins_onOff,set_coins_activeLights,get_coins_onOff_activeLights_count,get_coins_ignore\r\nfrom calc_7_redis_auto_calc import auto_change_buy,auto_change_sale\r\n\r\n\r\n\r\ndef keep_four(a):\r\n a=(float(a))\r\n return float('%.4f' % a)\r\n\r\n\r\ndef return_data_sale(base_data):\r\n\r\n XQ = eval(redis.get(\"XQ\"))\r\n X = XQ[\"X\"]\r\n Q = XQ[\"Q\"]\r\n\r\n #base_data=eval(redis.blpop('get_data_sale_list')[1])\r\n\r\n links_value=base_data[1]\r\n CoinType = base_data[0]\r\n CoinKey = get_coins_key(CoinType)\r\n\r\n ignore = get_coins_ignore(CoinType, \"sale\")\r\n\r\n convert_links_value=clean_data(links_value,ignore,\"sale\")\r\n\r\n\r\n Y = get_coins_Y(\"BTC\")\r\n Z = get_coins_Z(CoinType)\r\n min_price=float(X)*float(Y)*float(Z)\r\n\r\n onOff=get_coins_onOff(CoinType,\"sale\")\r\n agreement = get_coins_agreement(CoinType,\"sale\")\r\n\r\n#需上架=needadd 要顶:needpush\r\n if onOff:\r\n needChangePrice=need_change_price_sale(CoinType,convert_links_value,min_price)\r\n needPush=need_top_sale(CoinType,convert_links_value,min_price,agreement)\r\n willLose=need_lose_sale(convert_links_value,min_price)\r\n needadd=need_add_sale(convert_links_value)\r\n if needChangePrice or needPush or willLose or needadd:\r\n set_coins_activeLights(CoinType, \"sale\", True)\r\n else:\r\n set_coins_activeLights(CoinType, \"sale\", False)\r\n else:\r\n needChangePrice = False\r\n needPush = False\r\n willLose = False\r\n needadd=False\r\n\r\n p = Process(target=auto_change_sale, args=(willLose,needChangePrice,needPush,CoinType,convert_links_value,min_price))\r\n p.start()\r\n\r\n\r\n sale={\r\n \"coins\":{\r\n CoinType:{\r\n \"tradeHistory\":convert_links_value,\r\n \"needPush\":needPush,\r\n \"needChangePrice\":needChangePrice,\r\n \"needAdd\":needadd,\r\n \"willLose\":willLose,\r\n \"basePirce\":keep_four(min_price),\r\n \"name\":CoinType,\r\n \"type\":\"sale\",\r\n \"onOff\":CoinKey[\"sale\"][\"onOff\"],\r\n \"autoChangePrice\": CoinKey[\"sale\"][\"autoChangePrice\"],\r\n \"ignore\":CoinKey[\"sale\"][\"ignore\"]\r\n }\r\n },\r\n \"activeLights\": get_coins_onOff_activeLights_count(\"sale\")[0],\r\n \"closedLights\": get_coins_onOff_activeLights_count(\"sale\")[1]\r\n }\r\n return sale\r\n\r\n\r\ndef return_data_buy(base_data):\r\n\r\n XQ = eval(redis.get(\"XQ\"))\r\n X = XQ[\"X\"]\r\n Q = XQ[\"Q\"]\r\n\r\n\r\n links_value=base_data[1]\r\n CoinType = base_data[0]\r\n CoinKey=get_coins_key(CoinType)\r\n\r\n ignore=get_coins_ignore(CoinType, \"buy\")\r\n convert_links_value=clean_data(links_value,ignore,\"buy\")\r\n\r\n Y = get_coins_Y(\"BTC\")\r\n Z = get_coins_Z(CoinType)\r\n max_price = float(X) * float(Y) * float(Z) * float(Q)/100\r\n agreement = get_coins_agreement(CoinType, \"buy\")\r\n\r\n onOff = get_coins_onOff(CoinType, \"buy\")\r\n\r\n if onOff:\r\n needChangePrice = need_change_price_buy(CoinType, convert_links_value, max_price)\r\n needPush = need_top_buy(CoinType, convert_links_value, max_price, agreement)\r\n willLose = need_lose_buy(convert_links_value, max_price)\r\n needadd=need_add_buy(convert_links_value)\r\n if needChangePrice or needPush or willLose or needadd:\r\n set_coins_activeLights(CoinType, \"buy\", True)\r\n else:\r\n set_coins_activeLights(CoinType, \"buy\", False)\r\n else:\r\n needChangePrice = False\r\n needPush = False\r\n willLose = False\r\n needadd=False\r\n p = Process(target=auto_change_buy,\r\n args=(willLose, needChangePrice, needPush, CoinType, convert_links_value, max_price))\r\n p.start()\r\n\r\n buy={\r\n \"coins\":{\r\n CoinType:{\r\n \"tradeHistory\":convert_links_value,\r\n \"needPush\":needPush,\r\n \"needChangePrice\":needChangePrice,\r\n \"needAdd\":needadd,\r\n \"willLose\":willLose,\r\n \"basePirce\":keep_four(max_price),\r\n \"name\":CoinType,\r\n \"type\":\"buy\",\r\n \"onOff\":CoinKey[\"buy\"][\"onOff\"],\r\n \"autoChangePrice\": CoinKey[\"buy\"][\"autoChangePrice\"],\r\n \"ignore\":CoinKey[\"buy\"][\"ignore\"]\r\n }\r\n },\r\n \"activeLights\": get_coins_onOff_activeLights_count(\"buy\")[0],\r\n \"closedLights\": get_coins_onOff_activeLights_count(\"buy\")[1]\r\n\r\n }\r\n return buy","sub_path":"calc_6_redis_pre_calc.py","file_name":"calc_6_redis_pre_calc.py","file_ext":"py","file_size_in_byte":5153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"183188765","text":"# Fibonacci\n# Alexander Fraser\n# 8 February 2020\n\n# This program outputs all Fibonacci numbers up to the \n# integer specified by the user.\n\nimport Python_002_Primes as prime_script\n\ndef compute_fibonacci(limit_value):\n fib_list = [1]\n \n a = 0\n b = 1\n\n for _ in range(0, limit_value - 1):\n c = a + b\n a = b\n b = c\n \n fib_list.append(c)\n\n return fib_list\n\ndef main():\n print(\"This program will output all Fibonacci numbers up to the limit specified.\")\n limit_value = prime_script.collect_stop_value()\n fib_list = compute_fibonacci(limit_value)\n print(fib_list)\n\nif __name__ == \"__main__\":\n main()","sub_path":"Python_003_Fibonacci.py","file_name":"Python_003_Fibonacci.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"640278223","text":"# 给你一个二进制字符串数组 strs 和两个整数 m 和 n 。 \n# \n# \n# 请你找出并返回 strs 的最大子集的大小,该子集中 最多 有 m 个 0 和 n 个 1 。 \n# \n# 如果 x 的所有元素也是 y 的元素,集合 x 是集合 y 的 子集 。 \n# \n# \n# \n# \n# 示例 1: \n# \n# \n# 输入:strs = [\"10\", \"0001\", \"111001\", \"1\", \"0\"], m = 5, n = 3\n# 输出:4\n# 解释:最多有 5 个 0 和 3 个 1 的最大子集是 {\"10\",\"0001\",\"1\",\"0\"} ,因此答案是 4 。\n# 其他满足题意但较小的子集包括 {\"0001\",\"1\"} 和 {\"10\",\"1\",\"0\"} 。{\"111001\"} 不满足题意,因为它含 4 个 1 ,大于 \n# n 的值 3 。\n# \n# \n# 示例 2: \n# \n# \n# 输入:strs = [\"10\", \"0\", \"1\"], m = 1, n = 1\n# 输出:2\n# 解释:最大的子集是 {\"0\", \"1\"} ,所以答案是 2 。\n# \n# \n# \n# \n# 提示: \n# \n# \n# 1 <= strs.length <= 600 \n# 1 <= strs[i].length <= 100 \n# strs[i] 仅由 '0' 和 '1' 组成 \n# 1 <= m, n <= 100 \n# \n# Related Topics 动态规划 \n# 👍 359 👎 0\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution:\n def findMaxForm(self, strs: List[str], m: int, n: int) -> int:\n def get_0_1(str_i):\n ans = 0\n for c in str_i:\n if c == '0':\n ans += 1\n return [ans, len(str_i) - ans]\n\n len_s = len(strs)\n strs_tmp = [get_0_1(tmp_str) for tmp_str in strs]\n dp = [[[0 for k in range(n + 1)] for j in range(m + 1)] for i in range(len_s + 1)]\n for i in range(1, len_s + 1):\n for j in range(m + 1):\n for k in range(n + 1):\n dp[i][j][k] = dp[i - 1][j][k]\n if j >= strs_tmp[i - 1][0] and k >= strs_tmp[i - 1][1]:\n dp[i][j][k] = max(dp[i][j][k], 1 + dp[i - 1][j - strs_tmp[i - 1][0]][k - strs_tmp[i - 1][1]])\n return dp[len_s][m][n]\n\n\n# leetcode submit region end(Prohibit modification and deletion)\n\n# strs = [\"10\", \"1\", \"0\"]\n# m = 1\n# n = 1\n#\n#\n# def get_0_1(str_i):\n# ans = 0\n# for c in str_i:\n# if c == '0':\n# ans += 1\n# return [ans, len(str_i) - ans]\n#\n#\n# len_s = len(strs)\n# strs_tmp = [get_0_1(tmp_str) for tmp_str in strs]\n# dp = [[[0 for k in range(n + 1)] for j in range(m + 1)] for i in range(len_s + 1)]\n# for i in range(1, len_s + 1):\n# for j in range(m + 1):\n# for k in range(n + 1):\n# dp[i][j][k] = dp[i - 1][j][k]\n# if j >= strs_tmp[i - 1][0] and k >= strs_tmp[i - 1][1]:\n# dp[i][j][k] = max(dp[i][j][k], 1 + dp[i - 1][j - strs_tmp[i - 1][0]][k - strs_tmp[i - 1][1]])\n# print(dp[len_s][m][n])\n","sub_path":"[474]一和零.py","file_name":"[474]一和零.py","file_ext":"py","file_size_in_byte":2675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"87291892","text":"#Uses python3\nimport sys\nimport math\nfrom queue import PriorityQueue\n\ndef getDis(p1, p2):\n x1, y1 = p1\n x2, y2 = p2\n return math.sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2))\n\ndef closestPoint(v, spacePoints, visited, distance, Qi):\n origin = spacePoints[v]\n for i in range (len(spacePoints)):\n dis = getDis(origin, spacePoints[i])\n if dis < distance[i] and visited[i] == False:\n distance[i] = dis\n Qi.put((dis ,i))\n\n\ndef minimum_distance(spacePoints):\n Qi = PriorityQueue()\n visited = list(False for _ in range(len(spacePoints)))\n distance = list(float(\"inf\") for _ in range(len(spacePoints)))\n visited[0] = True\n distance[0] = 0\n Qi.put((distance[0] ,0))\n while not Qi.empty():\n _, v = Qi.get()\n visited[v] = True\n closestPoint(v, spacePoints, visited, distance, Qi)\n return sum(distance)\n\n#minimum_distance([(0,0), (0,1), (1,0), (1,1)])\nif __name__ == '__main__':\n input = sys.stdin.read()\n data = list(map(int, input.split()))\n n = data[0]\n x = data[1::2]\n y = data[2::2]\n spacePoints = []\n for i in range(len(x)):\n spacePoints.append((x[i], y[i]))\n print(\"{0:.9f}\".format(minimum_distance(spacePoints)))\n ","sub_path":"3- Algorithms on graphs/week5_mst/1_connecting_points/connecting_points.py","file_name":"connecting_points.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"130660355","text":"import argparse\nimport os\nimport signal\nfrom prometheus_ncs2_exporter import NCS2DeviceExporter, UsageFormatter\nfrom openvino.inference_engine import IECore\nfrom time import sleep\n\n\nclass AppShutdown(Exception):\n pass\n\n\ndef app_shutdown(signum, frame):\n print('Caught signal {}, exiting...'.format(signum))\n raise AppShutdown\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Sample NCS2 inference application with integrated metric exporter',\n formatter_class=UsageFormatter)\n parser.add_argument('--device', dest='device', help='NCS2 device name (default: %(default)s)', default='MYRIAD')\n parser.add_argument('--model', dest='model', help='XML (IR) model to load', required=True)\n parser.add_argument('--metrics-port', dest='metrics_port', type=int, default=8085, metavar='PORT',\n help='Port to expose device metrics on (default: %(default)s)')\n parser.add_argument('--polling-interval', dest='polling_interval', type=int, default=5, metavar='SEC',\n help='Metric polling interval in seconds (default: %(default)s)')\n args = parser.parse_args()\n\n # Install signal handlers to clean up the metric exporter thread\n signal.signal(signal.SIGTERM, app_shutdown)\n signal.signal(signal.SIGINT, app_shutdown)\n\n inference_engine = IECore()\n\n model_xml = args.model\n model_bin = os.path.splitext(model_xml)[0] + '.bin'\n\n # Read the specified network\n net = inference_engine.read_network(model_xml, model_bin)\n print('Network: {}'.format(net.name))\n\n # Load the network onto the device\n print('Loading network onto {} device...'.format(args.device))\n exec_net = inference_engine.load_network(net, args.device)\n\n print('Running network: {}'.format(exec_net.get_metric('NETWORK_NAME')))\n\n # Initialize the device metric exporter\n exporter = NCS2DeviceExporter(inference_engine=inference_engine,\n polling_interval=args.polling_interval,\n port=args.metrics_port)\n exporter.start_http_server()\n\n print('Running in the main thread')\n\n try:\n while True:\n print('Sleeping in main thread...')\n sleep(5)\n except AppShutdown:\n exporter.shutdown()\n\n\nif __name__ == '__main__':\n main()","sub_path":"inference_example.py","file_name":"inference_example.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"400542054","text":"from Tkinter import *\nimport ttk\n\nroot = Tk()\nroot.attributes('-fullscreen',True)\nroot.grid_columnconfigure(0, weight=1)\nclass Machine :\n def __init__(self) :\n self.macCycleCounter= StringVar()\n self.macCycleCount = StringVar()\n\n def setCycleCounter(self,counter) :\n self.macCycleCounter.set(counter)\n \n def setCount(self,count) :\n self.macCycleCount.set(count)\n \n def setCycleOff(self) :\n self.lblstate1.configure(bg=\"#ff1a1aff1a1a\")\n #self.lblstate2.configure(bg=\"#ff1a1aff1a1a\")\n def setCycleOn(self) :\n self.lblstate1.configure(bg=\"#94FD7C\")\n #self.lblstate2.configure(bg=\"#94FD7C\")\n \nclass MachineMainView:\n def __init__(self) :\n countColors=[\"#ffffcc\",\"#ffdab3\",\"#ccffcc\",\"#ffccff\",\"#ccffff\",\"#ffcccc\",\"#ccccff\",\"#cce4ff\"];\n machColors=[\"#ffffb3\",\"#ffcc99\",\"#b3ffb3\",\"#ffb3ff\",\"#99ffff\",\"#ffb3b3\",\"#b3b3ff\",\"#b3d7ff\"];\n #self.machines={17:Machine(),27:Machine(),22:Machine(),5:Machine(),6:Machine(),13:Machine(),19:Machine(),26:Machine()}\n self.machines={26:Machine(),19:Machine(),13:Machine(),6:Machine(),22:Machine(),27:Machine(),17:Machine()}\n #machines = [Machine() for i in range(8)]\n pos = [26,19,13,6,22,27,17]\n self.frame=Frame(root)\n for i in range(0 , 28) :\n self.frame.columnconfigure(i, weight=1)\n\n self.frame.pack(expand=True,fill=BOTH)\n rowpos=0\n i=0\n Label(self.frame,height=2, anchor=W ) .grid(row=2,column=0,sticky=W+E+N+S,columnspan=24) \n for j in range(0 , 7) :\n \n if j == 4 :\n i=0\n rowpos=3\n Label(self.frame,height=2, font=(\"Courier bold\", 60), anchor=W, bg=machColors[j] , text=\"M%d:\" %(j+1) ) .grid(row=rowpos,column=i*6,sticky=W+E+N+S) \n Label(self.frame, anchor=W, background=countColors[i],font=(\"Courier bold\", 60) , padx = 15 , textvariable=self.machines[pos[j]].macCycleCount).grid(row=rowpos,column=(i*6+1),columnspan=5,sticky=W+E+N+S)\n self.machines[pos[j]].lblstate1= Label(self.frame, height=2,anchor=W ,bg=\"#ff1a1a\" ,font=(\"Courier bold\", 40), padx = 5 ,textvariable=self.machines[pos[j]].macCycleCounter )\n self.machines[pos[j]].lblstate1.grid(row=rowpos+1,column=i*6,sticky=W+E+N+S,columnspan=6) \n i=i+1\n #for i in range(0 , 3) :\n # Label(self.frame,height=2, font=(\"Courier bold\", 60), anchor=W, bg=machColors[i+4] , text=\"M%d:\" %(i+5) ) .grid(row=3,column=i*6,sticky=E) \n # Label(self.frame, anchor=W, background=countColors[i+4] , padx = 15,font=(\"Courier bold\", 80) , textvariable=self.machines[pos[i+4]].macCycleCount).grid(row=3,column=(i*6+1),columnspan=5,sticky=W+E+N+S)\n # self.machines[pos[i+4]].lblstate1= Label(self.frame, height=2,anchor=W ,bg=\"#ff1a1a\" , font=(\"Courier bold\", 40), padx = 5,textvariable=self.machines[pos[i]].macCycleCounter )\n # self.machines[pos[i+4]].lblstate1.grid(row=4,column=i*6+1,sticky=W+E,columnspan=5) \n # self.machines[pos[i+4]].lblstate2= Label(self.frame, font=(\"Courier bold\", 20),anchor=W ,bg=\"#ff1a1a\" , text=\"M%d:\" %(i+5))\n # self.machines[pos[i+4]].lblstate2.grid(row=4,column=i*6,sticky=E+N+S) \n\n#MachineMainView()\n#root.mainloop()\n\n","sub_path":"MachineView.py","file_name":"MachineView.py","file_ext":"py","file_size_in_byte":3311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"402655444","text":"#==============================================================================================\r\n#\r\n# Descritpion: Database Wrapper functions\r\n#\r\n#==============================================================================================\r\n\r\nimport odbc\r\nimport os\r\nimport re\r\nimport socket\r\nimport sys\r\nimport time\r\nimport traceback\r\nimport util\r\nimport sqlite3\r\n_debug = False\r\n_askDBGagain = True\r\n_debugQueryTime = 0\r\n\r\n#----------------------------------------------------------------------------------------------\r\n#----------------------------------------------------------------------------------------------\r\nclass ResultRow:\r\n def __init__( self, fields, data):\r\n self.data = data\r\n self.fields = fields\r\n try:\r\n self.length = len( data)\r\n except TypeError:\r\n self.length = 0\r\n self.index = 0\r\n\r\n #------------------------------------------------------------------------------------------\r\n def __str__( self):\r\n return str( self.data)\r\n\r\n #------------------------------------------------------------------------------------------\r\n def __repr__( self):\r\n return str( self.data)\r\n\r\n #------------------------------------------------------------------------------------------\r\n def __eq__( self, other):\r\n if isinstance( other, ResultRow):\r\n return self.data == other.data\r\n else:\r\n return self.data == other\r\n\r\n #------------------------------------------------------------------------------------------\r\n def __len__( self):\r\n return self.length\r\n\r\n #------------------------------------------------------------------------------------------\r\n def __getitem__( self, key):\r\n if type(key) == slice:\r\n return self.data[key.start:key.stop:key.step]\r\n elif abs(key) <= self.length:\r\n return self.data[key]\r\n else:\r\n raise IndexError\r\n\r\n #------------------------------------------------------------------------------------------\r\n def __getattr__( self, name):\r\n \"\"\" when only one field is requested from the query self.fields = [] so we just return\r\n the atomic value fetched\r\n \"\"\"\r\n if self.data:\r\n if name in self.fields:\r\n x = self.fields.index(name)\r\n return self.data[x]\r\n elif self.fields == []:\r\n return self.data\r\n else:\r\n raise AttributeError\r\n else:\r\n return None\r\n\r\n #------------------------------------------------------------------------------------------\r\n def __iter__(self):\r\n \"\"\" Initialize the ieterator \"\"\"\r\n self.index = 0\r\n return self\r\n\r\n #------------------------------------------------------------------------------------------\r\n def __next__( self):\r\n \"\"\" Get the next row form the data set \"\"\"\r\n if self.index < self.length:\r\n rv = self.data[ self.index]\r\n self.index += 1\r\n return rv\r\n else:\r\n raise StopIteration\r\n\r\n#----------------------------------------------------------------------------------------------\r\nclass DB:\r\n \"\"\" Quick class to encapsulate DB access \"\"\"\r\n def __init__( self, DBparam = None, special = None):\r\n self.DBparam = DBparam\r\n self.special = special\r\n self.Reset()\r\n\r\n def Reset( self, forceDbUse=None):\r\n tries = 0\r\n while tries < 6:\r\n if forceDbUse is None:\r\n self.db = GetDB( self.DBparam, self.special)\r\n else:\r\n self.db = forceDbUse\r\n if self.db:\r\n self.c = GetCursor( self.db)\r\n break\r\n else:\r\n time.sleep(10)\r\n tries += 1\r\n if (_debug): print('DB connection retry in 10 seconds')\r\n self.c = None\r\n\r\n #------------------------------------------------------------------------------------------\r\n def Execute( self, sql):\r\n \"\"\" Execute a query, attempt to reconnect to the DB if the connection is lost \"\"\"\r\n if self.c:\r\n if (_debug): print(\"Execute: \", sql)\r\n while 1:\r\n try:\r\n self.c.execute( sql)\r\n return 1\r\n except :\r\n if _debug:\r\n print(traceback.print_exc())\r\n print()\r\n print(sql)\r\n return 0\r\n else:\r\n return None\r\n\r\n #------------------------------------------------------------------------------------------\r\n def GetAll( self, sql = None):\r\n \"\"\" Execute a query if provided and return the entire set \"\"\"\r\n start = time.clock()\r\n if self.c:\r\n if sql: self.Execute( sql)\r\n data = GetAll( self.c)\r\n self.queryTime = time.clock() - start\r\n else:\r\n data = None\r\n self.queryTime = -1\r\n return data\r\n\r\n #------------------------------------------------------------------------------------------\r\n def GetOne( self, sql = None):\r\n \"\"\" Execute a query if provided and return one from the cursor\r\n repeat with no sql to work through the cursor\r\n \"\"\"\r\n start = time.clock()\r\n if sql: self.Execute( sql)\r\n data = GetOne( self.c)\r\n self.queryTime = time.clock() - start\r\n return data\r\n\r\n #------------------------------------------------------------------------------------------\r\n def __del__( self):\r\n if self.db:\r\n Close( self.db)\r\n\r\n #------------------------------------------------------------------------------------------\r\n def MakeTupleStr( self, l):\r\n # create a str tuple representation usable by a DB query\r\n if len(l) == 0:\r\n t = '(NULL)'\r\n else:\r\n t = str(tuple(l))\r\n if len(l) == 1:\r\n t = t.replace(',','')\r\n\r\n return t\r\n\r\n #------------------------------------------------------------------------------------------\r\n def Close( self):\r\n self.db.Close()\r\n\r\n #------------------------------------------------------------------------------------------\r\n def Commit( self):\r\n self.db.commit()\r\n\r\n#----------------------------------------------------------------------------------------------\r\n#----------------------------------------------------------------------------------------------\r\nclass Query:\r\n \"\"\" A query Iterator object, allows a result set to be iterated over easily\r\n Additionally this object dynamically generates functions based on the selected\r\n fields in the query so you can access them by name i.e.,\r\n\r\n sql = 'select a,b from table'\r\n q = Query(sql)\r\n for i in q:\r\n a = i.a\r\n b = i.b\r\n\r\n when the fields are qualified such as\r\n 'T.fieldX' the access name becomes fieldX\r\n 'name = T.fieldX' the access name becomes name\r\n 'T.field as name' becomes name\r\n \"\"\"\r\n def __init__( self, query, db = None, data = None):\r\n \"\"\" Initalize a query object, needs a query \"\"\"\r\n self.index = 0\r\n self.dataSet = ()\r\n self.data = None\r\n self.fields = []\r\n self.query = query\r\n\r\n if data == None:\r\n if db:\r\n if type( db) == str:\r\n dba = DB(db)\r\n else:\r\n dba = db\r\n else:\r\n dba = DB('__DEFAULT_DB__')\r\n\r\n # get the data and query time\r\n start = time.clock()\r\n self.dataSet = dba.GetAll( query)\r\n self.queryTime = time.clock() - start\r\n del dba\r\n else:\r\n self.dataSet = data\r\n self.reset( query, self.dataSet)\r\n\r\n #------------------------------------------------------------------------------------------\r\n def reset( self, query, data):\r\n self.index = 0\r\n self.dataSet = data\r\n self.length = len( self.dataSet)\r\n\r\n if self.length > 0:\r\n self.data = self.dataSet[0]\r\n if type(self.data) in (list, tuple):\r\n if len(self.data) == 1:\r\n # flatten it into a simple list\r\n self.dataSet = [i for i, in self.dataSet]\r\n self.data = self.dataSet[0]\r\n self.fields = []\r\n else:\r\n # properties creation\r\n self.Properties( query)\r\n else:\r\n self.fields = []\r\n else:\r\n self.data = None\r\n self.fields = []\r\n\r\n #------------------------------------------------------------------------------------------\r\n def __len__( self):\r\n \"\"\" return the length of the data set \"\"\"\r\n return self.length\r\n\r\n #------------------------------------------------------------------------------------------\r\n def __getitem__( self, key):\r\n \"\"\" return the selected item/slice\r\n for a slice return a new Query object with the specified slice\r\n \"\"\"\r\n if type(key) == slice:\r\n return Query( self.query, data=self.dataSet[key.start:key.stop:key.step])\r\n elif abs(key) <= self.length:\r\n self.data = ResultRow( self.fields, self.dataSet[key])\r\n return self.data\r\n else:\r\n raise IndexError\r\n\r\n #------------------------------------------------------------------------------------------\r\n def __contains__( self, item):\r\n \"\"\" see if what we want is in the data set \"\"\"\r\n return item in self.dataSet\r\n\r\n #------------------------------------------------------------------------------------------\r\n def __iter__(self):\r\n \"\"\" Initialize the ieterator \"\"\"\r\n self.index = 0\r\n if self.length > 0:\r\n self.data = self.dataSet[self.index]\r\n return self\r\n\r\n #------------------------------------------------------------------------------------------\r\n def __next__( self):\r\n \"\"\" Get the next row form the data set \"\"\"\r\n if self.index < self.length:\r\n self.data = ResultRow( self.fields, self.dataSet[self.index])\r\n self.index += 1\r\n return self.data\r\n else:\r\n raise StopIteration\r\n\r\n #------------------------------------------------------------------------------------------\r\n def __bool__( self):\r\n \"\"\" Check if the query returned anything eg.\r\n d = Query(s)\r\n if d:\r\n ...\r\n \"\"\"\r\n return (self.length > 0)\r\n\r\n #------------------------------------------------------------------------------------------\r\n def __getattr__( self, name):\r\n \"\"\" This function provides the capability to fetch data values by the DB field names\r\n When only one field is requested in the query self.fields = [] and the tuples\r\n returned are flatten (see reset) so we just return the atomic value fetched which\r\n is in self.data\r\n \"\"\"\r\n if self.dataSet:\r\n if name in self.fields:\r\n x = self.fields.index(name)\r\n return self.data[x]\r\n elif self.fields == []:\r\n return self.data\r\n else:\r\n raise AttributeError\r\n else:\r\n return None\r\n\r\n #------------------------------------------------------------------------------------------\r\n def reverse( self):\r\n \"\"\" reverse the order of the dataSet \"\"\"\r\n if self.length > 0:\r\n self.dataSet.reverse()\r\n self.index = 0\r\n self.data = self.dataSet[0]\r\n\r\n #------------------------------------------------------------------------------------------\r\n def MakeTupleStr( self, l):\r\n \"\"\" create a str tuple representation usable by a DB query \"\"\"\r\n if len(l) == 0:\r\n t = '(NULL)'\r\n else:\r\n t = str(tuple(l))\r\n if len(l) == 1:\r\n t = t.replace(',','')\r\n\r\n return t\r\n\r\n #------------------------------------------------------------------------------------------\r\n def Properties( self, query):\r\n \"\"\" build field reference names from the query string for __getattr__ \"\"\"\r\n selAt = query.lower().find('select')\r\n newFields = []\r\n if selAt != -1:\r\n selAt += len('select')\r\n fromAt = query.lower().find('from')\r\n fields = query[selAt:fromAt]\r\n fields = fields.replace('\\n', ' ')\r\n # remove SQL functions\r\n fields = self.SQLfields( fields)\r\n fields = fields.split(',')\r\n fields = [i.strip() for i in fields]\r\n\r\n # process select column syntax\r\n for field in fields:\r\n # change N = T.F to N\r\n eq = field.find('=')\r\n if eq != -1:\r\n field = field[:eq].strip()\r\n else:\r\n # change T.F as N to N\r\n asX = field.find(' as ')\r\n if asX != -1:\r\n field = field[asX+4:].strip()\r\n else:\r\n # change table.field to field\r\n per = field.find('.')\r\n if per != -1:\r\n field = field[per+1:].strip()\r\n newFields.append( field)\r\n self.fields = newFields\r\n\r\n #------------------------------------------------------------------------------------------\r\n def SQLfields( self, fields):\r\n \"\"\" return a string with SQL functions removed by parameter count\r\n \"\"\"\r\n castRE = re.compile( r'cast *\\(.+?\\)', re.IGNORECASE)\r\n convertRE = re.compile( r'convert *\\(.+?\\)', re.IGNORECASE)\r\n isnullRE = re.compile( r'isnull *\\(.+?\\)', re.IGNORECASE)\r\n fieldRE = { castRE:0, convertRE:1, isnullRE:0}\r\n for theRE in fieldRE:\r\n paramNum = fieldRE[theRE]\r\n fields = self.FieldSearch( fields, theRE, paramNum)\r\n\r\n #remove single param functions\r\n single = ('max', 'min', 'sum', 'ceiling', 'floor')\r\n for i in single:\r\n reFmt = re.compile( r'%s *\\(.+?\\)' % i, re.IGNORECASE)\r\n fields = self.FieldSearch( fields, theRE, 0)\r\n\r\n removeList = ('distinct', '(', ')')\r\n for i in removeList:\r\n fields = fields.replace( i, '')\r\n return fields\r\n\r\n #------------------------------------------------------------------------------------------\r\n def FieldSearch( self, fields, theRE, paramNum):\r\n matches = theRE.findall( fields)\r\n for theMatch in matches:\r\n replaceStr = self.GetExpression( theMatch, paramNum)\r\n fields = fields.replace( theMatch, replaceStr)\r\n return fields\r\n\r\n #------------------------------------------------------------------------------------------\r\n def GetExpression( self, aMatch, index):\r\n # remove before and after the parenthesis inclusive\r\n lp = aMatch.find('(')\r\n rp = aMatch.find(')')\r\n aMatch = aMatch[lp+1:rp]\r\n # split the string on ','\r\n a1Match = aMatch.split(',')\r\n if len(a1Match) == 1:\r\n # split on 'AS'\r\n a1Match = aMatch.lower().split(' as ')\r\n return a1Match[index]\r\n\r\n#----------------------------------------------------------------------------------------------\r\ndef DBaccessStr():\r\n server = input('Enter the server name: ')\r\n UID = input('Enter the user ID: ')\r\n password = input('Enter the password: ')\r\n dbname = input('Enter the DB name: ')\r\n accessStr = \"DRIVER={SQL Server};SERVER=%s;UID=%s;PWD=%s;DATABASE=%s\" % (server, UID,\r\n password, dbname)\r\n\r\n return accessStr\r\n\r\n#----------------------------------------------------------------------------------------------\r\ndef GetDB( DBparam = None, special = None):\r\n \"\"\" Get a DB connection\r\n DBparam == '__DEFAULT_DB__' provides connection to default DB based on the\r\n host machine name. This is really for the Live servers 'dbserv','webserv'\r\n Any machine in Altair will default to the live backup 'Groundsoft_DBSERV'\r\n special == 'special' means that the special param will hold the login info for the\r\n require DB\r\n \"\"\"\r\n global _debug\r\n global _askDBGagain\r\n \r\n name = r'knowlogicTestDB.db'\r\n conn = sqlite3.connect(name)\r\n return conn\r\n\r\n\r\n #Open a DB connection, Check to see if we are running this on the live site\r\n host = socket.gethostname()\r\n if host == 'AE415730':\r\n p = r'H:\\Knowlogic\\Documents\\Trace\\TraceDB.mdb'\r\n elif host == 'Main':\r\n p = r'F:\\Knowlogic\\Documents\\Trace\\TraceDB.mdb'\r\n elif host == 'Jeff-Laptop':\r\n p = r'I:\\Knowlogic\\Documents\\Trace\\TraceDB.mdb'\r\n else:\r\n p = r'E:\\Knowlogic\\Documents\\Trace\\TraceDB.mdb'\r\n\r\n DBselect = 'DB'\r\n if DBselect.lower() == 'special':\r\n DBselect = 'DB'\r\n p = special\r\n\r\n # DB Choices\r\n DBchoices = {\r\n \"DB\": r\"DRIVER={Microsoft Access Driver (*.mdb)}; Dbq=%s;\" % p,\r\n }\r\n\r\n print('help')\r\n return None\r\n try:\r\n login = DBchoices[ DBselect]\r\n return odbc.odbc( login)\r\n except:\r\n print(\"GetDB: Unexpected error:\\n\", sys.exc_info())\r\n traceback.print_exc()\r\n return None\r\n\r\n#----------------------------------------------------------------------------------------------\r\ndef Close( db):\r\n \"\"\" Close the DB connection \"\"\"\r\n try:\r\n db.close()\r\n return 1\r\n except:\r\n print(\"Close: Unexpected error:\\n\", sys.exc_info())\r\n traceback.print_exc()\r\n return 0\r\n\r\n#----------------------------------------------------------------------------------------------\r\ndef GetCursor( db):\r\n \"\"\" return a cursor for a database \"\"\"\r\n try:\r\n return db.cursor()\r\n except:\r\n print(\"GetCursor: Unexpected error:\\n\", sys.exc_info())\r\n traceback.print_exc()\r\n return None\r\n\r\n#----------------------------------------------------------------------------------------------\r\ndef GetDBC( DBparam = None, special = None):\r\n \"\"\" return a Db connection and a cursor\"\"\"\r\n db = GetDB( DBparam, special)\r\n c = GetCursor( db)\r\n return db, c\r\n\r\n#----------------------------------------------------------------------------------------------\r\ndef Execute( cursor, sql):\r\n \"\"\" Execute a SQL statement against a specified cursor \"\"\"\r\n try:\r\n if (_debug): print(\"Execute: \", sql)\r\n cursor.execute( sql)\r\n return 1\r\n except:\r\n if (_debug):\r\n print(\"Execute: Unexpected error:\\n\", sys.exc_info())\r\n traceback.print_exc()\r\n return 0\r\n\r\n#----------------------------------------------------------------------------------------------\r\ndef GetAll( c):\r\n \"\"\" return the cursor result set \"\"\"\r\n global _debugQueryTime\r\n try:\r\n start = time.clock()\r\n allOfThem = c.fetchall()\r\n _debugQueryTime = time.clock() - start\r\n if allOfThem == None:\r\n allOfThem = []\r\n return allOfThem\r\n except:\r\n if (_debug):\r\n print(\"GetAll: Unexpected error:\\n\", sys.exc_info())\r\n traceback.print_exc()\r\n return []\r\n\r\n#----------------------------------------------------------------------------------------------\r\ndef GetOne( c):\r\n \"\"\" return the top row of the cursor result set working through the set \"\"\"\r\n global _debugQueryTime\r\n try:\r\n start = time.clock()\r\n theOne = c.fetchone()\r\n _debugQueryTime = time.clock() - start\r\n if theOne == None:\r\n theOne = ()\r\n return theOne\r\n except:\r\n if (_debug):\r\n print(\"GetOne: Unexpected error:\\n\", sys.exc_info())\r\n traceback.print_exc()\r\n return ()\r\n\r\n#----------------------------------------------------------------------------------------------\r\ndef DebugState( state):\r\n global _debug\r\n if state:\r\n _debug = True\r\n else:\r\n _debug = False\r\n\r\n#----------------------------------------------------------------------------------------------\r\ndef GS_DBlist():\r\n \"\"\" Create a file with table information \"\"\"\r\n db = DB('__DEFAULT_DB__')\r\n tables = AllTableList( db)\r\n\r\n f = file( 'DB.dat', 'w')\r\n\r\n for i, in tables:\r\n print('Process: %s' % i)\r\n str = '------------------ %s' % (i)\r\n f.write( str + '\\n')\r\n ListTable( i, db, f)\r\n\r\n f.write( '%d Tables\\n' % (len(tables)))\r\n f.close()\r\n\r\n#----------------------------------------------------------------------------------------------\r\ndef AllTableList(db):\r\n \"\"\" Returns a list of every user table in the database \"\"\"\r\n if not db:\r\n db = database.DB('__DEFAULT_DB__')\r\n all = db.GetAll(\"SELECT name FROM sysobjects WHERE xtype='U' ORDER BY name\")\r\n return all\r\n\r\n#----------------------------------------------------------------------------------------------\r\ndef ListTable( table, db, f):\r\n \"\"\" Get Column info \"\"\"\r\n info = db.GetAll( \"sp_columns @table_name='%s'\" % table)\r\n pk = db.GetAll(\"sp_pkeys @table_name='%s'\" % table) # primary key info\r\n # strip pk column names\r\n pk = [i[3] for i in pk]\r\n for i in info:\r\n str = 'Column[%32s ] Type[%15s ] Nullable[%3s] Primary[ %3s ]' % (\r\n i[3], i[5], i[10] and 'Yes' or ' No', i[3] in pk and 'Yes' or ' No')\r\n f.write(str + '\\n')\r\n\r\n#----------------------------------------------------------------------------------------------\r\ndef TestDBexecuteRetry():\r\n db = DB('__DEFAULT_DB__')\r\n for i in range(1000):\r\n s = 'select count(*) from gs_install'\r\n print('%3d' % i, time.asctime(time.localtime()), db.GetAll(s))\r\n time.sleep(5)\r\n\r\n#----------------------------------------------------------------------------------------------\r\nif __name__ == '__main__':\r\n GS_DBlist()\r\n","sub_path":"misc/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":22218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"250217253","text":"from flask import Flask, jsonify, request\nfrom threading import Thread\n\nfrom datetime import datetime\nimport requests\nimport time\n\napp = Flask(__name__)\n\nendpoint_url = \"http://localhost:5001/paciente/1/registrarevento\"\n\n@app.route('/')\ndef index(): \n return jsonify({\"message\": \"hello message broker\"})\n \n@app.route(\"/\", methods=[\"POST\"])\ndef post():\n\n def call_to_endpoint(data):\n \n counter = 0\n while counter < 99:\n try:\n counter += 1\n print(\"============================================================\")\n print(\"connnection to endpoint...\")\n res = requests.post(endpoint_url, json=data)\n print(\"connection success\")\n counter = 100\n except Exception as err:\n print(\"\")\n print(\"connection failed, \", datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\"))\n print(err)\n time.sleep(2)\n\n send_to_data = request.json\n\n thread = Thread(target=call_to_endpoint, kwargs={'data': send_to_data})\n thread.start()\n\n return jsonify({\"message\": \"successs\"})\n\nif __name__ == '__main__':\n app.run(debug=True, port=5000)\n","sub_path":"messageBroker/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"370375890","text":"# -*- coding: utf-8 -*-\n\nimport logging\n\n\ntry:\n from private_settings import DEFAULT_MAIL_FROM\n from private_settings import SECRET_KEY\n from private_settings import DEBUG\n\n logging.info('Used private settings')\nexcept ImportError:\n logging.warning('Used default settings')\n DEFAULT_MAIL_FROM = 'admin@x-x-x.com'\n SECRET_KEY = 'ReplaceItWithSecretString'\n DEBUG = True\n\nDEFAULT_TIMEZONE = 'Europe/Moscow'\nPROFILE = False\nSESSION_PREFIX = 'gaesess:'\nSESSION_STORE = 'kay.sessions.sessionstore.GAESessionStore'\n#SESSION_STORE = 'kay.sessions.sessionstore.SecureCookieSessionStore'\nCOOKIE_AGE = 1209600 # 2 weeks\nCOOKIE_NAME = '5STUDIO_SESSION'\n\nADD_APP_PREFIX_TO_KIND = True\nACCOUNT_ACTIVATION_DURATION = 172800 # (24h * 2)\nCACHE_MIDDLEWARE_SECONDS = 120\n\nADMINS = (\n)\n\nTEMPLATE_DIRS = (\n'templates',\n)\n\nUSE_I18N = True\nDEFAULT_LANG = 'ru'\n\nINSTALLED_APPS = (\n'kay.sessions',\n'kay.i18n',\n'kay.auth',\n'kay.registration',\n'kay.ext.ereporter',\n'apps.image',\n'apps.gift',\n'apps.auth5',\n'apps.admin',\n'apps.price',\n'apps.store',\n'apps.discount',\n'apps.api',\n'apps.about',\n'apps.sitemaps',\n'apps.brands',\n'apps.locstore',\n'apps.postman',\n'apps.category',\n'apps.dragons',\n'apps.presentation',\n'apps.srch',\n'apps.partners',\n'apps.action',\n'apps.showcase',\n'apps.file',\n'apps.sync',\n'apps.job',\n'apps.files'\n)\n\nAPP_MOUNT_POINTS = {\n 'kay.ext.ereporter': '/_kay/ereporter/',\n 'apps.gift': '/',\n 'apps.sitemaps': '/'\n}\n\nJINJA2_FILTERS = {\n 'truncatewords': 'filters.truncatewords',\n 'urlify': 'filters.urlify',\n 'markup': 'filters.markup',\n 'get_img_url': 'apps.image.filters.link',\n 'thumb_image': 'apps.image.filters.thumb_image',\n 'url_thumb': 'apps.image.filters.url_thumb',\n 'presentation': 'filters.presentation',\n 'json_quotes_markup': 'filters.json_quotes_markup',\n 'speak_date': 'filters.speak_date',\n 'catalogue': 'filters.catalogue',\n}\n\n# You can remove following settings if unnecessary.\nCONTEXT_PROCESSORS = (\n'kay.context_processors.request',\n'kay.context_processors.url_functions',\n'kay.context_processors.media_url',\n'kay.ext.media_compressor.context_processors.media_urls',\n)\n\nMIDDLEWARE_CLASSES = (\n'kay.auth.middleware.AuthenticationMiddleware',\n'kay.sessions.middleware.SessionMiddleware',\n'kay.cache.middleware.CacheMiddleware',\n)\n\nAUTH_USER_BACKEND = 'kay.auth.backends.datastore.DatastoreBackend'\nAUTH_USER_MODEL = 'apps.auth5.models.UserProfile'\n\nCOMPILE_MEDIA_JS = {\n 'base5.js': {\n 'output_filename': 'base5.js',\n 'source_files': ('media/js/jquery.scroll.js',\n 'media/js/main_menu.js',)\n },\n 'gift_get.js': {\n 'output_filename': 'gift_get.js',\n 'source_files': (\n 'media/js/jquery.colorbox.js',\n 'media/js/jquery.truncatewords.js',\n 'media/js/jquery.simplemodal.js',\n 'media/js/osx_modal.js',\n 'media/js/bootstrap-alerts.js'\n )\n },\n 'price_online.js': {\n 'output_filename': 'price_online.js',\n 'source_files': (\n 'media/js/jquery.simplemodal.js',\n 'media/js/json2.js',\n 'media/js/jquery.tabs.min.js'\n )\n }\n}\n\nCOMPILE_MEDIA_CSS = {\n 'base5.css': {\n 'output_filename': 'base5.css',\n 'source_files': (\n 'media/css/reset.css',\n 'media/css/grid.css',\n 'media/css/base.css',\n 'media/css/header.css',\n 'media/css/separator.css',\n 'media/css/button.css',\n 'media/css/main_menu.css',\n 'media/css/search_bar.css',\n 'media/css/scroll_to_top.css',\n ),\n },\n\n 'gift_list.css': {\n 'output_filename': 'gift_list.css',\n 'source_files': (\n 'media/css/backlight.css',\n 'media/css/gift_list.css',\n 'media/css/filter.css',\n 'media/css/jquery.badger.css',\n ),\n },\n\n 'gift.css': {\n 'output_filename': 'gift.css',\n 'source_files': (\n 'media/css/backlight.css',\n 'media/css/gift_list.css',\n 'media/css/colorbox.css',\n 'media/css/jquery.badger.css',\n 'media/css/osx_modal.css',\n 'media/css/bootstrap.css'\n ),\n },\n\n 'discount_example.css': {\n 'output_filename': 'discount_example.css',\n 'source_files': (\n 'media/css/backlight.css',\n 'media/css/gift_list.css',\n )\n },\n\n 'price_online.css': {\n 'output_filename': 'price_online.css',\n 'source_files': (\n 'media/css/tabs.css',\n 'media/css/price_online.css'\n )\n }\n}\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"225160666","text":"\"\"\"\r\n Informatik I, HS 2018\r\n Oliver Strassmann, 23. Nov\r\n Exercise 9, task 2\r\n\"\"\"\r\n\r\n\r\nfrom abc import ABC, abstractmethod\r\n\r\n\r\nclass Toy:\r\n def __init__(self, name):\r\n self.name = name\r\n self.is_assembled = False\r\n self.is_painted = False\r\n self.is_wrapped = False\r\n\r\n def is_complete(self):\r\n if self.is_assembled and self.is_painted and self.is_wrapped:\r\n return True\r\n return False\r\n\r\n\r\nclass AssemblyLine:\r\n\r\n def __init__(self, toys):\r\n self.__toys = toys\r\n\r\n def get_toys(self):\r\n return self.__toys\r\n\r\n def get_number_of_toys(self):\r\n return len(self.get_toys())\r\n\r\n def take_toy(self):\r\n \"\"\" removes the first toy from the assembly line (i.e., the toy at position 0 in the list) and returns it.\r\n If there are no toys in the assembly line, None should be returned. \"\"\"\r\n toy = self.__toys[0]\r\n self.__toys.remove(self.__toys[0])\r\n return toy\r\n\r\n def put_toy_back(self, toy):\r\n \"\"\" adds the toy back to the assembly line (at the last position).\r\n Make sure it is not possible to put anything other than a toy back into the assembly line. \"\"\"\r\n if isinstance(toy, Toy):\r\n self.__toys.append(toy)\r\n\r\n\r\nclass Elf(ABC):\r\n\r\n def __init__(self):\r\n self._toy_working_on = None\r\n\r\n @abstractmethod\r\n def do_job(self):\r\n pass\r\n\r\n def take_from(self, assembly_line):\r\n \"\"\" takes a toy from an assembly line that is passed as parameter and stores it to _toy_working_on.\r\n If the elf is already working on a toy, this method should do nothing \"\"\"\r\n\r\n if self._toy_working_on is None:\r\n self._toy_working_on = assembly_line.take_toy()\r\n\r\n def put_back(self, assembly_line):\r\n \"\"\" puts the toy the elf was working on back into the given assembly line.\r\n After putting back the toy, the elf should have no reference to the toy it has worked on anymore \"\"\"\r\n\r\n if self._toy_working_on is not None:\r\n assembly_line.put_toy_back(self._toy_working_on)\r\n self._toy_working_on = None\r\n\r\n\r\nclass AssemblerElf(Elf):\r\n\r\n def do_job(self):\r\n if self._toy_working_on is not None:\r\n self._toy_working_on.is_assembled = True\r\n\r\n\r\nclass PainterElf(Elf):\r\n\r\n def do_job(self):\r\n if self._toy_working_on is not None:\r\n self._toy_working_on.is_painted = True\r\n\r\n\r\nclass WrapperElf(Elf):\r\n\r\n def do_job(self):\r\n if self._toy_working_on is not None:\r\n if self._toy_working_on.is_assembled and self._toy_working_on.is_painted:\r\n self._toy_working_on.is_wrapped = True\r\n\r\n\r\nclass Santa:\r\n\r\n def verify(self, assembly_line):\r\n ok = True\r\n for toy in assembly_line.get_toys():\r\n if not toy.is_wrapped:\r\n ok = False\r\n break\r\n\r\n if ok:\r\n return True\r\n return False\r\n\r\n\r\nif __name__ == '__main__':\r\n # Create three toys\r\n toy1 = Toy(\"Toy1\")\r\n toy2 = Toy(\"Toy2\")\r\n toy3 = Toy(\"Toy3\")\r\n # Create an assembly line with three toys\r\n line = AssemblyLine([toy1, toy2, toy3])\r\n\r\n # Create three elves, one of each subclass\r\n assembler = AssemblerElf()\r\n painter = PainterElf()\r\n wrapper = WrapperElf()\r\n\r\n # Create a Santa :-)\r\n santa = Santa()\r\n\r\n # Let the elves work through the assembly line\r\n for elf in [assembler, wrapper, painter]: # Wrong order: wrapping can't happen before painting!\r\n for i in range(line.get_number_of_toys()):\r\n elf.take_from(line)\r\n elf.do_job()\r\n elf.put_back(line)\r\n\r\n # The line cannot be verified because the toys are not wrapped\r\n assert not santa.verify(line)\r\n\r\n # Create three new toys...\r\n toy4 = Toy(\"Toy4\")\r\n toy5 = Toy(\"Toy5\")\r\n toy6 = Toy(\"Toy6\")\r\n\r\n # ... and a new assembly line\r\n line2 = AssemblyLine([toy4, toy5, toy6])\r\n\r\n # This time, let the elves work through the assembly line in the right order\r\n for elf in [painter, assembler, wrapper]: # Right order: wrap at the end!\r\n for i in range(line2.get_number_of_toys()):\r\n elf.take_from(line2)\r\n elf.do_job()\r\n elf.put_back(line2)\r\n\r\n # Now the line can be verified\r\n assert santa.verify(line2)\r\n","sub_path":"2018_Informatik_l/Ex_9/oliver_strassmann_15932726_info1_exercise_9/task_2.py","file_name":"task_2.py","file_ext":"py","file_size_in_byte":4354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"189865542","text":"from django.shortcuts import render, redirect\nfrom .models import Note\n\n\ndef index(request):\n if request.method == 'POST':\n title = request.POST.get('titulo')\n content = request.POST.get('detalhes')\n \n note=Note(content=content,title=title)\n note.save()\n return redirect('index')\n else:\n all_notes = Note.objects.all()\n return render(request, 'notes/index.html', {'notes': all_notes})\n\ndef delete(request):\n if request.method == \"POST\":\n get_id = request.POST.get('id')\n note = Note.objects.get(id=get_id)\n note.delete()\n return redirect('index')\n\ndef update(request,id):\n if request.method==\"POST\":\n newtitle = request.POST.get('titulo')\n newcontent = request.POST.get('detalhes')\n note = Note.objects.filter(id=id)\n note.update(title=newtitle,content=newcontent)\n return redirect('index')\n else:\n note = Note.objects.get(id = id)\n return render(request, 'notes/index.html', {\"note\":note})","sub_path":"notes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"6129136","text":"\nimport sys\n\nimport dateutil.parser\nimport sqlalchemy\nimport sqlalchemy.orm\n\nimport run_analytics.models as models\n\n\ndef input_athlete(db):\n athlete = models.Athlete()\n athlete.name = input('Athlete name . . . ')\n db.add(athlete)\n db.commit()\n\ndef list_athletes(db):\n print('ID Name')\n for athlete in db.query(models.Athlete):\n print(athlete.listformat())\n\ndef input_session(db):\n list_athletes(db)\n session = models.Session()\n session.athlete_id = int( input('Athlete id . . . '))\n session.distance = float( input('Distance . . . '))\n session.start_datetime = dateutil.parser.parse(\n input('Start time . . . '))\n session.end_datetime = dateutil.parser.parse(\n input('End time . . . '))\n session.session_type = ( input('Session type . . . '))\n session.running_time = int( input('Time (seconds) . . . '))\n db.add(session)\n db.commit()\n\ndef list_sessions(db):\n for session in db.query(models.Session):\n print(session.listformat())\n \n\nif __name__ == '__main__':\n engine = sqlalchemy.create_engine('postgresql+psycopg2:///run_analytics',\n echo=False)\n db = sqlalchemy.orm.sessionmaker(bind=engine, autoflush=True)()\n # choose data type to enter\n table = sys.argv[1]\n mode = sys.argv[2]\n if table == 'athlete':\n if mode == 'add':\n input_athlete(db)\n elif mode == 'list':\n list_athletes(db)\n elif table == 'session':\n if mode == 'add':\n input_session(db)\n elif mode == 'list':\n list_sessions(db)\n #elif table == 'metric':\n # if mode == 'add':\n # input_metric(db)\n # elif mode == 'list':\n # list_metrics(db)\n","sub_path":"frontend/frontend.py","file_name":"frontend.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"17348234","text":"import setuptools\n\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"sql_metadata_lineage\",\n version=\"0.0.1\",\n author=\"Praveen Kumar B\",\n author_email=\"bpraveenkumar21@gmail.com\",\n description=\"Package to get SQL query metadata(first level lineage), column -> database.table.actual_column mapping along with table alias mapping(alias -> database.table)\",\n keywords = ['SQL metadata', 'SQL parse metadata', 'Metadata lineage for SQL', 'SQL Lineage'],\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/PraveenKumar-21/sql_metadata_lineage\",\n packages=setuptools.find_packages(),\n install_requires=[\n 'sqlparse',\n ],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n python_requires='>=3.6',\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"475535022","text":"from floret_store.views import FloretsListView,FloretDetailView,FloretCreate,FloretUpdate,FloretDelete\nfrom django.contrib.auth.decorators import permission_required\nfrom django.conf.urls import url\n\nurlpatterns = [\nurl(r'^(?P\\d+)/$',FloretsListView.as_view(), name=\"florets_index\"),\n\nurl(r'^(?P\\d+)/detail/$',FloretDetailView.as_view(), name=\"florets_detail\"),\nurl(r'^(?P\\d+)/add/$',permission_required(\"floret_store.add_floret\")(FloretCreate.as_view()), name=\"florets_add\"),\nurl(r'^(?P\\d+)/edit/$',permission_required(\"floret_store.change_floret\")(FloretUpdate.as_view()), name=\"florets_edit\"),\nurl(r'^(?P\\d+)/delete/$',permission_required(\"floret_store.delete_floret\")(FloretDelete.as_view()), name=\"florets_delete\"),\n]\n","sub_path":"floret_store/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"16260997","text":"from django.test import TestCase\r\n\r\nfrom bussdatabase.models import Buss, Chassisprodusent, Karosserifabrikk, Selskap\r\n\r\nfrom django.test.client import Client\r\nfrom django.contrib.auth.models import User\r\n\r\n\r\ndef create_user():\r\n user = User.objects.create_user('test', 'test@bussdatabasen.no', 'secret')\r\n return user\r\n\r\n\r\ndef create_buss():\r\n selskap = Selskap.objects.create(navn='Oslo sporveier', forkortelse='OS')\r\n karosseri = Karosserifabrikk.objects.create(navn='Arna Busser AS',\r\n alternativt_navn='Arna Bruk',\r\n forkortelse='Arna',\r\n sted='Arna ved Bergen',\r\n første_år=1947,\r\n siste_år=1997)\r\n chassis = Chassisprodusent.objects.create(navn='Volvo',\r\n wikipedia='https://no.wikipedia.org/wiki/Volvo_Bussar')\r\n Buss.objects.create(selskap=selskap,\r\n registreringsnummer='SR18712',\r\n byggeår=1987,\r\n karosserifabrikk=karosseri,\r\n chassis=chassis,\r\n motor='THB100EB',\r\n ytelse=245,\r\n lengde=12.2,\r\n bredde=2.5,\r\n akselavstand=5.9,\r\n vekt=1070,\r\n sitteplasser=38,\r\n ståplasser=35,\r\n eier='Lokaltrafikkhistorisk forening',\r\n )\r\n\r\n\r\nclass BussTestCase(TestCase):\r\n def setUp(self):\r\n # self.user = create_user()\r\n # self.client = Client\r\n create_buss()\r\n\r\n def test_buss_navn(self):\r\n buss = Buss.objects.get(registreringsnummer='SR18712')\r\n print(buss)\r\n print(buss.navn())\r\n\r\n self.assertEqual(buss.navn(), 'Oslo sporveier 793')\r\n self.assertEqual(buss.navn_kort(), 'OS 793')\r\n","sub_path":"bussdatabase/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"501658436","text":"import grouper\nfrom course import Student, Course\nfrom survey import MultipleChoiceQuestion, NumericQuestion, YesNoQuestion, \\\n CheckboxQuestion, Answer, Survey\nfrom criterion import HomogeneousCriterion, HeterogeneousCriterion, \\\n LonelyMemberCriterion\nfrom grouper import AlphaGrouper, RandomGrouper, GreedyGrouper, WindowGrouper, \\\n Group, Grouping\n\n# Create some Student objects\nstudent1 = Student(1, \"Sannat\")\nstudent2 = Student(2, \"Divij\")\nstudent3 = Student(3, \"Jay\")\nstudent4 = Student(4, \"Roger\")\n\n# Create some course objects\ncourse1 = Course(\"CSC148\")\ncourse2 = Course(\"CSC165\")\ncourse3 = Course(\"MAT137\")\n\n# Create some question objects\nquestion1 = MultipleChoiceQuestion(1, \"What is you favorite language\",\n ['Python', 'JAVA', 'C++', 'Javascript'])\nquestion2 = NumericQuestion(2, \"Rate the difficulty of UofT\", 1, 10)\nquestion3 = YesNoQuestion(3, \"Do you like university\")\nquestion4 = CheckboxQuestion(4, \"What foods do you like\",\n [\"Burger\", \"Salad\", \"Poutine\", \"Steak\"])\n\n# Create answer objects\nanswer1_1 = Answer('Python')\nanswer2_1 = Answer(5)\nanswer3_1 = Answer(True)\nanswer4_1 = Answer(['Salad', 'Poutine'])\n\nanswer1_2 = Answer('Javascript')\nanswer2_2 = Answer(7)\nanswer3_2 = Answer(True)\nanswer4_2 = Answer(['Burger', 'Poutine'])\n\n# Create survey objects\nsurvey1 = Survey([question1, question2, question3, question4])\n\nstudent = Student(10, 'Divij')\nstudent_1 = Student(20, 'Sannat')\nstudent_2 = Student(30, 'Vaibhav')\nstudent_3 = Student(40, 'Tanuj')\n\nquestion = CheckboxQuestion(1, \"What's your name?\",\n ['Sannat', 'Jay', 'Vaibhav', 'Divij'])\n\nquestion_4 = MultipleChoiceQuestion(5, \"What's your name?\",\n ['Sannat', 'Jay', 'Vaibhav', 'Divij'])\n\nquestion_2 = YesNoQuestion(3, \"Do you like university\")\n\nquestion_3 = NumericQuestion(4, \"What's your weight?\", 10, 15)\n\nstudent_list = [student, student_1, student_2, student_3]\ncourse = Course('Computer Science')\ncourse.enroll_students(student_list)\nweight = 1\n\n# List of answers\nanswer = Answer(True)\nanswer_1 = Answer(False)\nanswer_2 = Answer('Divij')\nanswer_3 = Answer(['Sannat'])\nanswer_4 = Answer('Divij')\nanswer_5 = Answer(11)\nanswer_6 = Answer(17)\n\n# Setting answers to students for question_2\nstudent.set_answer(question_2, answer)\nstudent_1.set_answer(question_2, answer_1)\nstudent_2.set_answer(question_2, answer)\nstudent_3.set_answer(question_2, answer_1)\n\n# Setting answers to students for question_4\nstudent.set_answer(question_4, answer_2)\nstudent_1.set_answer(question_4, answer_3)\nstudent_2.set_answer(question_4, answer_4)\nstudent_3.set_answer(question_4, answer_2)\n\n# Setting criterion for survey questions\n\nsurvey_x = Survey([question_2, question_4])\nsurvey_x.set_criterion(HomogeneousCriterion(), question_2)\nsurvey_x.set_criterion(HeterogeneousCriterion(), question_4)\n\n# Finding similarities of student answers with answers of student_1:\n\n# student = 1\n# student_1 = 0 + 0 = 0\n# student_2 = 1 + 1 = 2\n# student_3 = 0 + 1 = 1\n\n\nclass TestStudent:\n def test___str__(self):\n assert str(student1) == \"Sannat\"\n\n def test_has_answer(self):\n assert not student1.has_answer(question1)\n\n def test_set_answer(self):\n student1.set_answer(question1, answer1_1)\n assert student1.has_answer(question1)\n\n def test_get_answer(self):\n assert student1.get_answer(question1) == answer1_1\n assert student1.get_answer(question2) is None\n student1.set_answer(question3, answer3_1)\n assert student1.get_answer(question3) == answer3_1\n\n\nclass TestCourse:\n def test_enroll_students_get_students_empty_list(self):\n assert course1.enroll_students([]) is None\n assert course1.get_students() == ()\n\n def test_enroll_students_get_students(self):\n course1.enroll_students([student1, student2])\n assert course1.get_students() == (student1, student2)\n\n def test_all_answered(self):\n # student1 already has answer for question1, question3\n # student2 has no answers as of yet\n assert not course1.all_answered(survey1)\n student1.set_answer(question2, answer2_1)\n student1.set_answer(question4, answer4_1)\n student2.set_answer(question1, answer1_2)\n student2.set_answer(question2, answer2_2)\n student2.set_answer(question3, answer3_2)\n student2.set_answer(question4, answer4_2)\n assert course1.all_answered(survey1)\n\n\nclass TestMultipleChoiceQuestion:\n def test___str__(self):\n assert isinstance(str(question1), str)\n\n def test_validate_answer(self):\n assert not question1.validate_answer(Answer(True))\n assert question1.validate_answer(answer1_1)\n assert not question1.validate_answer(Answer(''))\n\n def test_get_similarity_not_similar(self):\n assert question1.get_similarity(answer1_1, answer1_2) == 0.0\n\n def test_get_similarity_similar_but_different_instance(self):\n assert question1.get_similarity(answer1_1, Answer('Python')) == 1.0\n\n\nclass TestNumericQuestion:\n def test___str__(self):\n assert isinstance(str(question2), str)\n\n def test_validate_answer(self):\n assert not question2.validate_answer(Answer('1'))\n assert question2.validate_answer(answer2_1)\n\n def test_validate_answer_boundaries(self):\n assert question2.validate_answer(Answer(1))\n assert question2.validate_answer(Answer(10))\n\n def test_validate_answer_out_of_bound(self):\n assert not question2.validate_answer(Answer(15))\n assert not question2.validate_answer(Answer(-4))\n\n def test_get_similarity(self):\n similarity = question2.get_similarity(answer2_1, answer2_2)\n assert round(similarity, 2) == round(1 - 2 / 9, 2)\n\n\nclass TestYesNoQuestion:\n def test___str__(self):\n assert isinstance(str(question3), str)\n\n def test_validate_answer(self):\n assert question3.validate_answer(Answer(True))\n assert not question3.validate_answer(Answer(['True']))\n\n def test_get_similarity(self):\n assert question3.get_similarity(answer3_1, answer3_2) == 1.0\n assert question3.get_similarity(Answer(True), Answer(False)) == 0.0\n\n\nclass TestCheckboxQuestion:\n def test___str__(self):\n assert isinstance(str(question4), str)\n\n def test_validate_answer(self):\n assert question4.validate_answer(answer4_1)\n\n def test_validate_answer_some_overlap_but_fails(self):\n assert not question4.validate_answer(Answer(['Salad', 'Steak', 'N/A']))\n\n def test_get_similarity(self):\n similarity = question4.get_similarity(answer4_1, answer4_2)\n assert round(similarity, 2) == round(1 / 3, 2)\n similarity = question4.get_similarity(Answer(['Poutine']),\n Answer(['Steak']))\n assert similarity == 0\n\n\nclass TestAnswer:\n\n def test_is_valid(self) -> None:\n answer_x = Answer(['Jay', 'Divij'])\n answer_z = Answer(['Sannat'])\n assert answer_x.is_valid(question)\n assert answer_z.is_valid(question)\n\n def test_is_valid_2(self) -> None:\n assert answer.is_valid(question_2)\n\n def test_is_valid_3(self) -> None:\n assert answer.is_valid(question_3) is False\n assert answer_5.is_valid(question_3)\n\n def test_is_valid_4(self) -> None:\n assert answer_4.is_valid(question_4)\n\n\nclass TestSurvey:\n\n def test___len__(self) -> None:\n survey = Survey([question, question_2])\n questions = survey._questions\n assert len(questions) == 2\n survey_1 = Survey([])\n questions_1 = survey_1._questions\n assert len(questions_1) == 0\n\n def test__contains__(self) -> None:\n survey = Survey([question, question_2])\n questions = survey.get_questions()\n assert question in questions\n assert question_4 not in questions\n\n def test___str__(self) -> None:\n survey = Survey([question, question_2])\n assert \"What's your name?\" \\\n \"\" \\\n \"What's your name\"\n\n def test_get_questions(self) -> None:\n survey = Survey([question, question_2])\n assert survey.get_questions() == [question, question_2]\n\n def test__get_criterion(self) -> None:\n survey = Survey([question, question_2])\n criterion_1 = HeterogeneousCriterion()\n survey.set_criterion(criterion_1, question)\n assert survey._get_criterion(question) == criterion_1\n assert survey._get_criterion(question_2) == survey._default_criterion\n\n def test_get_weight(self) -> None:\n survey = Survey([question, question_2])\n survey.set_weight(10, question)\n assert survey._get_weight(question) == 10\n assert survey._get_weight(question_2) == survey._default_weight\n\n def test_set_weight(self) -> None:\n survey = Survey([question, question_2])\n survey.set_weight(weight, question)\n assert survey._get_weight(question) == weight\n\n def test_set_criterion(self) -> None:\n survey = Survey([question, question_2])\n criterion = HeterogeneousCriterion()\n assert survey.set_criterion(criterion, question)\n assert survey._get_criterion(question) == criterion\n\n def test_score_grouping(self) -> None:\n survey = Survey([question, question_2])\n grouping = Grouping()\n group = Group([])\n students = [student, student_1]\n group_1 = Group(students)\n grouping.add_group(group)\n assert survey.score_grouping(grouping) == 0\n\n\nclass TestHomogeneousCriterion:\n\n def test_score_answers_TestHomogeneousCriterion(self) -> None:\n criterion = HomogeneousCriterion()\n question_object = question\n answers = [Answer(True), Answer('Divij'), Answer('Sannat')]\n assert not answers[0].is_valid(question_object)\n # assert criterion.score_answers(question_object, answers) == \\\n # 'This answer is invalid'\n\n def test_score_answers_TestHomogeneousCriterion_valid(self) -> None:\n criterion_1 = HomogeneousCriterion()\n answers = [Answer(['Divij']), Answer(['Sannat']), Answer(['Divij'])]\n assert round(criterion_1.score_answers(question, answers), 2) == 0.33\n\n\nclass TestHeterogeneousCriterion:\n\n def test_score_answers_Test_Heterogeneous_Criterion(self) -> None:\n criterion = HeterogeneousCriterion()\n answers = [Answer(True), Answer(['Divij']), Answer(['Sannat'])]\n assert not answers[0].is_valid(question)\n # assert criterion.score_answers(question, answers)\n # is InvalidAnswerError\n\n def test_score_answers_Test_Heterogeneous_Criterion_valid(self) -> None:\n criterion_1 = HeterogeneousCriterion()\n answers = [Answer(['Divij']), Answer(['Sannat']), Answer(['Divij'])]\n assert round(criterion_1.score_answers(question, answers), 2) == 0.67\n\n\nclass TestLonelyMemberCriterion:\n\n def test_score_answers_Test_LonelyMemberCriterion(self) -> None:\n criterion_1 = LonelyMemberCriterion()\n answers = [Answer(['Divij']), Answer(['Sannat']),\n Answer(['Divij']), Answer(['Divij'])]\n assert round(criterion_1.score_answers(question, answers), 2) == 0.0\n\n def test_score_answers_Test_LonelyMemberCriterion_(self) -> None:\n criterion_1 = LonelyMemberCriterion()\n answers = [Answer(['Divij'])]\n assert round(criterion_1.score_answers(question, answers), 2) == 0.0\n\n\ndef test_slice_list() -> None:\n to_be_sliced = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n assert grouper.slice_list(to_be_sliced, 2) == [[1, 2], [3, 4], [5, 6],\n [7, 8], [9, 10]]\n assert grouper.slice_list(to_be_sliced, 3) == [[1, 2, 3], [4, 5, 6],\n [7, 8, 9], [10]]\n assert grouper.slice_list(to_be_sliced, 5) == [[1, 2, 3, 4, 5],\n [6, 7, 8, 9, 10]]\n\n\ndef test_windows() -> None:\n to_be_sliced = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n assert grouper.windows(to_be_sliced, 4) == [[1, 2, 3, 4], [2, 3, 4, 5],\n [3, 4, 5, 6], [4, 5, 6, 7],\n [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9, 10]]\n assert grouper.windows(to_be_sliced, 1) == [[1], [2], [3], [4], [5],\n [6], [7], [8], [9], [10]]\n assert grouper.windows(to_be_sliced, 3) == [[1, 2, 3], [2, 3, 4], [3, 4, 5],\n [4, 5, 6], [5, 6, 7], [6, 7, 8],\n [7, 8, 9], [8, 9, 10]]\n\n\nclass TestAlphaGrouper:\n\n def test_init(self) -> None:\n alpha = grouper.AlphaGrouper(1)\n assert alpha.group_size == 1\n\n def test_make_grouping(self) -> None:\n alpha = grouper.AlphaGrouper(2)\n survey = Survey([question, question_2]) # CheckBox and YesNoQuestion\n grouping = alpha.make_grouping(course, survey)\n groups = grouping.get_groups()\n\n assert groups[0].get_members() == [student, student_1]\n assert groups[1].get_members() == [student_3, student_2]\n\n\n# class TestRandomGrouper:\n# pass\n\n\nclass TestGreedyGrouper:\n\n def test_init(self) -> None:\n greedy = grouper.GreedyGrouper(2)\n assert greedy.group_size == 2\n\n def test_make_grouping(self) -> None:\n greedy = grouper.GreedyGrouper(2)\n grouping = greedy.make_grouping(course, survey_x)\n groups = grouping.get_groups()\n\n assert groups[0].get_members() == [student, student_2]\n assert groups[1].get_members() == [student_1, student_3]\n\n\nclass TestWindowGrouper:\n\n def test_init(self) -> None:\n window = grouper.WindowGrouper(2)\n assert window.group_size == 2\n\n def test_make_grouping(self) -> None:\n\n window = grouper.WindowGrouper(2)\n grouping = window.make_grouping(course, survey_x)\n groups = grouping.get_groups()\n\n assert groups[0].get_members() == [student, student_1]\n assert groups[1].get_members() == [student_2, student_3]\n\n\nclass TestGroup:\n\n def test_group___len__(self) -> None:\n\n group = grouper.Group([])\n assert group.__len__() == 0\n group_1 = grouper.Group([student_1, student_3])\n assert group_1.__len__() == 2\n\n def test_group___contains__(self) -> None:\n\n group = grouper.Group([])\n group_1 = grouper.Group([student_1, student_2])\n assert not group.__contains__(student_1)\n assert group_1.__contains__(student_1)\n\n def test_group___str__(self) -> None:\n\n group = grouper.Group([])\n group_1 = grouper.Group([student, student_1])\n string = group.__str__()\n string_1 = group_1.__str__()\n assert 'Vaibhav' not in string\n assert 'Tanuj' not in string_1\n assert 'Divij' not in string\n assert 'Sannat' in string_1\n\n def test_group_get_members(self) -> None:\n\n group = grouper.Group([student, student_1])\n members = group.get_members()\n assert members is not group\n\n for member in range(len(members)):\n assert members[member] is group._members[member]\n\n\nclass TestGrouping:\n\n def test_grouping___len__(self) -> None:\n grouping = grouper.Grouping()\n assert len(grouping) == 0\n group = grouper.Group([student, student_1])\n group_1 = grouper.Group([student_3, student_2])\n grouping.add_group(group)\n grouping.add_group(group_1)\n assert len(grouping) == 2\n\n def test_grouping___str__(self) -> None:\n\n grouping = grouper.Grouping()\n group = grouper.Group([student, student_1])\n group_1 = grouper.Group([student_2])\n group_2 = grouper.Group([student_3])\n grouping.add_group(group)\n grouping.add_group(group_2)\n\n assert 'Divij' in str(grouping)\n assert 'Sannat' in str(grouping)\n assert 'Vaibhav' not in str(grouping)\n assert 'Tanuj' in str(grouping)\n\n def test_grouping_add_group(self) -> None:\n\n grouping = grouper.Grouping()\n assert len(grouping) == 0\n group = grouper.Group([student, student_1])\n group_1 = grouper.Group([])\n assert grouping.add_group(group)\n assert not grouping.add_group(group_1)\n\n def test_grouping_get_groups(self) -> None:\n\n grouping = grouper.Grouping()\n group = grouper.Group([student, student_1])\n group_1 = grouper.Group([student_2])\n grouping.add_group(group)\n grouping.add_group(group_1)\n\n shallow_copy = grouping.get_groups()\n\n for group in shallow_copy:\n assert group is not grouping._groups\n assert group in grouping._groups\n\n\nif __name__ == \"__main__\":\n import pytest\n pytest.main(['tests.py'])\n","sub_path":"a1_v2/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":16874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"6185393","text":"from drain.step import Step\nfrom drain import util, data\n\nimport pandas as pd\nimport numpy as np\nimport logging\n\nfrom lead.model.data import LeadData\n\n\nclass LeadTransform(Step):\n \"\"\"\n This Step transforms the data for modeling by defining an outcome variable,\n performing feature selection and creating sample weights.\n \"\"\"\n def __init__(self, inputs, outcome_expr, aggregations,\n wic_sample_weight=0, exclude=[], include=[]):\n \"\"\"\n Args:\n inputs: list containing a LeadCrossValidate step\n outcome_expr: the query to perform on the auxillary information to produce an outcome variable\n aggregations: defines which of the SpacetimeAggregations to include\n and which to drop\n wic_sample_weight: optional different sample weight for wic kids\n \"\"\"\n Step.__init__(self,\n inputs=inputs,\n outcome_expr=outcome_expr,\n aggregations=aggregations,\n wic_sample_weight=wic_sample_weight, \n exclude=exclude, include=include)\n\n def run(self, X, aux, train, test):\n \"\"\"\n Args:\n X: full feature matrix, including both training and test sets\n aux: auxillary information, aligned with X\n train: boolean series to mask training, aligned with X\n test: boolean series to mask testing, aligned with X\n\n \"\"\"\n y = aux.eval(self.outcome_expr)\n\n logging.info('Selecting aggregations')\n aggregations = self.get_input(LeadData).aggregations\n for a, args in self.aggregations.iteritems():\n X = aggregations[a].select(X, args, inplace=True)\n\n logging.info('Selecting features')\n X = data.select_features(X, exclude=self.exclude, \n include=self.include)\n\n sample_weight = 1 + (aux.wic * self.wic_sample_weight)\n\n c = data.non_numeric_columns(X)\n if len(c) > 0:\n logging.warning('Non-numeric columns: %s' % c)\n\n return {'X': X, 'y': y, \n 'train': train, 'test': test, \n 'aux': aux, 'sample_weight': sample_weight}\n","sub_path":"lead/model/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"185905650","text":"# -*- coding: utf-8 -*-\n\"\"\"\nDjango settings for hackconf project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/dev/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/dev/ref/settings/\n\"\"\"\nfrom __future__ import absolute_import, unicode_literals\nfrom django.utils.translation import ugettext_lazy as _\n\nimport environ\n\ngettext = lambda s: s\n\nROOT_DIR = environ.Path(__file__) - 3 # (hackconf/config/settings/common.py - 3 = hackconf/)\nAPPS_DIR = ROOT_DIR.path('hackconf')\n\nenv = environ.Env()\n\n# APP CONFIGURATION\n# ------------------------------------------------------------------------------\nDJANGO_APPS = (\n # Default Django apps:\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.auth',\n 'django.contrib.sitemaps',\n 'cms',\n 'menus',\n 'sekizai',\n 'treebeard',\n 'easy_thumbnails',\n 'djangocms_admin_style',\n 'djangocms_text_ckeditor',\n 'djangocms_style',\n 'djangocms_column',\n 'cmsplugin_filer_image',\n 'cmsplugin_filer_file',\n 'cmsplugin_filer_folder',\n 'cmsplugin_filer_teaser',\n 'cmsplugin_filer_utils',\n 'cmsplugin_filer_video',\n 'djangocms_googlemap',\n 'djangocms_inherit',\n 'djangocms_link',\n 'filer',\n # 'reversion',\n # Useful template tags:\n # 'django.contrib.humanize',\n\n # Admin\n 'django.contrib.admin',\n)\nTHIRD_PARTY_APPS = (\n 'crispy_forms', # Form layouts\n)\n\n# Apps specific for this project go here.\nLOCAL_APPS = (\n # custom users app\n # Your stuff: custom apps go here\n 'hackconf',\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps\nINSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS\n\n# MIDDLEWARE CONFIGURATION\n# ------------------------------------------------------------------------------\nMIDDLEWARE_CLASSES = (\n 'django.middleware.security.SecurityMiddleware',\n 'cms.middleware.utils.ApphookReloadMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'cms.middleware.user.CurrentUserMiddleware',\n 'cms.middleware.page.CurrentPageMiddleware',\n 'cms.middleware.toolbar.ToolbarMiddleware',\n 'cms.middleware.language.LanguageCookieMiddleware'\n)\n\n# DEBUG\n# ------------------------------------------------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug\nDEBUG = env.bool('DJANGO_DEBUG', False)\n\n# FIXTURE CONFIGURATION\n# ------------------------------------------------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS\nFIXTURE_DIRS = (\n str(APPS_DIR.path('fixtures')),\n)\n\n# EMAIL CONFIGURATION\n# ------------------------------------------------------------------------------\nEMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', default='django.core.mail.backends.smtp.EmailBackend')\n\n# MANAGER CONFIGURATION\n# ------------------------------------------------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#admins\nADMINS = (\n (\"\"\"HackSoft\"\"\", 'Your email'),\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#managers\nMANAGERS = ADMINS\n\n# DATABASE CONFIGURATION\n# ------------------------------------------------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases\nDATABASES = {\n 'default': {\n 'CONN_MAX_AGE': 0,\n 'ENGINE': 'django.db.backends.sqlite3',\n 'HOST': 'localhost',\n 'NAME': 'project.db',\n 'PASSWORD': '',\n 'PORT': '',\n 'USER': ''\n }\n}\nDATABASES['default']['ATOMIC_REQUESTS'] = True\n\n\n# GENERAL CONFIGURATION\n# ------------------------------------------------------------------------------\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# In a Windows environment this must be set to your system time zone.\nTIME_ZONE = 'UTC'\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code\n# LANGUAGE_CODE = 'en-us'\nLANGUAGE_CODE = 'en'\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id\nSITE_ID = 1\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n\nUSE_I18N = True\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n\nUSE_L10N = True\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz\nUSE_TZ = True\n\n# TEMPLATE CONFIGURATION\n# ------------------------------------------------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#templates\nTEMPLATES = [\n {\n # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs\n 'DIRS': [\n str(APPS_DIR.path('templates')),\n ],\n 'OPTIONS': {\n # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug\n 'debug': DEBUG,\n # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders\n # https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types\n 'loaders': [\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n 'django.template.loaders.eggs.Loader'\n ],\n # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors\n 'context_processors': [\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n 'django.core.context_processors.i18n',\n 'django.core.context_processors.debug',\n 'django.core.context_processors.request',\n 'django.core.context_processors.media',\n 'django.core.context_processors.csrf',\n 'django.core.context_processors.tz',\n 'sekizai.context_processors.sekizai',\n 'django.core.context_processors.static',\n 'cms.context_processors.cms_settings'\n ],\n },\n },\n]\n\n# See: http://django-crispy-forms.readthedocs.io/en/latest/install.html#template-packs\nCRISPY_TEMPLATE_PACK = 'bootstrap3'\n\n# STATIC FILE CONFIGURATION\n# ------------------------------------------------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root\nSTATIC_ROOT = str(ROOT_DIR('staticfiles'))\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url\nSTATIC_URL = '/static/'\n\n# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS\nSTATICFILES_DIRS = (\n str(APPS_DIR.path('static')),\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n)\n\n# MEDIA CONFIGURATION\n# ------------------------------------------------------------------------------\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root\nMEDIA_ROOT = str(ROOT_DIR('media'))\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url\nMEDIA_URL = '/media/'\n\n# URL Configuration\n# ------------------------------------------------------------------------------\nROOT_URLCONF = 'config.urls'\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application\nWSGI_APPLICATION = 'config.wsgi.application'\n\n# SLUGLIFIER\nAUTOSLUG_SLUGIFY_FUNCTION = 'slugify.slugify'\n\n\n# django-compressor\n# ------------------------------------------------------------------------------\n\n\n# Location of root django.contrib.admin URL, use {% url 'admin:index' %}\nADMIN_URL = r'^admin/'\n\n\n# Your common stuff: Below this line define 3rd party library settings\nLANGUAGES = (\n # Customize this\n ('en', gettext('en')),\n)\n\nCMS_LANGUAGES = {\n # Customize this\n 'default': {\n 'redirect_on_fallback': True,\n 'hide_untranslated': False,\n 'public': True,\n },\n 1: [\n {\n 'code': 'en',\n 'redirect_on_fallback': True,\n 'hide_untranslated': False,\n 'name': gettext('en'),\n 'public': True,\n },\n ],\n}\n\nCMS_TEMPLATES = (\n ('home_page_template.html', 'Home Page Template'),\n)\n\nCMS_PERMISSION = True\n\nCMS_PLACEHOLDER_CONF = {}\n\nTHUMBNAIL_PROCESSORS = (\n 'easy_thumbnails.processors.colorspace',\n 'easy_thumbnails.processors.autocrop',\n 'filer.thumbnail_processors.scale_and_crop_with_subject_location',\n 'easy_thumbnails.processors.filters'\n)\n\nCMS_STYLE_NAMES = (\n ('info', _(\"info\")),\n ('new', _(\"new\")),\n ('hint', _(\"hint\")),\n ('section', _(\"section\")),\n)\n\nTEXT_ADDITIONAL_TAGS = ('iframe',)\nTEXT_ADDITIONAL_ATTRIBUTES = ('scrolling', 'allowfullscreen', 'frameborder', 'src', 'height', 'width')\n\nfrom .local import *\n","sub_path":"config/settings/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":9576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"403602428","text":"\ndef is_valid(s):\n idx1 = s.find('_')\n idx2 = s.find('.')\n if idx1 != 3 or idx2 != 14:\n return False\n # check topic\n topic = s[:idx1]\n if len(topic) != 3 or topic[0] != 't' or not topic[1].isnumeric() or not topic[2].isnumeric():\n return False\n # check student id\n id = s[idx1+1: idx2]\n if len(id) != 10:\n return False\n for c in id:\n if not c.isnumeric():\n return False\n # check file extension\n ext = s[idx2:]\n if ext != '.tar':\n return False\n return True\n\n\nif __name__ == '__main__':\n r = is_valid('t05_6210112341.tar')\n print(r)\n print(type(r))\n r = is_valid('t5_621011234-1.zip')\n print(r)\n r = is_valid('T5_621011234-1.zip')\n print(r)\n","sub_path":"Lab/Computer Programming/L05/files/P10.py","file_name":"P10.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"502820457","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Wei, Shuowen\n\nhttps://leetcode.com/problems/binary-tree-level-order-traversal/\n\n\"\"\"\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def levelOrder(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n if not root:\n return [] \n currentLevel = [root]\n returnVal = [[root.val]]\n while currentLevel: \n nextLevel = [] \n for n in currentLevel:\n if n.left:\n nextLevel.append(n.left)\n if n.right:\n nextLevel.append(n.right)\n if nextLevel:\n returnVal.append([i.val for i in nextLevel]) \n currentLevel = nextLevel\n \n return returnVal\n ","sub_path":"Easy/LC102BinaryTreeLevelOrderTraversal.py","file_name":"LC102BinaryTreeLevelOrderTraversal.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"50235284","text":"# Gabriel S. Ehrlich\r\n# 28 September 2015\r\n# gabriel.s.ehrlich@gmail.com\r\n\r\n\"\"\"Pull together measurement widgets into the same program\r\n\r\nThis module cobbles together the control, acquisition, and data-viewing\r\nwidgets defined in cam_full:\r\n- init_w: initialization, temperature control, and closing the camera\r\n gracefully. On startup of cam_full, this is the only widget\r\n visible. When the camera is initialized, the rest will start up.\r\n- start_w: setting acquisition parameters and starting/stopping the\r\n acquisition.\r\n- rms_w: display of the root-mean-square of the probe-only spectra.\r\n- ratio_w: display of the probe-only/pump-probe spectrum ratio.\r\n- probe_only_w and pump_probe_w: display of the respective raw spectra.\r\n\"\"\"\r\n\r\nimport cam_control, acq_control, rms, ratio\r\nfrom andor.andorcamera import newton, idus\r\nfrom PyQt4 import QtGui as gui\r\nfrom plotter import PlotterWidget, AvgPlotter\r\n\r\ncam = newton\r\n\r\ndef start_the_rest(acquiring):\r\n \"\"\"Start widgets that need the camera to be initialized to work\"\"\"\r\n global start_w, rms_w, ratio_w, probe_only_w, pump_probe_w\r\n reload(acq_control)\r\n reload(rms)\r\n reload(ratio)\r\n\r\n start_w = acq_control.AcquisitionWidget(cam, acquiring=acquiring)\r\n start_w.show()\r\n\r\n rms_w = PlotterWidget(rms.RmsPlotter, \"RMS/mean counts\",\r\n cam.x, start_w.new_probe_only)\r\n rms_w.show()\r\n start_w.startDisplay.connect(rms_w.startAcq)\r\n start_w.abortDisplay.connect(rms_w.abortAcq)\r\n\r\n ratio_w = PlotterWidget(ratio.RatioPlotter, \"Probe-only/pump-probe counts\",\r\n cam.x, start_w.new_probe_only, start_w.new_pump_probe)\r\n ratio_w.show()\r\n start_w.startDisplay.connect(ratio_w.startAcq)\r\n start_w.abortDisplay.connect(ratio_w.abortAcq)\r\n\r\n probe_only_w = PlotterWidget(AvgPlotter, \"Probe only\",\r\n cam.x, start_w.new_probe_only)\r\n probe_only_w.show()\r\n start_w.startDisplay.connect(probe_only_w.startAcq)\r\n start_w.abortDisplay.connect(probe_only_w.abortAcq)\r\n\r\n pump_probe_w = PlotterWidget(AvgPlotter, \"Pump-probe\",\r\n cam.x, start_w.new_pump_probe)\r\n pump_probe_w.show()\r\n start_w.startDisplay.connect(pump_probe_w.startAcq)\r\n start_w.abortDisplay.connect(pump_probe_w.abortAcq)\r\n\r\ndef close_the_rest():\r\n \"\"\"Remotely close the widgets that are not cam_control\"\"\"\r\n start_w.close()\r\n rms_w.close()\r\n ratio_w.close()\r\n probe_only_w.close()\r\n pump_probe_w.close()\r\n\r\nif __name__ == \"__main__\":\r\n app = gui.QApplication([])\r\n init_w = cam_control.CameraControlWidget(cam)\r\n init_w.show()\r\n init_w.cam_initialize_done.connect(start_the_rest)\r\n init_w.cam_shut_down.connect(close_the_rest)\r\n app.exec_()","sub_path":"code/cam_full/cam_full.py","file_name":"cam_full.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"218284004","text":"\"\"\"\nСоздает файл с тестовой базой, содержащий шаблоны форм.\n\"\"\"\n\nfrom tinydb import TinyDB\n\nif __name__ == '__main__':\n db = TinyDB('db.json')\n db.purge()\n db.insert({'ftname': 'OrderForm', 'user_name': 'text', 'order_date': 'date', 'user_email': 'email'})\n db.insert({'ftname': 'BatmanForm', 'first_name': 'text', 'age': 'text', 'birth_date': 'date'})\n db.insert({'ftname': 'ContactForm', 'user_name': 'text', 'user_email': 'email', 'user_phone': 'phone'})","sub_path":"db_init.py","file_name":"db_init.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"67508423","text":"from db import cursor\nfrom toaccount import *\n\ndef get_from_db():\n\tactive_people_per_day = \"\"\"select convert(varchar,timestamp, 23) as day ,count(distinct fromaccount)\nfrom trade \nwhere convert(varchar,timestamp, 108) between '10:30:00' and '13:00:00'\ngroup by convert(varchar,timestamp, 23) \norder by day\n\"\"\"\n\tcursor.execute(active_people_per_day)\n\tres=cursor.fetchall()\n\treturn res\n\ndef get_from_db_per_group(group):\n\tactive_people_per_group = \"\"\"select convert(varchar,timestamp, 23) as day ,count(distinct fromaccount)\nfrom trade \nwhere toaccount in %s and convert(varchar,timestamp, 108) between '10:30:00' and '13:00:00'\ngroup by convert(varchar,timestamp, 23) \norder by day\n\"\"\"%str(group)\n\tcursor.execute(active_people_per_group)\n\tres=cursor.fetchall()\n\treturn res\n\ndef list_to_dict(lst):#[(1,2),(a,b),...]=>{1:2,a:b}\n\td = dict()\n\tfor i in lst:\n\t\td[i[0]]=i[1]\n\treturn d\n\nwith open(\"../../gen/active_people_count/per_lunch.csv\",\"w\") as f:\n\tper_day_list = get_from_db()\n\tper_day_dict = list_to_dict(per_day_list)\n\n\tactive1 = get_from_db_per_group(account_1)\n\tactive1 = list_to_dict(active1)\n\t# print (per_day_dict)\n\tactive2 = get_from_db_per_group(account_2)\n\tactive2 = list_to_dict(active2)\n\tactive3 = get_from_db_per_group(account_3)\n\tactive3 = list_to_dict(active3)\n\tactive4 = get_from_db_per_group(account_4)\n\tactive4 = list_to_dict(active4)\n\tactive5 = get_from_db_per_group(account_5)\n\tactive5 = list_to_dict(active5)\n\tactive6 = get_from_db_per_group(account_6)\n\tactive6 = list_to_dict(active6)\n\t#title\n\tf.write(\"day,all,1,2,3,4,5,6\\n\")\n\tfor i in per_day_list:\n\t\tday = i[0]\n\t\tcount0=per_day_dict.get(day,0)\n\t\tcount1=active1.get(day,0)\n\t\tcount2=active2.get(day,0)\n\t\tcount3=active3.get(day,0)\n\t\tcount4=active4.get(day,0)\n\t\tcount5=active5.get(day,0)\n\t\tcount6=active6.get(day,0)\n\t\tprint(count0,count1)\n\t\tf.write(\"%s,%d,%d,%d,%d,%d,%d,%d\\n\"%(day,count0,count1,count2,count3,count4,count5,count6\n\t\t\t))\ncursor.close()\n","sub_path":"code/py/active_people_per_lunch.py","file_name":"active_people_per_lunch.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"378332072","text":"# -*- coding: utf-8 -*-\n# PyXBMCt framework module\n#\n# PyXBMCt is a mini-framework for creating Kodi (XBMC) Python addons\n# with arbitrary UI made of Controls - decendants of xbmcgui.Control class.\n# The framework uses image textures from Kodi Confluence skin.\n#\n# Licence: GPL v.3 \n\"\"\"\nThis module contains all the Window classes of the PyXBMCt framework\n\"\"\"\n\nfrom __future__ import absolute_import, division, unicode_literals\nimport inspect\nfrom abc import ABCMeta, abstractmethod\nfrom .addonskin import skin\nfrom .abstractgrid import AbstractGrid\nfrom .addoncontrols import Button, List, RadioButton\nfrom .addonwindowerror import AddonWindowError\nfrom .kodiconstants import KEY_BUTTON_A, ACTION_PREVIOUS_MENU, ACTION_MOUSE_LEFT_CLICK\nfrom .xbmc4xbox import isXBMC4XBOX\n\n_XBMC4XBOX = isXBMC4XBOX()\n\n# typing module only needed when running pytype and is not available on XBMC4XBOX AFAIK\ntry:\n import typing\nexcept:\n pass\n\n# kodi_six doesn't work on XBMC4XBOX\nif _XBMC4XBOX:\n import xbmcgui\nelse:\n from .addoncontrols import Slider, Edit\n from six.moves import range\n from kodi_six import xbmcgui\n from six import with_metaclass\n\n\nclass AbstractWindow(AbstractGrid if _XBMC4XBOX else with_metaclass(ABCMeta, AbstractGrid)):\n \"\"\"\n Top-level control window.\n\n The control windows serves as a parent widget for other XBMC UI controls\n much like Tkinter.Tk or PyQt QWidget class.\n\n This class is a basic \"skeleton\" for a control window.\n\n .. warning:: This is an abstract class and is not supposed to be instantiated directly!\n \"\"\"\n\n if _XBMC4XBOX:\n __metaclass__ = ABCMeta\n\n def __init__(self):\n self._controls = [] # type: typing.List[xbmcgui.Control]\n self._actions_connected = [] # type: typing.List[typing.Tuple[typing.Union[int, xbmcgui.Control], typing.List[typing.Callable]]]\n self._controls_connected = [] # type: typing.List[typing.Tuple[typing.Union[int, xbmcgui.Control], typing.List[typing.Callable]]]\n # Need access to this class and this is not easy to obtain\n # as it is not the superclass of this one\n self._XBMCWindowClass = None\n for ancestor in inspect.getmro(self.__class__):\n if inspect.getmodule(ancestor) == inspect.getmodule(xbmcgui):\n self._XBMCWindowClass = ancestor\n # break\n if self._XBMCWindowClass is None:\n raise AddonWindowError(\"Could not find Window parent class\")\n\n def getWindow(self):\n return self\n\n def autoNavigation(self, vertical_wrap_around=True,\n horizontal_wrap_around=True, include_disabled=False,\n include_invisible=False, controls_subset=None,\n control_types=(Button, List, RadioButton) if _XBMC4XBOX \\\n else (Button, List, RadioButton, Slider, Edit)):\n \"\"\"\n Automatically setup the navigation between controls in the Window\n\n :param vertical_wrap_around: if you navigate up from the topmost control it will take you to the bottommost control\n :param horizontal_wrap_around: if you navigate down from the bottommost control it will take you to the topmost control\n :param include_disabled: include controls that are disabled\n :param include_invisible: include controls that are currently not visible\n :param controls_subset: pass in a specific set of controls to set up the navigation for (only these controls will be effacted and then can will only be set up to navigate to each other)\n :param control_types: the types of controls to consider for the navigation\n \"\"\"\n # type: (bool, bool, bool, bool, typing.Iterable[xbmcgui.Control], typing.Tuple[typing.Any, ...]) -> None\n if controls_subset is None:\n controls = self._controls\n else:\n controls = controls_subset\n\n controls = [c for c in controls if \\\n (control_types == None or isinstance(c, control_types)) and \\\n (include_disabled or c.isEnabled()) and \\\n (include_invisible or c.isVisible())]\n\n # Note: coordinates are measured from the top left of the window\n # and a controls coordinates refer to its top left corner\n\n for control in controls:\n nearest_left = None\n nearest_right = None\n nearest_up = None\n nearest_down = None\n\n wrap_around_move_left = None\n wrap_around_move_right = None\n wrap_around_move_down = None\n wrap_around_move_up = None\n\n control_x = control.getX()\n control_y = control.getY()\n control_midpoint_x, control_midpoint_y = control.getMidpoint()\n control_width = control.getWidth()\n control_height = control.getHeight()\n\n for neighbour in controls:\n neighbour_x = neighbour.getX()\n neighbour_y = neighbour.getY()\n neighbour_midpoint_x, neighbour_midpoint_y = neighbour.getMidpoint()\n neighbour_midpoint_x_dif = abs(neighbour_midpoint_x - control_midpoint_x)\n neighbour_midpoint_y_dif = abs(neighbour_midpoint_y - control_midpoint_y)\n\n # Ensure that the neighbour is not too high or low\n if neighbour_y < control_y + control_height and neighbour_y + neighbour.getHeight() > control_y:\n if neighbour_x < control_x and (nearest_left == None or nearest_left_x < neighbour_x or (\n nearest_left_x == neighbour_x and neighbour_midpoint_y_dif < nearest_left_midpoint_y_dif)):\n nearest_left = neighbour\n nearest_left_x = neighbour_x\n nearest_left_midpoint_y_dif = neighbour_midpoint_y_dif\n elif neighbour_x > control_x and (nearest_right == None or nearest_right_x > neighbour_x or (\n nearest_right_x == neighbour_x and neighbour_midpoint_y_dif < nearest_right_midpoint_y_dif)):\n nearest_right = neighbour\n nearest_right_x = neighbour_x\n nearest_right_midpoint_y_dif = neighbour_midpoint_y_dif\n\n if horizontal_wrap_around:\n # check if nearest_left/right is none as if a suitable\n # control to the left or right has been found there will\n # be no wrap around\n if nearest_left == None and neighbour_x > control_x and (\n wrap_around_move_left == None or wrap_around_move_left_x < neighbour_x or (\n wrap_around_move_left_x == neighbour_x and neighbour_midpoint_y_dif < wrap_around_move_left_midpoint_y_dif)):\n wrap_around_move_left = neighbour\n wrap_around_move_left_x = neighbour_x\n wrap_around_move_left_midpoint_y_dif = neighbour_midpoint_y_dif\n elif nearest_right == None and neighbour_x < control_x and (\n wrap_around_move_right == None or wrap_around_move_right_x > neighbour_x or (\n wrap_around_move_right_x == neighbour_x and neighbour_midpoint_y_dif < wrap_around_move_right_midpoint_y_dif)):\n wrap_around_move_right = neighbour\n wrap_around_move_right_x = neighbour_x\n wrap_around_move_right_midpoint_y_dif = neighbour_midpoint_y_dif\n\n if neighbour_x < control_x + control_width and neighbour_x + neighbour.getWidth() > control_x:\n if neighbour_y > control_y and (nearest_down == None or nearest_down_y > neighbour_y or (\n nearest_down_y == neighbour_y and neighbour_midpoint_x_dif < nearest_down_midpoint_x_dif)):\n nearest_down = neighbour\n nearest_down_midpoint_x_dif = neighbour_midpoint_x_dif\n nearest_down_y = neighbour_y\n elif neighbour_y < control_y and (nearest_up == None or nearest_up_y < neighbour_y or (\n nearest_up_y == neighbour_y and neighbour_midpoint_x_dif < nearest_up_midpoint_x_dif)):\n nearest_up = neighbour\n nearest_up_midpoint_x_dif = neighbour_midpoint_x_dif\n nearest_up_y = neighbour_y\n\n if vertical_wrap_around:\n if nearest_down == None and neighbour_y < control_y and (\n wrap_around_move_down == None or wrap_around_move_down_y > neighbour_y or (\n wrap_around_move_down_y == neighbour_y and neighbour_midpoint_x_dif < wrap_around_move_down_midpoint_x_dif)):\n wrap_around_move_down = neighbour\n wrap_around_move_down_midpoint_x_dif = neighbour_midpoint_x_dif\n wrap_around_move_down_y = neighbour_y\n elif nearest_up == None and neighbour_y > control_y and (\n wrap_around_move_up == None or wrap_around_move_up_y < neighbour_y or (\n wrap_around_move_up_y == neighbour_y and neighbour_midpoint_x_dif < wrap_around_move_up_midpoint_x_dif)):\n wrap_around_move_up = neighbour\n wrap_around_move_up_midpoint_x_dif = neighbour_midpoint_x_dif\n wrap_around_move_up_y = neighbour_y\n\n if nearest_left:\n control.controlLeft(nearest_left)\n elif wrap_around_move_left:\n control.controlLeft(wrap_around_move_left)\n\n if nearest_right:\n control.controlRight(nearest_right)\n elif wrap_around_move_right:\n control.controlRight(wrap_around_move_right)\n\n if nearest_down:\n control.controlDown(nearest_down)\n elif wrap_around_move_down:\n control.controlDown(wrap_around_move_down)\n\n if nearest_up:\n control.controlUp(nearest_up)\n elif wrap_around_move_up:\n control.controlUp(wrap_around_move_up)\n\n def setGeometry(self, width_, height_, rows_, columns_, pos_x=-1, pos_y=-1):\n \"\"\"\n Set width, height, Grid layout, and coordinates (optional) for a new control window.\n\n :param width_: widgh of the created window.\n :param height_: height of the created window.\n :param rows_: # rows of the Grid layout to place controls on.\n :param columns_: # colums of the Grid layout to place controls on.\n :param pos_x: (opt) x coordinate of the top left corner of the window.\n :param pos_y: (opt) y coordinates of the top left corner of the window.\n\n If pos_x and pos_y are not privided, the window will be placed\n at the center of the screen.\n\n Example::\n\n self.setGeometry(400, 500, 5, 4)\n \"\"\"\n # type: (int, int, int, int, int, int) -> None\n self._width = width_\n self._height = height_\n self.rows = rows_\n self.columns = columns_\n if pos_x > 0 and pos_y > 0:\n self.x = pos_x\n self.y = pos_y\n else:\n self.x = 640 - width_ // 2\n self.y = 360 - height_ // 2\n\n def getRows(self):\n \"\"\"\n Get grid rows count.\n\n :raises: :class:`AddonWindowError` if a grid has not yet been set.\n \"\"\"\n # type: () -> int\n try:\n return self.rows # pytype: disable=attribute-error\n except AttributeError:\n raise AddonWindowError('Grid layout is not set! Call setGeometry first.')\n\n def getColumns(self):\n \"\"\"\n Get grid columns count.\n\n :raises: :class:`AddonWindowError` if a grid has not yet been set.\n \"\"\"\n # type: () -> int\n try:\n return self.columns # pytype: disable=attribute-error\n except AttributeError:\n raise AddonWindowError('Grid layout is not set! Call setGeometry first.')\n\n def getX(self):\n \"\"\"Get X coordinate of the top-left corner of the window.\"\"\"\n # type: () -> int\n try:\n return self.x # pytype: disable=attribute-error\n except AttributeError:\n raise AddonWindowError('Window geometry is not defined! Call setGeometry first.')\n\n def getY(self):\n \"\"\"Get Y coordinate of the top-left corner of the window.\"\"\"\n # type: () -> int\n try:\n return self.y # pytype: disable=attribute-error\n except AttributeError:\n raise AddonWindowError('Window geometry is not defined! Call setGeometry first.')\n\n def getWindowWidth(self):\n \"\"\"Get window width.\"\"\"\n # type: () -> int\n try:\n return self._width # pytype: disable=attribute-error\n except AttributeError:\n raise AddonWindowError('Window geometry is not defined! Call setGeometry first.')\n\n def getWindowHeight(self):\n \"\"\"Get window height.\"\"\"\n # type: () -> int\n try:\n return self._height # pytype: disable=attribute-error\n except AttributeError:\n raise AddonWindowError('Window geometry is not defined! Call setGeometry first.')\n\n def connect(self, event, callback):\n \"\"\"\n Connect an event to a function.\n\n :param event: event to be connected.\n :param callback: callback object the event is connected to.\n\n An event can be an instance of a Control object or an integer key action code.\n Several basic key action codes are provided by PyXBMCt. ``xbmcgui`` module\n provides more action codes.\n\n You can connect the following Controls: :class:`Button`, :class:`RadioButton`\n and :class:`List`. Other Controls do not generate any control events when activated\n so their connections won't work.\n\n To catch :class:`Slider` events you need to connect the following key actions:\n ``ACTION_MOVE_LEFT``, ``ACTION_MOVE_RIGHT`` and ``ACTION_MOUSE_DRAG``, and do a check\n whether the ``Slider`` instance is focused.\n\n ``callback`` parameter is a function or a method to be executed on when the event is fired.\n\n .. warning:: For connection you must provide a function object without brackets ``()``,\n not a function call!\n\n ``lambda`` can be used as to call another function or method with parameters known at runtime.\n\n Examples::\n\n self.connect(self.exit_button, self.close)\n\n or::\n\n self.connect(ACTION_NAV_BACK, self.close)\n \"\"\"\n # type: (typing.Union[int, xbmcgui.Control], typing.Callable) -> None\n\n if isinstance(event, int):\n connect_list = self._actions_connected\n else: # Event is actually a control\n if hasattr(event, \"_connectCallback\"):\n # Only connect the event if it returns true\n # or a new callable.\n should_connect = event._connectCallback(callback, self)\n if callable(should_connect):\n callback = should_connect\n elif not should_connect:\n return\n connect_list = self._controls_connected\n try:\n entry = next(entry for entry in connect_list if entry[0] == event)\n\n entry[1].append(callback)\n except:\n connect_list.append((event, [callback]))\n\n def connectEventList(self, events, callback):\n \"\"\"\n Connect a list of controls/action codes to a function.\n\n See :meth:`connect` docstring for more info.\n \"\"\"\n # type: (typing.List[typing.Union[int, xbmcgui.Control]], typing.Callable) -> None\n for event in events:\n self.connect(event, callback)\n\n def disconnect(self, event, callback=None):\n \"\"\"\n Disconnect an event from a function.\n\n An event can be an inctance of a Control object or an integer key action code\n which has previously been connected to a function or a method.\n\n :param event: event to be disconnected.\n :param callback: callback related to the event to be disconnected (if None then all callbacks are disconnected).\n :raises: :class:`AddonWindowError` if an event is not connected to any function.\n\n Examples::\n\n self.disconnect(self.exit_button)\n\n or::\n\n self.disconnect(ACTION_NAV_BACK)\n \"\"\"\n # type: (typing.Union[int, xbmcgui.Control], typing.Callable) -> None\n if isinstance(event, int):\n event_list = self._actions_connected\n else:\n event_list = self._controls_connected\n\n for event_index in range(len(event_list)):\n if event == event_list[event_index][0]:\n if callback == None:\n event_list.pop(event_index)\n return\n else:\n callback_list = event_list[event_index][1]\n for callback_index in range(len(callback_list)):\n if callback == callback_list[callback_index]:\n if len(callback_list) == 1:\n event_list.pop(event_index)\n else:\n callback_list.pop(callback_index) # pytype: disable=attribute-error\n return # May leave an empty list\n raise AddonWindowError('The action or control %s is not connected to function! %s' %\n (str(event), str(callback)))\n\n raise AddonWindowError('The action or control %s is not connected!' % str(event))\n\n def disconnectEventList(self, events, callback=None):\n \"\"\"\n Disconnect a list of controls/action codes from functions.\n\n See :func:`disconnect` docstring for more info.\n\n :param events: the list of events to be disconnected.\n :param callback: callback related to each of the events to be disconnected (if None then all callbacks are disconnected).\n :raises: :class:`AddonWindowError` if at least one event in the list\n is not connected to any function.\n \"\"\"\n # type: (typing.Iterable[typing.Union[int, xbmcgui.Control]], typing.Callable) -> None\n for event in events:\n self.disconnect(event, callback)\n\n def _executeConnected(self, event, connected_list):\n \"\"\"\n Execute a connected event (an action or a control).\n\n This is a helper method not to be called directly.\n \"\"\"\n # type: (typing.Union[int, xbmcgui.Control], typing.List[typing.Tuple[typing.Union[int, xbmcgui.Control], typing.List[typing.Callable]]]) -> None\n for item in connected_list:\n if item[0] == event:\n for callback in item[1]:\n callback()\n break\n\n def setAnimation(self, control):\n \"\"\"\n Set animation for control\n\n :param control: control for which animation is set.\n\n This method is called automatically to set animation properties for all controls\n added to the current addon window instance -- both for built-in controls\n (window background, title bar etc.) and for controls added with :meth:`placeControl`.\n\n It receives a control instance as the 2nd positional argument (besides ``self``).\n By default the method does nothing, i.e. no animation is set for controls.\n To add animation you need to re-implement this method in your child class.\n\n E.g::\n\n def setAnimation(self, control):\n control.setAnimations([('WindowOpen', 'effect=fade start=0 end=100 time=1000',),\n ('WindowClose', 'effect=fade start=100 end=0 time=1000',)])\n \"\"\"\n # type: (xbmcgui.Control) -> None\n pass\n\n def setFocus(self, control):\n # type: (xbmcgui.Control) -> None\n do_set_focus = True\n if hasattr(control, '_focusedCallback'):\n do_set_focus = control._focusedCallback()\n if do_set_focus:\n self._XBMCWindowClass.setFocus(self, control)\n\n def onFocus(self, control):\n \"\"\"\n Catch focused controls.\n\n :param control: is an instance of :class:`xbmcgui.Control` class.\n \"\"\"\n # type: (xbmcgui.Control) -> None\n if hasattr(control, '_focusedCallback'):\n control._focusedCallback()\n\n def addControl(self, control):\n \"\"\"\n Wrapper for xbmcgui.Window.addControl.\n\n :param control: the control to add.\n\n .. note:: In most circumstances you should use placeControl.\n .. note:: Only use this method if want to to place and element in a Group it using pixel coordinates\n\n Example::\n\n window.addControls(label)\n \"\"\"\n # type: (xbmcgui.Control) -> None\n self._controls.append(control)\n self._XBMCWindowClass.addControl(self, control)\n\n def addControls(self, controls):\n \"\"\"\n Wrapper for xbmcgui.Window.addControls.\n\n :param controls: iterable containing the controls to add.\n\n .. note:: In most circumstances you should use placeControl.\n .. note:: Only use this method if want to to place and element in a Group it using pixel coordinates\n\n Example::\n\n window.addControls([label, button])\n \"\"\"\n # type: (typing.Iterable[xbmcgui.Control]) -> None\n # addControls is not directly available on XBMC4XBOX\n # so this implementation is the most portable\n for control in controls:\n self.addControl(control)\n\n def removeControl(self, control):\n \"\"\"\n Remove a control from the window grid layout.\n\n :param control: control instance to be removed from the grid.\n\n Example::\n\n self.removeControl(self.label)\n \"\"\"\n # type: (xbmcgui.Control) -> None\n if hasattr(control, \"_removedCallback\"):\n control._removedCallback(self)\n self._XBMCWindowClass.removeControl(self, control)\n\n def removeControls(self, controls):\n \"\"\"\n Remove multiple controls from the window grid layout.\n\n :param controls: an iterable of control instances to be removed from the grid.\n\n Example::\n\n self.removeControl(self.label)\n \"\"\"\n # type: (typing.Iterable[xbmcgui.Control]) -> None\n for control in controls:\n self.removeControl(control)\n\n def onAction(self, action):\n \"\"\"\n Catch button actions.\n\n :param action: an instance of :class:`xbmcgui.Action` class.\n \"\"\"\n # type: (xbmcgui.Action) -> None\n if action == ACTION_PREVIOUS_MENU:\n self.close() # pytype: disable=attribute-error\n # On control is not called on XBMC4XBOX for subclasses of the built in\n # controls. However onAction is.\n elif _XBMC4XBOX and hasattr(action, 'getButtonCode') and action.getButtonCode() in (\n KEY_BUTTON_A, ACTION_MOUSE_LEFT_CLICK):\n control = self.getFocus() # pytype: disable=attribute-error\n if isinstance(control, (Button, RadioButton, List)) and control.isEnabled():\n self.onControl(control)\n else:\n self._executeConnected(action, self._actions_connected)\n\n def onControl(self, control):\n \"\"\"\n Catch activated controls.\n\n :param control: is an instance of :class:`xbmcgui.Control` class.\n \"\"\"\n # type: (xbmcgui.Control) -> None\n self._executeConnected(control, self._controls_connected)\n\n\nclass AddonWindow(AbstractWindow):\n \"\"\"\n Top-level control window.\n\n The control windows serves as a parent widget for other XBMC UI controls\n much like ``Tkinter.Tk`` or PyQt ``QWidget`` class.\n This is an abstract class which is not supposed to be instantiated directly\n and will raise exeptions. It is designed to be implemented in a grand-child class\n with the second inheritance from ``xbmcgui.Window`` or ``xbmcgui.WindowDialog``\n in a direct child class.\n\n This class provides a control window with a background and a header\n similar to top-level widgets of desktop UI frameworks.\n\n .. warning:: This is an abstract class and is not supposed to be instantiated directly!\n \"\"\"\n\n def __init__(self, title=''):\n \"\"\"Constructor method.\"\"\"\n # type: (str) -> None\n super(AddonWindow, self).__init__()\n self._setFrame(title)\n\n def onControl(self, control):\n \"\"\"\n Catch activated controls.\n\n :param control: is an instance of :class:`xbmcgui.Control` class.\n \"\"\"\n # type: (xbmcgui.Control) -> None\n if (hasattr(self, 'window_close_button') and\n control.getId() == self.window_close_button.getId()):\n self.close() # pytype: disable=attribute-error\n else:\n super(AddonWindow, self).onControl(control)\n\n def _setFrame(self, title):\n \"\"\"\n Set window frame\n\n Define paths to images for window background and title background textures,\n and set control position adjustment constants used in setGrid.\n\n This is a helper method not to be called directly.\n \"\"\"\n # type: (str) -> None\n # Window background image\n self.background_img = skin.background_img\n # Background for a window header\n self.title_background_img = skin.title_background_img\n self.background = xbmcgui.ControlImage(-10, -10, 1, 1, self.background_img)\n self.addControl(self.background)\n self.setAnimation(self.background)\n self.title_background = xbmcgui.ControlImage(-10, -10, 1, 1, self.title_background_img)\n self.addControl(self.title_background)\n self.setAnimation(self.title_background)\n self.title_bar = xbmcgui.ControlLabel(-10, -10, 1, 1, title, alignment=skin.header_align,\n textColor=skin.header_text_color, font='font13_title')\n self.addControl(self.title_bar)\n self.setAnimation(self.title_bar)\n self.window_close_button = xbmcgui.ControlButton(-100, -100, skin.close_btn_width, skin.close_btn_height, '',\n focusTexture=skin.close_button_focus,\n noFocusTexture=skin.close_button_no_focus)\n self.addControl(self.window_close_button)\n self.setAnimation(self.window_close_button)\n\n def setGeometry(self, width_, height_, rows_, columns_, pos_x=-1, pos_y=-1, padding=5):\n \"\"\"\n Set width, height, Grid layout, and coordinates (optional) for a new control window.\n\n :param width_: new window width in pixels.\n :param height_: new window height in pixels.\n :param rows_: # of rows in the Grid layout to place controls on.\n :param columns_: # of colums in the Grid layout to place controls on.\n :param pos_x: (optional) x coordinate of the top left corner of the window.\n :param pos_y: (optional) y coordinate of the top left corner of the window.\n :param padding: (optional) padding between outer edges of the window\n and controls placed on it.\n\n If ``pos_x`` and ``pos_y`` are not privided, the window will be placed\n at the center of the screen.\n\n Example::\n\n self.setGeometry(400, 500, 5, 4)\n \"\"\"\n # type: (int, int, int, int, int, int, int) -> None\n self.win_padding = padding\n super(AddonWindow, self).setGeometry(width_, height_, rows_, columns_, pos_x, pos_y)\n self.background.setPosition(self.x, self.y)\n self.background.setWidth(self._width)\n self.background.setHeight(self._height)\n self.title_background.setPosition(self.x + skin.x_margin, self.y + skin.y_margin + skin.title_back_y_shift)\n self.title_background.setWidth(self._width - 2 * skin.x_margin)\n self.title_background.setHeight(skin.header_height)\n self.title_bar.setPosition(self.x + skin.x_margin + skin.title_bar_x_shift,\n self.y + skin.y_margin + skin.title_bar_y_shift)\n self.title_bar.setWidth(self._width - 2 * skin.x_margin)\n self.title_bar.setHeight(skin.header_height)\n self.window_close_button.setPosition(self.x + self._width - skin.close_btn_x_offset,\n self.y + skin.y_margin + skin.close_btn_y_offset)\n\n def _raiseSetGeometryNotCalledError(self):\n \"\"\"\n Helper method that raises an AddonWindowError that states that setGeometry needs to be called. Used by methods\n that will fail if the window geometry is not defined.\n :raises AddonWindowError\n \"\"\"\n # type: () -> None\n raise AddonWindowError('Window geometry is not defined! Call setGeometry first.')\n\n def getGridX(self):\n # type: () -> int\n try:\n val = self.x + self.win_padding\n except AttributeError:\n self._raiseSetGeometryNotCalledError()\n return val + skin.x_margin\n\n def getGridY(self):\n # type: () -> int\n try:\n val = self.y + self.win_padding\n except AttributeError:\n self._raiseSetGeometryNotCalledError()\n return val + skin.y_margin + skin.title_back_y_shift + skin.header_height\n\n def getGridWidth(self):\n # type: () -> int\n try:\n val = self._width - 2 * self.win_padding\n except AttributeError:\n self._raiseSetGeometryNotCalledError()\n return val - 2 * skin.x_margin\n\n def getGridHeight(self):\n # type: () -> int\n try:\n val = self._height - 2 * self.win_padding\n except AttributeError:\n self._raiseSetGeometryNotCalledError()\n return val - skin.header_height - skin.title_back_y_shift - 2 * skin.y_margin\n\n def setWindowTitle(self, title=''):\n \"\"\"\n Set window title.\n\n .. warning:: This method must be called **AFTER** (!!!) :meth:`setGeometry`,\n otherwise there is some werid bug with all skin text labels set to the ``title`` text.\n\n Example::\n\n self.setWindowTitle('My Cool Addon')\n \"\"\"\n # type: (str) -> None\n self.title_bar.setLabel(title)\n\n def getWindowTitle(self):\n \"\"\"Get window title.\"\"\"\n # type: () -> str\n return self.title_bar.getLabel()\n\n\nclass BlankFullWindow(AbstractWindow, xbmcgui.Window):\n \"\"\"\n BlankFullWindow()\n\n Addon UI container with a solid background.\n\n This is a blank window with a black background and without any elements whatsoever.\n The decoration and layout are completely up to an addon developer.\n The window controls can hide under video or music visualization.\n \"\"\"\n pass\n\n\nclass BlankDialogWindow(AbstractWindow, xbmcgui.WindowDialog):\n \"\"\"\n BlankDialogWindow()\n\n Addon UI container with a transparent background.\n\n This is a blank window with a transparent background and without any elements whatsoever.\n The decoration and layout are completely up to an addon developer.\n The window controls are always displayed over video or music visualization.\n \"\"\"\n pass\n\n\nclass AddonFullWindow(AddonWindow, xbmcgui.Window):\n \"\"\"\n AddonFullWindow(title='')\n\n Addon UI container with a solid background.\n\n ``AddonFullWindow`` instance is displayed on top of the main background image --\n ``self.main_bg`` -- and can hide behind a fullscreen video or music viaualisation.\n\n Minimal example::\n\n addon = AddonFullWindow('My Cool Addon')\n addon.setGeometry(400, 300, 4, 3)\n addon.doModal()\n \"\"\"\n\n def __new__(cls, title='', *args, **kwargs):\n return super(AddonFullWindow, cls).__new__(cls, *args, **kwargs)\n\n def _setFrame(self, title):\n \"\"\"\n Set the image for for the fullscreen background.\n \"\"\"\n # type: (str) -> None\n # Image for the fullscreen background.\n self.main_bg_img = skin.main_bg_img\n # Fullscreen background image control.\n self.main_bg = xbmcgui.ControlImage(1, 1, 1280, 720, self.main_bg_img)\n self.addControl(self.main_bg)\n super(AddonFullWindow, self)._setFrame(title)\n\n def setBackground(self, image=''):\n \"\"\"\n Set the main bacground to an image file.\n\n :param image: path to an image file as str.\n\n Example::\n\n self.setBackground('/images/bacground.png')\n \"\"\"\n # type: (str) -> None\n self.main_bg.setImage(image)\n\n\nclass AddonDialogWindow(AddonWindow, xbmcgui.WindowDialog):\n \"\"\"\n AddonDialogWindow(title='')\n\n Addon UI container with a transparent background.\n\n .. note:: ``AddonDialogWindow`` instance is displayed on top of XBMC UI,\n including fullscreen video and music visualization.\n\n Minimal example::\n\n addon = AddonDialogWindow('My Cool Addon')\n addon.setGeometry(400, 300, 4, 3)\n addon.doModal()\n \"\"\"\n","sub_path":"plugin.program.tribler/pyxbmct/addonwindow.py","file_name":"addonwindow.py","file_ext":"py","file_size_in_byte":33453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"630857737","text":"#!/usr/bin/env python\n\n\"\"\"Test script for sequence_var.py\"\"\"\n\nimport unittest\n\nfrom random_sequences_pipeline import argument_parser\nfrom random_sequences_pipeline import unconstrained_structure\nfrom random_sequences_pipeline import random_sequences\nfrom random_sequences_pipeline import fold_sequences\n\nGODZILLA = 'Queen of monsters'\n\nclass TestParser(unittest.TestCase):\n def test_parser(self):\n \"\"\"Test parsing of user input\"\"\"\n long_input = argument_parser(['--length', '20',\n '--number1', '9',\n '--seed1', '100',\n '--number2', '8',\n '--seed2', '99'])\n self.assertEqual(long_input.length, 20)\n self.assertEqual(long_input.number1, 9)\n self.assertEqual(long_input.seed1, 100)\n self.assertEqual(long_input.number2, 8)\n self.assertEqual(long_input.seed2, 99) \n short_input = argument_parser(['-l', '90',\n '-n1', '5',\n '-s1', '80',\n '-n2', '3',\n '-s2', '1000'])\n self.assertEqual(short_input.length, 90)\n self.assertEqual(short_input.number1, 5)\n self.assertEqual(short_input.seed1, 80)\n self.assertEqual(short_input.number2, 3)\n self.assertEqual(short_input.seed2, 1000) \n no_input = argument_parser('')\n self.assertEqual(no_input.length, 100)\n self.assertEqual(no_input.number1, 10)\n self.assertEqual(no_input.seed1, 1)\n self.assertEqual(no_input.number2, 100)\n self.assertEqual(no_input.seed2, 1) \n\nclass TestUnconstrainedStruct(unittest.TestCase):\n def test_unconstrained_struct(self):\n self.assertEqual(unconstrained_structure(28), '............................')\n self.assertEqual(unconstrained_structure(0), '')\n self.assertEqual(unconstrained_structure(1), '.')\n \nclass TestRandomSeq(unittest.TestCase):\n def test_random_seq(self):\n \"\"\"Test structure creation\"\"\"\n expected_result1 = ['CCUACAGAGUGGUCAUUAGGAAAGUCAC',\n 'UUUGGUGACUUCCAGCUUACAUAGGGCC',\n 'AAGCGAGCUUAACAUUCAUGCGCCGUGA']\n actual_result1 = list(random_sequences('............................', 3, 5))\n self.assertEqual(expected_result1, actual_result1)\n expected_result2 = ['CUGGAUCGGUGUUUAGAGUAGUCACAUU',\n 'GCUGAACCUAUUAGGUGGAGCCAACUCU',\n 'GUCUUUAGCGAUGGAUCGUUAAUAGAUG',\n 'CUGCGACCCACAUCGGGUCUAAUUGGAU']\n actual_result2 = list(random_sequences('(((..........)))(((......)))', 4, 5)) \n self.assertEqual(expected_result2, actual_result2)\n \nclass TestRnaFold(unittest.TestCase):\n def test_rna_fold(self):\n sequence = 'CCUACAGAGUGGUCAUUAGGAAAGUCACUUUGGUGACUUCCAGCUUACAUAGGGCAAGCGAGCUUAACAUU'\n expected_result = '.((((...))))......((((.(((((....)))))))))(((((.(.........).))))).......'\n actual_result = fold_sequences(sequence)\n self.assertEqual(expected_result, actual_result)\n \nif __name__ == '__main__':\n unittest.main()\n","sub_path":"pythons/test_random_sequences_pipeline.py","file_name":"test_random_sequences_pipeline.py","file_ext":"py","file_size_in_byte":3309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"167537829","text":"# Создание конвертированой матрицы\r\ndef convert_matrix(matrix, delays, number_machines, number_jobs):\r\n cost_matrix = [[] for x in range(number_machines)]\r\n for i in range(number_machines):\r\n for j in range(number_jobs):\r\n cost_matrix[i].append(matrix[i][j] - delays[j])\r\n return cost_matrix\r\n\r\n\r\n# Выбор работы с минимальным di\r\ndef choice_task(matrix, do_not_used_tasks, number_machines, number_jobs, l):\r\n min_cost_values = []\r\n index = 0\r\n for j in do_not_used_tasks:\r\n min_cost_values.append(matrix[0][j] + l[0])\r\n for i in range(number_machines):\r\n if min_cost_values[index] > matrix[i][j] + l[i]:\r\n min_cost_values[index] = matrix[i][j] + l[i]\r\n index = index + 1\r\n\r\n job_index = do_not_used_tasks[0]\r\n max_min_cost = min_cost_values[0]\r\n index = 0\r\n for i in min_cost_values:\r\n if max_min_cost < i:\r\n job_index = do_not_used_tasks[index]\r\n max_min_cost = i\r\n index = index + 1\r\n return job_index\r\n\r\n\r\n# Удалить выполненую работу\r\ndef rem_completed_task(do_not_used_tasks, task_i):\r\n for i in range(len(do_not_used_tasks)):\r\n if do_not_used_tasks[i] == task_i:\r\n del do_not_used_tasks[i]\r\n return\r\n\r\n\r\n# Выбор исполнителя \r\ndef choice_executor(matrix, number_machines, l, job_index):\r\n min_pos = None\r\n min_val = None\r\n for i in range(number_machines):\r\n min_current = matrix[i][job_index] + l[i]\r\n if min_val is None or min_val > min_current:\r\n min_pos = i\r\n min_val = min_current\r\n return min_pos\r\n\r\n\r\n# l - время завершения выполнения последней работы\r\n# l_indexes - список исполнителя и его работ\r\ndef calculate(matrix, delays, number_machines, number_jobs):\r\n l = [0 for x in range(len(matrix))]\r\n l_indexes = [[] for x in range(len(matrix))]\r\n cost_matrix = convert_matrix(matrix, delays, number_machines, number_jobs)\r\n\r\n do_not_used_tasks = [x for x in range(number_jobs)]\r\n\r\n while len(do_not_used_tasks) > 0:\r\n\r\n job_index = choice_task(cost_matrix, do_not_used_tasks, number_machines, number_jobs, l)\r\n\r\n machine_index = choice_executor(matrix, number_machines, l, job_index)\r\n\r\n l_indexes[machine_index].append([job_index, l[machine_index]])\r\n l[machine_index] += matrix[machine_index][job_index]\r\n rem_completed_task(do_not_used_tasks, job_index)\r\n\r\n return l_indexes\r\n","sub_path":"alg/alg.py","file_name":"alg.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"269873102","text":"\"\"\"one variable generalized linear model\n\na wrapper of R glmnet at \n\nthe Python one is not so well-written, with many bugs.\n\nit's easier to use the R version instead.\n\"\"\"\n\n# old stuff\n\n# \"\"\"one variable generalized linear model (GLM)\n#\n# essentially a wrapper of glmnet at \n# \"\"\"\n#\n# # somehow, this line will make all glmnet packages available. it will affect namespace globally.\n# # bad design.\n# # check \n# # really bad design.\n# import glmnet_python\n\nimport numpy as np\nfrom rpy2 import robjects, rinterface\n# I don't need this, as I will try to convert everything manually.\n# see \n# line 76-82\n# import rpy2.robjects.numpy2ri as n2r\nfrom rpy2.rinterface import SexpVector, REALSXP, INTSXP\n\n# load glmnet\nr = robjects.r\nr.library('glmnet')\n\n\ndef _convert_to_r_array(x, force_2d=False):\n # see \n # line 76-82\n # copy to avoid any problem.\n x = np.asarray(x).copy()\n if force_2d:\n assert x.ndim in {1, 2}\n # this is necessary for y variable. otherwise, it would fail for cv.glmnet.\n if x.ndim == 1:\n x = x[:, np.newaxis]\n if x.dtype == np.float64:\n vec = SexpVector(x.ravel(\"F\"), REALSXP)\n elif x.dtype == np.int64:\n vec = SexpVector(x.ravel(\"F\"), INTSXP)\n else:\n raise RuntimeError('not implemented for this dtype {}'.format(x.dtype))\n dim = SexpVector(x.shape, INTSXP)\n return rinterface.baseenv['array'](vec, dim=dim)\n\n\ndef _glmnet(X, y, **kwargs):\n X = _convert_to_r_array(X, force_2d=True)\n y = _convert_to_r_array(y, force_2d=True)\n # then call it.\n return r['glmnet'](X, y, **kwargs)\n\n\ndef _glmnet_coef(fit, return_bias=False):\n # by default, this extracts all coef.\n # first column is bias. (assuming we always fit bias).\n if not return_bias:\n return np.array(r['as.matrix'](r['coef'](fit)))[1:]\n else:\n return np.array(r['as.matrix'](r['coef'](fit)))\n\n\ndef _glmnet_lambda(fit):\n return np.array(fit.rx2('lambda'))\n\n\ndef _glmnet_bias(fit):\n return np.array(fit.rx2('a0'))\n\n\ndef _glmnet_predict(fit, newx, s, type_='response'):\n return np.array(r['predict'](fit, newx=_convert_to_r_array(newx, force_2d=True),\n s=s if isinstance(s, str) else _convert_to_r_array(s),\n exact=False, type=type_))\n\n\ndef glmnet_interface(X, y, *, alpha, standardize, family):\n fit = _glmnet(X, y, alpha=alpha, standardize=standardize, family=family)\n coef_seq = _glmnet_coef(fit).T\n bias_seq = _glmnet_bias(fit)\n lam_seq = _glmnet_lambda(fit)\n\n return lam_seq, coef_seq, bias_seq\n","sub_path":"tang_jcompneuro/glm_r.py","file_name":"glm_r.py","file_ext":"py","file_size_in_byte":3014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"507464887","text":"import warnings\nfrom libc import printf\n\n# Test the factorial calculation functions.\ndef factorial_demo():\n\n\t# Print factorials of the numbers in the given range.\n\tfor n in range(0, 10):\n\t\tprintf(\"%d = %ld\\n\", n, factorial_iterative(n));\n\t\tprintf(\"%d = %ld\\n\", n, factorial_recursive(n));\n\t\tprintf(\"%d = %ld\\n\", n, factorial_tailcall(n, 1));\n\n\n# Calculate factorial of the given number. Using recursion.\ndef factorial_recursive(n):\n\tif n == 0:\n\t\treturn 1\n\n\treturn factorial_recursive(n-1) * n\n\n\n# Calculate factorial of the given number. Using tail call.\ndef factorial_tailcall(n, r):\n\tif (n == 0):\n\t\treturn r\n\tr *= n\n\treturn factorial_tailcall(n-1, r)\n\n\n# Calculate factorial of the given number. Using iterations.\ndef factorial_iterative(n):\n\tr = 1\n\tfor i in range(1, n+1):\n\t\tr *= i\n\treturn r\n\n\ndef main():\n\n\tfactorial_demo();\n\n\texit(0);\n# end main\n\n\nif __name__ == \"__main__\":\n\tmain();\n","sub_path":"factorial.py","file_name":"factorial.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"240395875","text":"# - Gather __all detail data__ of Netherlands municipalities from [wikipedia](https://en.wikipedia.org/wiki/List_of_municipalities_of_the_Netherlands)\n# - Save them to CSV file\n\n\n# importing the necessary libraries\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\n\n# defining the url that I want to scrape\nurl='https://en.wikipedia.org/wiki/List_of_municipalities_of_the_Netherlands'\nr=requests.get(url)\nsoup = BeautifulSoup(r.text,'html.parser')\ntable=soup.find('table',{'class':'wikitable plainrowheaders sortable'})\nrows=table.find_all('tr')[1:]\n\n# defining the lists that will be used to store the datas\nmunicipalities=[]\ncbs_codes=[]\nprovinces=[]\npopulations=[]\npop_densities=[]\nland_areas=[]\n\n# with a for loop I will try to get all the datas from the table \nfor row in rows:\n municipality=row.find('th').text.strip()\n municipalities.append(municipality)\n\n cbs_code=row.find_all('td')[0].text.strip()\n cbs_codes.append(cbs_code)\n\n province=row.find_all('td')[1].text.strip()\n provinces.append(province)\n\n population=row.find_all('td')[2].text.strip()\n populations.append(population)\n\n pop_density=row.find_all('td')[3].text.strip()\n pop_densities.append(pop_density)\n \n land_area=row.find_all('td')[4].text.strip()\n land_areas.append(land_area)\n\n#Creating the dataframe\ndf = pd.DataFrame({'Municipality':municipalities,'CBS Code':cbs_codes,'Province':provinces,\n 'Population':populations,'Population Density':pop_densities,'Land Area':land_areas})\ndf.head()\n\n#Saving the scraped data to CSV file\ndf.to_csv('Municipalities_of_NL.csv')\n\n","sub_path":"web_scrape.py","file_name":"web_scrape.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"110937997","text":"from pyrocko import moment_tensor as mtm\n\nmagnitude = 6.3\nstrike = 123\ndip = 54\nrake = 32\n\nm0 = mtm.magnitude_to_moment(magnitude) # convert the mag to moment\nmt = mtm.MomentTensor(strike=strike, dip=dip, rake=rake, scalar_moment=m0)\nm6 = [mt.mnn, mt.mee, mt.mdd, mt.mne, mt.mnd, mt.med] # The six MT components\n\nprint(\" Mnn, Mee, Mdd, Mne, Mnd, Med, \")\nprint(m6/mt.scalar_moment()) # normalized MT components\n","sub_path":"PYROCKO/sdr_to_mom.py","file_name":"sdr_to_mom.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"410959640","text":"# 문제 설명\n# 함수 solution은 정수 n을 매개변수로 입력받습니다. n의 각 자릿수를 큰것부터 작은 순으로 정렬한 새로운 정수를 리턴해주세요.\n# 예를들어 n이 118372면 873211을 리턴하면 됩니다.\n\n# 제한 조건\n# n은 1이상 8000000000 이하인 자연수입니다.\n\ndef solution(n):\n ans =[]\n temp = str(n)\n lis = sorted(temp, reverse=True)\n answer = lis[0]\n for i in range(1,len(lis)):\n answer += lis[i]\n return int(answer)\n","sub_path":"solution(level_1)/정수_내림차순으로_배치하기.py","file_name":"정수_내림차순으로_배치하기.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"452785626","text":"#!/usr/bin/python\n\nimport numpy as np\nimport os\nimport pickle\n#import cPickle as pickle\nimport sys\n\n\npath = 'melspec'\n\n\nfilenames = os.listdir(path)\ndata = {}\ni = 0\nfor file in filenames:\n file_path = os.path.join(path, file)\n #print (file_path)\n with open(file_path, 'rb') as f:\n try:\n soundId = os.path.splitext(file)[0]\n #print (soundId)\n content = f.read()\n pp = pickle.loads(content,encoding='latin1')\n\n ##pp= pickle.load(f)\n pp = np.asarray(pp) \n #print (pp[0])\n data[str(i)] = pp\n i+=1\n except Exception as e:\n print (\"Error occurred\" + str(e))\n \nmask = np.genfromtxt('mask.csv',delimiter=',')\nmask = mask.astype(int)\ntotal = 900\nX = 599\nY = 128\nZ = 2\nlabels = np.genfromtxt('V.csv',delimiter=',')\nuserfactors = np.genfromtxt('U.csv',delimiter = ',')\n\ntdata = np.ndarray((total, X, Y,Z), dtype=np.uint8)\ntlabel = np.ndarray((total,labels.shape[1]))\nfor j,k in enumerate(mask[:900]):\n tdata[j] = data[str(k)]\n tlabel[j] = labels[j]\ntestdata = np.ndarray((100, X, Y,Z), dtype=np.uint8)\nfor j,k in enumerate(mask[900:]): \n testdata[j] = data[str(k)]\n \nprint (tdata.shape) \nprint (tlabel.shape)\nprint ('subhash')\n\nfrom keras.layers import Input, Conv2D, MaxPooling2D, Dense, Reshape, Flatten\nfrom keras.layers import Lambda, Activation, BatchNormalization, Dropout\nfrom keras.models import Model\nfrom keras import backend as K\nfrom keras.callbacks import ModelCheckpoint\nfrom keras import losses,optimizers,utils\nfrom keras.optimizers import Adam, SGD\nfrom matplotlib import pyplot as plt\nN = labels.shape[1]\n\n#def Loss_latentvecs(true, pred):\n \n\n\ndef MusicModel(input_shape):\n dropout=0\n inp = Input(shape = input_shape, name = 'input1')\n x = Conv2D(32,(4,4),padding = 'same')(inp)\n x = BatchNormalization()(x) \n x = Activation('relu')(x)\n x = Dropout(dropout)(x)\n x = MaxPooling2D(4)(x)\n x = Conv2D(64,(4,4),padding = 'same')(x)\n x = BatchNormalization()(x) \n x = Activation('relu')(x)\n x = Dropout(dropout)(x)\n x = MaxPooling2D()(x) \n x = Conv2D(128,(4,4),padding = 'same')(x)\n x = BatchNormalization()(x) \n x = Activation('relu')(x)\n x = Dropout(dropout)(x)\n x = MaxPooling2D()(x)\n x = Conv2D(256,(4,4),padding = 'same')(x)\n x = BatchNormalization()(x) \n x = Activation('relu')(x)\n x = Dropout(dropout)(x)\n x = MaxPooling2D()(x)\n x = Flatten()(x)\n print (K.shape(x))\n x = Dense(1024,activation='relu')(x)\n x = Dense(N)(x)\n model = Model(inp, x)\n return model \n \nif __name__ == '__main__':\n \n model = MusicModel(input_shape=(599,128,2)) \n model.summary()\n opt = Adam(lr=0.00001)\n model.compile(optimizer=opt, loss='mean_squared_error', metrics=['mae'])\n checkpoint = ModelCheckpoint('weight.h5', monitor='val_loss',save_best_only=True)\n model.save('my_model.h5')\n \n history = model.fit(tdata,tlabel,batch_size=4, epochs=80, verbose=1, shuffle=True,validation_split=0.2,callbacks=[checkpoint])\n model.load_weights('weight.h5')\n predictedlabels = model.predict(testdata,verbose=1,batch_size=4)\n np.savetxt('predicted.csv',predictedlabels,delimiter=',')\n with open('/trainHistoryDict', 'wb') as file_pi:\n pickle.dump(history.history, file_pi)\n x = range(1,81)\n plt.subplot(2, 1, 1)\n plt.xlabel('Epochs')\n plt.ylabel('Loss')\n plt.plot(x,history.history['loss'])\n plt.plot(x,history.history['val_loss'])\n plt.legend(('Training', 'Validation'), loc='upper right')\n plt.title('MSE loss')\n plt.subplot(2, 1, 2)\n plt.xlabel('Epochs')\n plt.ylabel('mae')\n plt.plot(x,history.history['mean_absolute_error'])\n plt.plot(x,history.history['val_mean_absolute_error'])\n plt.legend(('Training', 'Validation'), loc='upper right')\n plt.title('MAES')\n\n plt.tight_layout() \n plt.show()\n plt.savefig('plot.jpg')\n \n","sub_path":"trainMelspec.py","file_name":"trainMelspec.py","file_ext":"py","file_size_in_byte":3963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"308042846","text":"\ndef mat_mult(X, Y):\n assert len(X[0]) == len(Y)\n result = [[0] * len(Y[0])] * len(X)\n result = [[sum(a * b for a, b in zip(X_row, Y_col))\n for Y_col in zip(*Y)] for X_row in X]\n return result\n\n\ndef mat_print(mat):\n assert type(mat) == list and type(mat[0]) == list\n [print(repr(piece)) or '' + '\\n' for piece in mat]\n\n\n\nimport math\nfrom itertools import (combinations, combinations_with_replacement, count,\n permutations)\nfrom typing import List\n\nimport numpy as np\nimport scipy\n\nhelp = \"nMk: n choose k with multinomials\\nnChoosek: n choosing k normally\"\n\n\ndef nMk(n: int, k: [int]):\n \"\"\"\n n choose k multinomially,\n \"\"\"\n denom = 1\n for i in k:\n denom *= math.factorial(i)\n return math.factorial(n) / denom\n\n\ndef nChoosek(n: int, k: int):\n \"\"\"\n normal n choose k\n \"\"\"\n return math.factorial(n) / (math.factorial(k) * math.factorial(n - k))\n\n\ndef partition(n: int, k: int):\n \"\"\"\n partition of n identical elements into k unordered piles\n \"\"\"\n if n == 0 and k == 0:\n return 1\n if k > n:\n return 0\n if k == 0 and n >= 1:\n return 0\n if k == 1:\n return 1\n if k == n:\n return 1\n return partition(n - 1, k - 1) + partition(n - k, k)\n\n\ndef pall(n):\n count = 0\n for k in range(0, n + 1):\n count += p(n, k)\n return count\n\n\ndef stirling(n: int, k: int):\n if k == 1 or n == k:\n return 1\n if k == 0:\n if n == 0:\n return 1\n return 0\n if k < 0 or k > n:\n return 0\n if n < 0 or k < 0:\n raise ValueError()\n first = k * stirling(n - 1, k)\n second = stirling(n - 1, k - 1)\n return first + second\n\n\ndef p_recursive(n):\n print(f\"p{n} is \")\n for k in range(1, 15):\n print(f\"k is {k}: {(-1) ** k} * (p{n - (k * (3 * k - 1) / 2)}) +p{n - (k * (3 * k + 1) / 2)})\")\n\n\ndef snk(n, k):\n if k < 0:\n raise ValueError()\n if k == 1:\n return pall(n - 1)\n else:\n first = snk(n - 1, k - 1)\n second = snk(n - k, k - 1)\n return first - second\n\n\ndef lu_factor(A):\n \"\"\"\n LU factorization with partial pivorting\n\n Overwrite A with:\n U (upper triangular) and (unit Lower triangular) L\n Return [LU,piv]\n Where piv is 1d numpy array with row swap indices\n \"\"\"\n n = A.shape[0]\n piv = np.arange(0, n)\n for k in range(n - 1):\n\n # piv\n max_row_index = np.argmax(abs(A[k:n, k])) + k\n piv[[k, max_row_index]] = piv[[max_row_index, k]]\n A[[k, max_row_index]] = A[[max_row_index, k]]\n\n # LU\n for i in range(k + 1, n):\n A[i, k] = A[i, k] / A[k, k]\n for j in range(k + 1, n):\n A[i, j] -= A[i, k] * A[k, j]\n\n return [A, piv]\n\n\ndef matrix_cofactor(matrix):\n return np.linalg.inv(matrix).T * np.linalg.det(matrix)\n\n\ndef dist(t, u):\n dif_of_y = t[1] - u[1]\n dif_of_x = t[0] - u[0]\n return math.sqrt(dif_of_x**2 + dif_of_y**2)\n\ndef project(u,v):\n num = np.linalg.multi_dot([v,u])\n denom = np.linalg.multi_dot([u,u])\n print(f'num is {num}, denom is {denom}')\n div_result = num/denom\n print(f'div result is {div_result}')\n result = div_result * u\n print(result)\n return result\n\ndef orth(a,b):\n return b - project(a,b)\n\ndef make_array_of_combinations(min,max, num) -> [int]:\n from itertools import combinations\n return combinations(range(min,max+1), num)\n\ndef find_span_vars(vectors:List[np.ndarray], vector:List[int]):\n gen = make_array_of_combinations(-15,15,len(vectors))\n matches = []\n from itertools import starmap\n import operator\n for candidate in gen:\n pairs = zip(vectors, candidate)\n after_multiplying = starmap(operator.mul, pairs)\n from functools import reduce\n added_vectors = reduce(operator.add, after_multiplying)\n if np.array_equal(added_vectors, vector):\n matches += [candidate]\n return matches\n\n\ndef row_echelon(A):\n \"\"\" Return Row Echelon Form of matrix A \"\"\"\n\n # if matrix A has no columns or rows,\n # it is already in REF, so we return itself\n r, c = A.shape\n if r == 0 or c == 0:\n return A\n\n # we search for non-zero element in the first column\n for i in range(len(A)):\n if A[i,0] != 0:\n break\n else:\n # if all elements in the first column is zero,\n # we perform REF on matrix from second column\n B = row_echelon(A[:,1:])\n # and then add the first zero-column back\n return np.hstack([A[:,:1], B])\n\n # if non-zero element happens not in the first row,\n # we switch rows\n if i > 0:\n ith_row = A[i].copy()\n A[i] = A[0]\n A[0] = ith_row\n\n # we divide first row by first element in it\n A[0] = A[0] / A[0,0]\n # we subtract all subsequent rows with first row (it has 1 now as first element)\n # multiplied by the corresponding element in the first column\n A[1:] -= A[0] * A[1:,0:1]\n\n # we perform REF on matrix from second row, from second column\n B = row_echelon(A[1:,1:])\n\n # we add first row and first (zero) column, and return\n return np.vstack([A[:1], np.hstack([A[1:,:1], B]) ])\n\ndef is_orthogonal(vector_set:List):\n from itertools import permutations\n\n gen= permutations([np.array(item) for item in vector_set],2)\n\n def all_zeros(l):\n return all(item == 0 for item in l)\n\n if any(all_zeros(item) for item in vector_set):\n return False\n\n for vec1, vec2 in gen:\n dp = np.dot(vec1, vec2)\n if dp != 0:\n return False\n\n\nvector_set = [\n [[1],[2],[-1],],\n [[1],[0],[1]],\n [[-1], [1], [1]]\n]\ndata_xys = [\n (2,9),(3,10),(4,21),(5,20)\n]\n\ntest_data = [\n (0,1),\n (1,2),\n (2,2),\n (3,4),\n (4,5),\n]\n\ndef do_least_sqr_regress(pts:List[tuple])-> tuple:\n n= len(pts)\n x_s = [item[0] for item in pts]\n y_s = [item[1] for item in pts]\n\n sum_x = sum(x_s)\n sum_y = sum(y_s)\n\n sum_sqrd_x_s = sum(item[0]**2 for item in pts)\n\n sum_xy = 0\n\n for i, j in pts:\n sum_xy += i * j\n\n print(f'sum x is {sum_x}')\n print(f'sum y is {sum_y}')\n print(f'sum xy is {sum_xy}')\n print(f'sum_sqrd_x_s is {sum_sqrd_x_s}')\n\n m_num = (-1 * sum_x * sum_y + sum_xy * n)\n denom = (sum_sqrd_x_s * n) - (sum_x ** 2)\n m = m_num / denom\n\n b_num = (-1 * sum_x * sum_xy + sum_y * sum_sqrd_x_s)\n b = b_num / denom\n\n return m,b\n\nv1 = np.array([3,0,-4])\nv2 = np.array([11,0,2])\nv3 = np.array([1,1,7])\nminumum = -10\nmaximum = 40\ngen = permutations( range(minumum,maximum), 3)\ncounter = count(0)\n\nx1 = np.array([[-1],[-4],[-3]])\nx2 = np.array([[-1],[-2],[-2]])\nx3 = np.array([[1],[1],[1]])\n\nx4 = np.array([[3],[-4],[3]])\n\nt1 = 2 * x1\nt2 = 1 * x2\nt3 = 0 * x3\n\nto_factor = np.array([[2,3,3],[0,2,1],[4,6,1]])\ndef main():\n a = np.matrix([[-32, -6, 0], [194, 41, -21], [40, 8, -2]])\n x = np.matrix([[-6],[37],[8]])\n\n matches = []\n print(lu_factor(to_factor))\n import sys;sys.exit()\n\n for a1,a2,a3 in gen:\n val = next(counter)\n if val % 10000==0:\n print(f'{val/10000} ten thousands')\n\n\n p = np.array([\n [a1],[a2],[a3]])\n\n try:\n\n if np.array_equal(a @ p, 5*p):\n matches.append(p)\n print(p)\n except:\n continue\n return matches\n\n\ndef make_matrix_from_eigvect_eignval(p: np.matrix, d:np.matrix):\n \"\"\"\n The Eigen- relationship can be represented by Ax=kx where A is the matrix, x is a vertical vector and k is some constant value.\n Example -\n p = np.matrix([ ## vector matrix where the verticla vectors are v1=[-1,-2,-2], v2=[-1,-4,-3], v3=[1,1,1]\n [-1, -1, 1],\n [-2, -4, 1],\n [-2, -3, 1]])\n d = np.matrix([ # Eigenvalues correspond as follows 1 <=> v1, 2 <=> v2, 0 <=> v3\n [1, 0, 0],\n [0, 2, 0],\n [0, 0, 0]])\n a = make_matrix_from_eigvect_eignval(p, d)\n :param p: Eigenvectors of the matrix. Each column represents a vertical vector x.\n :param d: Eigenvalues of the matrix. If it is an n*n matrix, then there should only be up to n non-zero entries.\n :return: Matrix that represents A where Ax = kx.\n \"\"\"\n return p * d * np.linalg.inv(p)\n\ndef np_map(func, arr):\n\n return np.array([[func(xi) for xi in x] for x in arr])\n\n\nif __name__ == \"__main__\":\n main()\n import sys; sys.exit()\n import numpy as np\n\n a = np.array([[-32, -6, 0], [194, 41, -21], [40, 8, -2]])\n from pprint import pprint\n from fractions import Fraction\n eigval,eigvect = np.linalg.eig(a)\n pprint(eigval)\n\n p = np.matrix([[-1, -1, 1], [-2, -4, 1], [-2, -3, 1]])\n d = np.matrix([[-1, 0, 0], [0, -1, 0], [0, 0, 1]])\n a = make_matrix_from_eigvect_eignval(p, d)\n\n\n if np.array_equal(a * x1, t1):\n if np.array_equal(a * x2, x2):\n print('two tests passed')\n print(a[1])\n\n if np.array_equal(a * x3, t3):\n print('three tests passed')\n print(a)\n\n\n print(a)\n\n print(a*x4)\n","sub_path":"math_scripts/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":9093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"248907044","text":"#! /usr/bin/env python\n\n# bit diff = no of 1's in (a ^ b)\nw=0\ndef get_input():\n a = input(\"==> Enter first number: \")\n b = input(\"==> Enter second number: \")\n convert(a, b)\n\ndef convert(a, b):\n try:\n bitise(int(a), int(b))\n except ValueError:\n print('Please input numbers only')\n get_input()\n\ndef bitise(a, b):\n a = int(bin(a).replace('0b', ''))\n b = int(bin(b).replace('0b', ''))\n bit_diff(a^b)\n\ndef bit_diff(a):\n global w\n for i in str(a):\n if i=='1': w +=1\n\ndef main():\n print(\"*bitop method\")\n get_input()\n print(str(w)+\" positional bits differ\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"bit_diff_bitop.py","file_name":"bit_diff_bitop.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"61102418","text":"#!/usr/bin/python\n\n#from Bio import SeqIO\nimport MySQLdb as db\nimport sys\n\ncon = db.connect(host='localhost', user='hlim', passwd='secret!', db='chembl_22',unix_socket = '/var/run/mysqld/mysqld.sock');\ncur=con.cursor()\ndef get_assayInfo_by_tid(tid):\n aids=get_aid_by_tid(tid)\n if aids:\n results=[]\n for aid in aids:\n aid=str(aid[0])\n assayType=get_assayType(aid)\n assayTestType=get_assayTestType(aid)\n confScore=get_assay_confidence(aid)\n result=(aid,assayType,assayTestType,confScore)\n results.append(result)\n return results\n else:\n return None\ndef get_activityInfo_by_aid(aid):\n activityIds=get_activityId_by_aid(aid)\n if activityIds:\n results=[]\n for act in activityIds:\n act=str(act[0])\n molregno=get_molregno_by_activityId(act)\n relation=get_relation_by_activityId(act)\n value=get_value_by_activityId(act)\n unit=get_unit_by_activityId(act)\n actType=get_type_by_activityId(act)\n result=(molregno,relation,value,unit,actType)\n results.append(result)\n return results\n else:\n return None\n \ndef get_molregno_by_activityId(actId):\n qry=\"SELECT molregno FROM activities WHERE activity_id=%s\"\n cur.execute(qry,(str(actId),))\n res=cur.fetchone()\n if res:\n return str(res[0])\n else:\n return None\ndef get_relation_by_activityId(actId):\n qry=\"SELECT standard_relation FROM activities WHERE activity_id=%s\"\n cur.execute(qry,(str(actId),))\n res=cur.fetchone()\n if res:\n return str(res[0])\n else:\n return None\ndef get_value_by_activityId(actId):\n qry=\"SELECT standard_value FROM activities WHERE activity_id=%s\"\n cur.execute(qry,(str(actId),))\n res=cur.fetchone()\n if res:\n return str(res[0])\n else:\n return None\ndef get_unit_by_activityId(actId):\n qry=\"SELECT standard_units FROM activities WHERE activity_id=%s\"\n cur.execute(qry,(str(actId),))\n res=cur.fetchone()\n if res:\n return str(res[0])\n else:\n return None\ndef get_type_by_activityId(actId):\n qry=\"SELECT standard_type FROM activities WHERE activity_id=%s\"\n cur.execute(qry,(str(actId),))\n res=cur.fetchone()\n if res:\n return str(res[0])\n else:\n return None\n \ndef get_activityId_by_aid(aid):\n qry=\"SELECT activity_id FROM activities WHERE assay_id=%s\"\n cur.execute(qry,(str(aid),))\n res=cur.fetchall()\n if res:\n return res\n else:\n return None\n\ndef get_aid_by_tid(tid):\n qry=\"SELECT assay_id FROM assays WHERE tid=%s\"\n cur.execute(qry,(str(tid),))\n res=cur.fetchall()\n if res:\n return res\n else:\n return None\n\ndef get_assayType(aid):\n qry=\"SELECT assay_type FROM assays WHERE assay_id=%s\"\n cur.execute(qry,(str(aid),))\n res=cur.fetchone()\n if res:\n res=str(res[0])\n if res==\"B\":\n return \"Binding\"\n elif res==\"A\":\n return \"ADME\"\n elif res==\"F\":\n return \"Functional\"\n else:\n \"Unknown\"\n else:\n return \"Unknown\"\n\ndef get_assayTestType(aid):\n qry=\"SELECT assay_test_type FROM assays WHERE assay_id=%s\"\n cur.execute(qry,(str(aid),))\n res=cur.fetchone()\n if res:\n return str(res[0])\n else:\n return \"Unknown\"\n\ndef get_assay_confidence(aid):\n qry=\"SELECT confidence_score FROM assays WHERE assay_id=%s\"\n cur.execute(qry,(str(aid),))\n res=cur.fetchone()\n if res:\n return str(res[0])\n else:\n return None\ndef get_chemInfo_by_molregno(molregno):\n ikey=get_ikey_by_molregno(molregno)\n smiles=get_smiles_by_molregno(molregno)\n chiral=get_chirality_by_molregno(molregno)\n prodrug=get_prodrug_by_molregno(molregno)\n result=(ikey,smiles,chiral,prodrug)\n return result\n\ndef get_chirality_by_molregno(molregno):\n qry=\"SELECT chirality FROM molecule_dictionary WHERE molregno=%s\"\n cur.execute(qry,(str(molregno),))\n res=cur.fetchone()\n if res:\n res=int(res[0])\n if res==0:\n return \"Racemic\"\n elif res==1:\n return \"Single_Stereoisomer\"\n elif res==2:\n return \"Achiral\"\n else:\n return \"Unknown\"\n else:\n return \"Unknown\"\ndef get_prodrug_by_molregno(molregno):\n qry=\"SELECT prodrug FROM molecule_dictionary WHERE molregno=%s\"\n cur.execute(qry,(str(molregno),))\n res=cur.fetchone()\n if res:\n res=int(res[0])\n if res==0:\n return \"No\"\n elif res==1:\n return \"Yes\"\n else:\n return \"Unknown\"\n else:\n return \"Unknown\"\ndef get_ikey_by_molregno(molregno):\n qry=\"SELECT standard_inchi_key FROM compound_structures WHERE molregno=%s\"\n cur.execute(qry,(str(molregno),))\n res=cur.fetchone()\n if res:\n res=str(res[0])\n return res\n else:\n return \"Unknown\"\ndef get_smiles_by_molregno(molregno):\n qry=\"SELECT canonical_smiles FROM compound_structures WHERE molregno=%s\"\n cur.execute(qry,(str(molregno),))\n res=cur.fetchone()\n if res:\n res=str(res[0])\n return res\n else:\n return \"Unknown\"\n\ndef count_component_by_tid(tid):\n qry=\"SELECT tid,component_id FROM target_components WHERE tid=%s\"\n cur.execute(qry,(str(tid),))\n res=cur.fetchall()\n return res\ndef get_protInfo_by_tid(tid):\n compId=get_component_id_by_tid(tid)\n qry=\"SELECT accession, description, sequence FROM component_sequences WHERE component_id=%s\"\n cur.execute(qry,(str(compId),))\n res=cur.fetchone()\n if res:\n accession=str(res[0])\n desc=str(res[1])\n seq=str(res[2])\n result=(tid,accession,desc,seq)\n return result\n else:\n return \"Unknown\"\ndef get_component_id_by_tid(tid):\n qry=\"SELECT component_id FROM target_components WHERE tid=%s\"\n cur.execute(qry,(str(tid),))\n res=cur.fetchone()\n if res:\n res=str(res[0])\n return res\n else:\n return \"Unknown\"\n#ainfo=get_assayInfo_by_tid(\"55\")\n#print ainfo\n#actinfo=get_activityInfo_by_aid(\"4002\")\n#print actinfo\n#drug=get_chemInfo_by_molregno(\"115\")\n#print drug\n#sys.exit() #testing line\n\nassayFile=\"./CYP450_Assays.csv\"\ntargetInfo=\"./CYP450_Targets.tsv\" #comma may be part of description\nchemInfo=\"./CYP450_chemicals.tsv\" #comma may be part of SMILES\n#domainInfo=\"./CYP450_domains.csv\"\nAF=open(assayFile,\"w\")\nTF=open(targetInfo,\"w\")\nCF=open(chemInfo,\"w\")\n#DF=open(domainInfo,\"w\")\nmolregnos=[]\ndomainids=[]\n\nqry=\"SELECT DISTINCT(tid) FROM target_dictionary WHERE pref_name LIKE 'Cytochrome P450%' AND tax_id=9606 AND target_type='Single Protein'\"\ncur.execute(qry)\nresult = cur.fetchall()\nhuman_cyp_tids=[]\nfor s in result:\n human_cyp_tids.append(str(s[0]))\n#print len(human_cyp_tids)\nTF.write(\"TargetID\\tAccession\\tDescription\\tSequence\\n\")\nfor tid in human_cyp_tids:\n tid=str(tid)\n prot=get_protInfo_by_tid(tid)\n tid=prot[0]\n accession=prot[1]\n description=prot[2]\n sequence=prot[3]\n TF.write(tid+\"\\t\"+accession+\"\\t\"+description+\"\\t\"+sequence+\"\\n\")\n \ndataset = [] #(aid, type, invitro, conf_score, compound_id, target_id, standard_type, standard_relation, standard_value, standard_units)\nfor tid in human_cyp_tids:\n assayInfo=get_assayInfo_by_tid(tid)\n for ai in assayInfo:\n aid = str(ai[0])\n activityInfo = get_activityInfo_by_aid(aid)\n for s in activityInfo:\n molregnos.append(s[0])\n dataset.append((ai[0], ai[1], ai[2], ai[3], s[0], tid, s[4], s[1], s[2], s[3]) )\nAF.write(\"AssayId, AssayType, TestType, ConfidenceScore, Molregno, TargetId, ActivityType, ValueRelation, ActivityValue, ActivityUnit\\n\")\nfor data in dataset:\n line=\"%s, %s, %s, %s, %s, %s, %s, %s, %s, %s\\n\" %(data[0],data[1],data[2],data[3],data[4],data[5],data[6],data[7],data[8],data[9])\n AF.write(line)\n#print len(dataset)\n\nmolregnos=list(set(molregnos))\nCF.write(\"Molregno\\tStandardInChIKey\\tChirality\\tIsProdrug\\tCanonicalSMILES\\n\")\nfor molregno in molregnos:\n chemInfo=get_chemInfo_by_molregno(str(molregno))\n ikey=str(chemInfo[0])\n smiles=str(chemInfo[1])\n chiral=str(chemInfo[2])\n prodrug=str(chemInfo[3])\n CF.write(str(molregno)+\"\\t\"+ikey+\"\\t\"+chiral+\"\\t\"+prodrug+\"\\t\"+smiles+\"\\n\")\n","sub_path":"CYP450/dataprep/ExtractAssays.py","file_name":"ExtractAssays.py","file_ext":"py","file_size_in_byte":8352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"471442513","text":"import urllib.request\nimport urllib.parse \n\nurl = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=https://www.google.com.hk/'\ninput_word = input(\"Input whatever you want to translate:\")\n\ndata = {'type':'AUTO',\n'i':input_word,\n'doctype':'json',\n'xmlVersion':'1.8',\n'keyfrom':'fanyi.web',\n'ue':'UTF-8',\n'action':'FY_BY_CLICKBUTTON',\n'typoResult':'true'}\n\ndata = urllib.parse.urlencode(data).encode('utf-8')\n\nresponse = urllib.request.urlopen(url, data)\nresult = eval(response.read().decode())\nprint('The translate result is:\\n%s'%(result['translateResult'][0][0]['tgt']))\n","sub_path":"dictionary.py","file_name":"dictionary.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"28041843","text":"from django.shortcuts import render\n\n# Create your views here.\n\n\ndef pageCount(request):\n count = request.session.get('count', 0)\n count = count + 1\n request.session['count'] = count\n return render(request, 'Sessionapp/count.html', {'count': count})\n","sub_path":"sessionAPI/SessionApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"102855110","text":"from django.shortcuts import redirect\nfrom datetime import date\nfrom django.views import View\nfrom django.utils import timezone\nfrom drchrono.utils import get_token\nfrom drchrono.models import Appointment, Patient\n\nfrom drchrono.endpoints import PatientEndpoint, AppointmentEndpoint\n\n\nclass DataSync(View):\n \"\"\"\n adding data sync endpoint to avoid calling api's on every load\n \"\"\"\n\n def get_appointments_on_date(self, date):\n auth_token = get_token()\n appointments = AppointmentEndpoint(auth_token)\n return list(appointments.list(date=date))\n\n def get_patients(self):\n auth_token = get_token()\n patients = PatientEndpoint(auth_token)\n return list(patients.list())\n\n def update_appointment_data(self, patient_list, appointment_list):\n # here on loading, if there is already data with missing times in it, we populate it here.\n for appointment in appointment_list:\n patient = [patient for patient in patient_list if patient.patient_id == appointment.get('patient')][0]\n\n appointment_obj, created = Appointment.objects.get_or_create(\n appointment_id=appointment.get('id'),\n patient_id=patient.patient_id,\n status=appointment.get('status'),\n scheduled_time=appointment.get('scheduled_time'),\n reason=appointment.get('reason'),\n notes = appointment.get('notes')\n )\n\n if appointment_obj.status == 'Arrived' and not appointment_obj.arrival_time:\n appointment_obj.arrival_time = timezone.now()\n\n appointment_obj.save()\n\n def update_patient_data(self, patient_list):\n # here on loading, if there is already data with missing times in it, we populate it here.\n for patient in patient_list:\n Patient.objects.get_or_create(\n patient_id= patient.get('id'),\n first_name = patient.get('first_name'),\n last_name = patient.get('last_name'),\n middle_name = patient.get('middle_name'),\n nick_name = patient.get('nick_name'),\n email=patient.get('email'),\n gender = patient.get('gender'),\n ethnicity = patient.get('ethnicity'),\n date_of_birth = patient.get('date_of_birth'),\n default_pharmacy = patient.get('default_pharmacy'),\n cell_phone = patient.get('cell_phone'),\n patient_photo = patient.get('patient_photo'),\n preferred_language = patient.get('preferred_language'),\n race = patient.get('race'),\n social_security_number = patient.get('social_security_number'),\n emergency_contact_name = patient.get('emergency_contact_name'),\n emergency_contact_phone = patient.get('emergency_contact_phone'),\n emergency_contact_relation = patient.get('emergency_contact_relation')\n )\n\n return Patient.objects.all()\n\n\n def get(self, request, *args, **kwargs):\n # First get lists from api\n patient_list = self.get_patients()\n appointment_list = self.get_appointments_on_date(date=date.today())\n # then create objects\n patients = self.update_patient_data(patient_list)\n self.update_appointment_data(patients, appointment_list)\n\n return redirect('welcome')\n","sub_path":"drchrono/views/data_sync_views.py","file_name":"data_sync_views.py","file_ext":"py","file_size_in_byte":3424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"316520531","text":"import jpype\nimport numpy as np\nimport pickle\nimport argparse\nfrom collections import defaultdict\n\n\n# flatten arrays\ndef flatten_array(arr):\n return [item for sublist in arr for item in sublist]\n\n\ndef default_to_regular(d):\n if isinstance(d, defaultdict):\n d = {k: default_to_regular(v) for k, v in d.items()}\n return d\n\n\ndef get_te(destinations, sources):\n avg_te = {}\n local_te = {}\n params = {'embedding': {}, 'delay': {}}\n\n if destinations == dict:\n for source in sources:\n avg_te[source] = {}\n local_te[source] = {}\n for destination in destinations:\n avg_te[source][destination] = []\n local_te[source][destination] = []\n\n for destination in destinations:\n params['embedding'][destination] = []\n params['delay'][destination] = []\n\n # create a TE calculator\n te_calc_class = jpype.JPackage(\"infodynamics.measures.continuous.kraskov\").TransferEntropyCalculatorKraskov\n te_calc = te_calc_class()\n\n for destination in destinations:\n # destination is data for all 8 neurons\n for i in range(8):\n # specify neuron time series\n dest_array = destinations[destination][:, i].tolist()\n # Since we're dealing with a well-defined simulation, we embed the destination only\n te_calc.setProperty(te_calc_class.PROP_AUTO_EMBED_METHOD,\n te_calc_class.AUTO_EMBED_METHOD_RAGWITZ_DEST_ONLY)\n te_calc.setProperty(te_calc_class.PROP_K_SEARCH_MAX, \"6\")\n te_calc.setProperty(te_calc_class.PROP_TAU_SEARCH_MAX, \"6\")\n # Supply source embedding\n te_calc.setProperty(te_calc_class.L_PROP_NAME, \"1\")\n te_calc.setProperty(te_calc_class.L_TAU_PROP_NAME, \"1\")\n\n # Check the auto-selected parameters and print out the result:\n optimised_k = int(te_calc.getProperty(te_calc_class.K_PROP_NAME))\n optimised_k_tau = int(te_calc.getProperty(te_calc_class.K_TAU_PROP_NAME))\n # optimisedL = int(teCalc.getProperty(teCalcClass.L_PROP_NAME))\n # optimisedLTau = int(teCalc.getProperty(teCalcClass.L_TAU_PROP_NAME))\n\n params['embedding'][destination].append(optimised_k)\n params['delay'][destination].append(optimised_k_tau)\n\n for source in sources:\n source_array = sources[source]\n # Since we're auto-embedding, no need to supply k, l, k_tau, l_tau here:\n te_calc.initialise()\n\n # Compute TE\n te_calc.setObservations(source_array, dest_array)\n\n te = te_calc.computeAverageLocalOfObservations()\n local_measures = te_calc.computeLocalOfPreviousObservations()\n\n avg_te[source][destination].append(te)\n local_te[source][destination].append(list(local_measures))\n\n else:\n print('not a dict')\n for source in sources:\n avg_te[source] = []\n local_te[source] = []\n\n # create a TE calculator\n te_calc_class = jpype.JPackage(\"infodynamics.measures.continuous.kraskov\").TransferEntropyCalculatorKraskov\n te_calc = te_calc_class()\n\n dest_array = destinations\n # Since we're dealing with a well-defined simulation, we embed the destination only\n te_calc.setProperty(te_calc_class.PROP_AUTO_EMBED_METHOD,\n te_calc_class.AUTO_EMBED_METHOD_RAGWITZ_DEST_ONLY)\n te_calc.setProperty(te_calc_class.PROP_K_SEARCH_MAX, \"6\")\n te_calc.setProperty(te_calc_class.PROP_TAU_SEARCH_MAX, \"6\")\n # Supply source embedding\n te_calc.setProperty(te_calc_class.L_PROP_NAME, \"1\")\n te_calc.setProperty(te_calc_class.L_TAU_PROP_NAME, \"1\")\n\n for source in sources:\n source_array = sources[source]\n # Since we're auto-embedding, no need to supply k, l, k_tau, l_tau here:\n te_calc.initialise()\n\n # Compute TE\n te_calc.setObservations(source_array, dest_array)\n\n te = te_calc.computeAverageLocalOfObservations()\n local_measures = te_calc.computeLocalOfPreviousObservations()\n\n avg_te[source].append(te)\n local_te[source].append(list(local_measures))\n\n return avg_te, local_te, params\n\n\ndef get_mi(destinations, sources):\n avg_mi = {}\n local_mi = {}\n\n for source in sources:\n avg_mi[source] = {}\n local_mi[source] = {}\n for destination in destinations:\n avg_mi[source][destination] = []\n local_mi[source][destination] = []\n\n mi_calc_class = jpype.JPackage(\"infodynamics.measures.continuous.kraskov\").MutualInfoCalculatorMultiVariateKraskov2\n mi_calc = mi_calc_class()\n\n for destination in destinations:\n # destination is data for all 8 neurons\n for i in range(8):\n # specify neuron time series\n dest_array = destinations[destination][:, i].tolist()\n\n mi_calc.setProperty(\"NORMALISE\", \"true\")\n\n for source in sources:\n source_array = sources[source]\n\n mi_calc.initialise(1, 1)\n\n # Compute MI\n mi_calc.setObservations(source_array, dest_array)\n\n mi = mi_calc.computeAverageLocalOfObservations()\n local_measures = mi_calc.computeLocalOfPreviousObservations()\n\n avg_mi[source][destination].append(mi)\n local_mi[source][destination].append(list(local_measures))\n return avg_mi, local_mi\n\n\ndef get_ais(destinations):\n avg_ais = {}\n local_ais = {}\n params = {'embedding': {}, 'delay': {}}\n\n for destination in destinations:\n avg_ais[destination] = []\n local_ais[destination] = []\n params['embedding'][destination] = []\n params['delay'][destination] = []\n\n # 1. Construct the calculator:\n ais_calc_class = jpype.JPackage(\"infodynamics.measures.continuous.kraskov\").ActiveInfoStorageCalculatorKraskov\n ais_calc = ais_calc_class()\n for destination in destinations:\n # destination is data for all 8 neurons\n for i in range(8):\n # specify neuron time series\n dest_array = destinations[destination][:, i].tolist()\n\n # 2. Set any properties to non-default values:\n ais_calc.setProperty(\"AUTO_EMBED_METHOD\", \"MAX_CORR_AIS\")\n ais_calc.setProperty(\"AUTO_EMBED_K_SEARCH_MAX\", \"6\")\n ais_calc.setProperty(\"AUTO_EMBED_TAU_SEARCH_MAX\", \"6\")\n\n optimised_k = int(ais_calc.getProperty(ais_calc_class.K_PROP_NAME))\n optimised_k_tau = int(ais_calc.getProperty(ais_calc_class.TAU_PROP_NAME))\n\n params['embedding'][destination].append(optimised_k)\n params['delay'][destination].append(optimised_k_tau)\n\n # 3. Initialise the calculator for (re-)use:\n ais_calc.initialise()\n # 4. Supply the sample data:\n ais_calc.setObservations(dest_array)\n\n # 5. Compute the estimate:\n ais = ais_calc.computeAverageLocalOfObservations()\n local_measures = ais_calc.computeLocalOfPreviousObservations()\n\n avg_ais[destination].append(ais)\n local_ais[destination].append(list(local_measures))\n\n return avg_ais, local_ais, params\n\n\ndef get_cross_mi(action, brain, conditioning):\n all_lags = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))\n\n # mi_calc_class = jpype.JPackage(\n # \"infodynamics.measures.continuous.kraskov\").MutualInfoCalculatorMultiVariateKraskov2\n mi_calc_class = jpype.JPackage(\n \"infodynamics.measures.continuous.kraskov\").ConditionalMutualInfoCalculatorMultiVariateKraskov2\n mi_calc = mi_calc_class()\n\n dest_array = action\n conditional_array = conditioning\n mi_calc.setProperty(\"NORMALISE\", \"true\")\n\n for lag in range(1, 2):\n mi_calc.setProperty(\"PROP_TIME_DIFF\", str(lag))\n\n for source in brain:\n for i in range(8):\n # specify neuron time series\n source_array = brain[source][:, i].tolist()\n mi_calc.initialise(1, 1, 1)\n\n # Compute MI\n mi_calc.setObservations(source_array, dest_array, conditional_array)\n\n mi = mi_calc.computeAverageLocalOfObservations()\n\n sig_distr = mi_calc.computeSignificance(1000)\n sig_mean = sig_distr.getMeanOfDistribution()\n sig_std = sig_distr.getStdOfDistribution()\n sig_p = sig_distr.pValue\n\n # print(\"Neuron %d, MI = %.4f bits (null: %.4f +/- %.4f std dev.); p(surrogate > measured)=%.5f \"\n # \"from %d surrogates)\" %\n # (i, mi, sig_mean, sig_std, sig_p, 1000))\n\n local_measures = mi_calc.computeLocalOfPreviousObservations()\n\n all_lags[lag]['avg_mi'][source].append(mi)\n all_lags[lag]['local_mi'][source].append(list(local_measures))\n all_lags[lag]['sig_mi'][source].append((sig_mean, sig_std, sig_p))\n\n all_lags_regular = default_to_regular(all_lags)\n\n return all_lags_regular\n\n\ndef main(measure, trial_num):\n # jar location\n jarLocation = \"/Users/katja/javawd/infodynamics-dist-1.4/infodynamics.jar\"\n # Start the JVM (add the \"-Xmx\" option with say 1024M if you get crashes due to not enough memory space)\n jpype.startJVM(jpype.getDefaultJVMPath(), \"-ea\", \"-Djava.class.path=\" + jarLocation)\n\n # get data\n pkl_file = open('input_data/resampled_td_914463.pkl', 'rb')\n td = pickle.load(pkl_file)\n pkl_file.close()\n\n # pkl_file = open('td_immobile_914463.pkl', 'rb')\n # td = pickle.load(pkl_file)\n # pkl_file.close()\n # trial_num = 30 # target in position 10\n # td = td[0] # tracker in position 0\n\n target_pos = flatten_array(td['target_pos'][trial_num].tolist())\n target_dist = flatten_array((td['target_pos'][trial_num] - td['tracker_pos'][trial_num]).tolist())\n left_border_dist = flatten_array((-20 - td['tracker_pos'][trial_num]).tolist())\n right_border_dist = flatten_array((20 - td['tracker_pos'][trial_num]).tolist())\n\n outputs_a1 = td['output_a1'][trial_num]\n brain_states_a1 = td['brain_state_a1'][trial_num]\n\n outputs_a2 = td['output_a2'][trial_num]\n brain_states_a2 = td['brain_state_a2'][trial_num]\n\n left_motor = td['keypress'][trial_num][:, 0]\n right_motor = td['keypress'][trial_num][:, 1]\n\n brain_a1 = {'outputs_a1': outputs_a1, 'activation_a1': brain_states_a1}\n brain_a2 = {'outputs_a2': outputs_a2, 'activation_a2': brain_states_a2}\n\n destinations_data = {'outputs_a1': outputs_a1, 'outputs_a2': outputs_a2,\n 'activation_a1': brain_states_a1, 'activation_a2': brain_states_a2}\n\n sources_data = {'target_dist': target_dist, 'left_border_dist': left_border_dist,\n 'right_border_dist': right_border_dist}\n\n if measure == \"te\":\n sources_data = {'target_dist': target_dist, 'left_border_dist': left_border_dist,\n 'right_border_dist': right_border_dist,\n 'left_motor': left_motor, 'right_motor': right_motor}\n\n # computed_avg_te, computed_local_te, computed_params = get_te(destinations_data, sources_data)\n #\n # output = open('{}_trial{}.pkl'.format(measure, trial_num+1), 'wb')\n # pickle.dump((computed_avg_te, computed_local_te, computed_params), output)\n # output.close()\n #\n # print('done stimuli to neurons')\n\n sources_data_exit_a1 = {}\n for source in brain_a1:\n for i in range(8):\n k = source + '_n' + str(i)\n sources_data_exit_a1[k] = brain_a1[source][:, i]\n\n destinations_data_exit_a1 = left_motor.tolist()\n print(left_motor)\n print(type(left_motor))\n\n print(sources_data_exit_a1.keys())\n computed_avg_te, computed_local_te, computed_params = get_te(destinations_data_exit_a1, sources_data_exit_a1)\n\n output = open('{}_trial{}_exit1.pkl'.format(measure, trial_num+1), 'wb')\n pickle.dump((computed_avg_te, computed_local_te, computed_params), output)\n output.close()\n\n sources_data_exit_a2 = {}\n for source in brain_a2:\n for i in range(8):\n k = source + '_n' + str(i)\n sources_data_exit_a2[k] = brain_a2[source][:, i]\n\n destinations_data_exit_a2 = right_motor.tolist()\n\n computed_avg_te, computed_local_te, computed_params = get_te(destinations_data_exit_a2, sources_data_exit_a2)\n\n output = open('{}_trial{}_exit2.pkl'.format(measure, trial_num+1), 'wb')\n pickle.dump((computed_avg_te, computed_local_te, computed_params), output)\n output.close()\n\n elif measure == \"mi\":\n computed_avg_mi, computed_local_mi = get_mi(destinations_data, sources_data)\n\n output = open('{}_trial{}.pkl'.format(measure, trial_num + 1), 'wb')\n pickle.dump((computed_avg_mi, computed_local_mi), output)\n output.close()\n\n elif measure == \"ais\":\n computed_avg_ais, computed_local_ais, computed_params = get_ais(destinations_data)\n\n output = open('{}_trial{}.pkl'.format(measure, trial_num + 1), 'wb')\n pickle.dump((computed_avg_ais, computed_local_ais, computed_params), output)\n output.close()\n\n elif measure == \"cross_mi\":\n brain2_to_action1 = get_cross_mi(left_motor, brain_a2, target_pos)\n brain1_to_action2 = get_cross_mi(right_motor, brain_a1, target_pos)\n\n output = open('{}_trial{}.pkl'.format(measure, trial_num + 1), 'wb')\n pickle.dump((brain2_to_action1, brain1_to_action2), output)\n output.close()\n\n jpype.shutdownJVM()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"measure\", type=str)\n parser.add_argument(\"trial_num\", type=int)\n args = parser.parse_args()\n main(args.measure, args.trial_num)\n","sub_path":"joint-tracking/infoplots.py","file_name":"infoplots.py","file_ext":"py","file_size_in_byte":14163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"609010583","text":"import os\n\nfrom flask import Flask\nfrom .models import db\n\n\ndef _inject_config(app):\n base_settings = os.path.join(app.root_path, '../conf/base_settings.py')\n app.config.from_pyfile(base_settings)\n\n\ndef create_basic_app():\n app = Flask(__name__)\n _inject_config(app)\n db.init_app(app)\n return app\n\n\ndef create_app():\n app = Flask(__name__)\n _inject_config(app)\n db.init_app(app)\n return app\n","sub_path":"tabe/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"310359317","text":"# Copyright 2018 Xanadu Quantum Technologies Inc.\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.\nr\"\"\"\nConfiguration\n=============\n\n**Module name:** :mod:`pennylane.configuration`\n\n.. currentmodule:: pennylane.configuration\n\nThis module contains the :class:`Configuration` class, which is used to\nload, store, save, and modify configuration options for PennyLane and all\nsupported plugins and devices.\n\nBehaviour\n---------\n\nOn first import, PennyLane attempts to load the configuration file `config.toml`, by\nscanning the following three directories in order of preference:\n\n1. The current directory\n2. The path stored in the environment variable ``PENNYLANE_CONF``\n3. The default user configuration directory:\n\n * On Linux: ``~/.config/pennylane``\n * On Windows: ``~C:\\Users\\USERNAME\\AppData\\Local\\Xanadu\\pennylane``\n * On MacOS: ``~/Library/Preferences/pennylane``\n\nIf no configuration file is found, a warning message will be displayed in the logs,\nand all device parameters will need to be passed as keyword arguments when\nloading the device.\n\nThe user can access the initialized configuration via `pennylane.config`, view the\nloaded configuration filepath, print the configurations options, access and modify\nthem via keys (i.e., ``pennylane.config['main.shots']``), and save/load new configuration files.\n\nConfiguration files\n-------------------\n\nThe configuration file `config.toml` uses the `TOML standard `_,\nand has the following format:\n\n.. code-block:: toml\n\n [main]\n # Global PennyLane options.\n # Affects every loaded plugin if applicable.\n shots = 0\n\n [strawberryfields.global]\n # Options for the Strawberry Fields plugin\n hbar = 1\n shots = 100\n\n [strawberryfields.fock]\n # Options for the Strawberry Fields Fock plugin\n cutoff_dim = 10\n hbar = 0.5\n\n [strawberryfields.gaussian]\n # Indentation doesn't matter in TOML files,\n # but helps provide clarity.\n\n [projectq.global]\n # Options for the Project Q plugin\n\n [projectq.simulator]\n gate_fusion = true\n\n [projectq.ibm]\n user = \"johnsmith\"\n password = \"secret123\"\n use_hardware = true\n device = \"ibmqx4\"\n num_runs = 1024\n\nMain PennyLane options, that are passed to all loaded devices, are provided under the ``[main]``\nsection. Alternatively, options can be specified on a per-plugin basis, by setting the options under\n``[plugin.global]``.\n\nFor example, in the above configuration file, the Strawberry Fields\ndevices will be loaded with a default of ``shots = 100``, rather than ``shots = 0``. Finally,\nyou can also specify settings on a device-by-device basis, by placing the options under the\n``[plugin.device]`` settings.\n\nSummary of methods\n------------------\n\n.. currentmodule:: pennylane.configuration.Configuration\n\n.. autosummary::\n path\n load\n save\n\nHelper methods\n--------------\n\n.. autosummary::\n safe_set\n safe_get\n\nCode details\n~~~~~~~~~~~~\n\n.. currentmodule:: pennylane.configuration\n\n\"\"\"\nimport os\nimport logging as log\n\nimport toml\nfrom appdirs import user_config_dir\n\nlog.getLogger()\n\n\nclass Configuration:\n \"\"\"Configuration class.\n\n This class is responsible for loading, saving, and storing PennyLane\n and plugin/device configurations.\n\n Args:\n name (str): filename of the configuration file.\n This should be a valid TOML file. You may also pass an absolute\n or a relative file path to the configuration file.\n \"\"\"\n def __init__(self, name):\n # Look for an existing configuration file\n self._config = {}\n self._filepath = None\n self._name = name\n self._user_config_dir = user_config_dir('pennylane', 'Xanadu')\n self._env_config_dir = os.environ.get(\"PENNYLANE_CONF\", \"\")\n\n # search the current directory the directory under environment\n # variable PENNYLANE_CONF, and default user config directory, in that order.\n directories = [os.curdir, self._env_config_dir, self._user_config_dir, '']\n for idx, directory in enumerate(directories):\n try:\n self._filepath = os.path.join(directory, self._name)\n self.load(self._filepath)\n break\n except FileNotFoundError:\n if idx == len(directories)-1:\n log.info('No PennyLane configuration file found.')\n\n def __str__(self):\n if self._config:\n return \"{}\".format(self._config)\n return \"\"\n\n def __repr__(self):\n return \"PennyLane Configuration <{}>\".format(self._filepath)\n\n @property\n def path(self):\n \"\"\"Return the path of the loaded configuration file.\n\n Returns:\n str: If no configuration is loaded, this returns ``None``.\"\"\"\n return self._filepath\n\n def load(self, filepath):\n \"\"\"Load a configuration file.\n\n Args:\n filepath (str): path to the configuration file.\n \"\"\"\n with open(filepath, 'r') as f:\n self._config = toml.load(f)\n\n def save(self, filepath):\n \"\"\"Save a configuration file.\n\n Args:\n filepath (str): path to the configuration file.\n \"\"\"\n with open(filepath, 'w') as f:\n toml.dump(self._config, f)\n\n def __getitem__(self, key):\n keys = key.split('.')\n return self.safe_get(self._config, *keys)\n\n def __setitem__(self, key, value):\n keys = key.split('.')\n self.safe_set(self._config, value, *keys)\n\n def __bool__(self):\n return bool(self._config)\n\n @staticmethod\n def safe_set(dct, value, *keys):\n \"\"\"Safely set the value of a key from a nested dictionary.\n\n If any key provided does not exist, a dictionary containing the\n remaining keys is dynamically created and set to the required value.\n\n Args:\n dct (dict): the dictionary to set the value of.\n value: the value to set. Can be any valid type.\n *keys: each additional argument corresponds to a nested key.\n \"\"\"\n for key in keys[:-1]:\n dct = dct.setdefault(key, {})\n\n dct[keys[-1]] = value\n\n @staticmethod\n def safe_get(dct, *keys):\n \"\"\"Safely return value from a nested dictionary.\n\n If any key provided does not exist, an empty dictionary is returned.\n\n Args:\n dct (dict): the dictionary to set the value of.\n *keys: each additional argument corresponds to a nested key.\n\n Returns:\n value corresponding to ``dct[keys[0]][keys[1]]`` etc.\n \"\"\"\n for key in keys:\n try:\n dct = dct[key]\n except KeyError:\n return {}\n return dct\n","sub_path":"pennylane/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":7248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"112495915","text":"from data_structures_and_algorithms.challenges.left_join.left_join import left_join\nfrom data_structures_and_algorithms.Data_Structures.hashtable.hashtable import Hashmap\n\ndef test_simple_left_join():\n synonym=Hashmap(1024)\n antonyms=Hashmap(1024)\n synonym.add('fond','enamored')\n synonym.add('wrath','anger')\n antonyms.add('fond','averse')\n assert left_join(synonym, antonyms) == [['fond', 'enamored', 'averse'], ['wrath', 'anger', 'null']]\ndef test_no_common_keys():\n synonym=Hashmap(1024)\n antonyms=Hashmap(1024)\n synonym.add('fond','enamored')\n synonym.add('wrath','anger')\n antonyms.add('see','look')\n assert left_join(synonym, antonyms) == [['fond', 'enamored', 'null'], ['wrath', 'anger', 'null']]\ndef test_1st_dict_is_empty():\n synonym=Hashmap(1024)\n antonyms=Hashmap(1024)\n antonyms.add('see','look')\n assert left_join(synonym, antonyms) == []\ndef test_2nd_dictionary_empty():\n synonym=Hashmap(1024)\n antonyms=Hashmap(1024)\n synonym.add('fond','enamored')\n synonym.add('wrath','anger')\n assert left_join(synonym, antonyms) == [['fond', 'enamored', 'null'], ['wrath', 'anger', 'null']]\n","sub_path":"tests/test_left_join.py","file_name":"test_left_join.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"550398739","text":"\"\"\"\n\n\"\"\"\nfrom datetime import datetime\nfrom sqlalchemy import (MetaData, Table, Column, Integer, String, BigInteger,\n DateTime, ForeignKey)\n\n__all__ = ['__meta', 'stocks_table', 'hist_data_table']\n\n__meta = MetaData()\n\nstocks_table = Table('stocks', __meta,\n #Column('id', Integer(), primary_key=True),\n Column('code', String(100), primary_key=True),\n Column('company', String(100), index=True, unique=True, nullable=False),\n Column('market_type', Integer()),\n Column('main_ics', String(100), nullable=True),\n Column('alt_ics', String(100), nullable=True),\n Column('created_on', DateTime(), default=datetime.now),\n Column('updated_on', DateTime(), default=datetime.now, onupdate=datetime.now),\n Column('delisted_on', DateTime(), nullable=True)\n )\n\n\nhist_data_table = Table('hist_data', __meta,\n Column('id', BigInteger(), primary_key=True),\n Column('code', ForeignKey('stocks.code')),\n Column('date', DateTime(), index=True),\n Column('close', Integer()),\n Column('open', Integer()),\n Column('high', Integer()),\n Column('low', Integer()),\n Column('volume', Integer())\n )\n\n\n#Column('created_on', DateTime(), default=datetime.now),\n# Column('updated_on', DateTime(), default=datetime.now, onupdate=datetime.now),\n# hist_data_table 에 추가\n\n#from sqlalchemy import Index\n#Index('ix_test', mytable.c.cookie_sku, mytable.c.cookie_name))","sub_path":"BigBull/database/data_model.py","file_name":"data_model.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"277367386","text":"# vim: et:sw=2:ts=2:nowrap\n\nimport ctypes\nfrom ctypes import create_string_buffer, byref\nimport numpy as np\nimport os.path\nimport sys\nimport time\n\nfrom .clib import GxFpga\n\n\nclass FpgaError(Exception):\n \"\"\"\n The exception thrown when an error occurs in communicating with\n the FPGA board.\n \"\"\"\n pass \n\nclass Board(object):\n \"\"\"A Pythonic interface to the Marvin Test GX3500 FPGA board\"\"\"\n \n def __init__(self, slot):\n \"\"\"\n Create a binding to a given GX2500 board.\n \n :param slot: the PCI bus/slot number to bind against\n \"\"\"\n\n handle = ctypes.c_short(0)\n self._call(GxFpga.GxFpgaInitialize, slot, byref(handle))\n self._handle = handle\n \n def _call(self, function, *args):\n \"\"\"\n Call a libGxFpga function, automatically passing in a final argument\n byref(status), then raise an appropriate FpgaError if status != 0.\n \n :param function: the function in .clib.GxFpga to call\n :param *args: the first N-1 arguments taken by the function (argument N\n is assumed to be byref(status)\n \"\"\"\n status = ctypes.c_short(0)\n args = args + (byref(status), )\n function(*args)\n \n if status.value != 0:\n err_str = create_string_buffer(b'', size=256)\n GxFpga.GxFpgaGetErrorString(status, err_str, 256, byref(status))\n raise FpgaError(err_str.value)\n\n def reset(self):\n \"\"\"\n Reset the board.\n \"\"\"\n self._call(GxFpga.GxFpgaReset, self._handle)\n \n def _load_percentage(self):\n \"\"\"Returns the percentage value from GxFpgaLoadStatus\"\"\"\n percentage = ctypes.c_short(0)\n self._call(GxFpga.GxFpgaLoadStatus, self._handle, byref(percentage))\n return percentage.value\n \n def summary(self):\n \"\"\"\n Read the board self-identification summary.\n \n :return: the self-identification summary string\n \"\"\"\n buf = create_string_buffer(b'', size=256)\n self._call(GxFpga.GxFpgaGetBoardSummary, self._handle, buf, 256)\n \n return buf.value\n \n def load_program(self, filename, target='volatile', progress='stdout'):\n \"\"\"\n Load a bitstream file to either the FPGA or the FPGA EEPROM.\n If loading directly to the FPGA, the file must be a Serial Vector Format\n (.svf) bitstream file.\n If loading directly to the FPGA EEPROM, the file must be a (.rpd) bitstream file.\n \n :param filename: the path to the target .svf|.rpd file\n :param target: which storage to load the bitstream into, either 'volatile' or 'eeprom'.\n :param progress: how to handle load progress notifications. May be None for \n silent, 'stdout' for a textual progress report on stdout, or\n a callable progress(step, percent) where step is 'start', 'load',\n or 'done', and percent is the percentage of the load that has\n completed.\n \"\"\"\n if target == 'volatile':\n lt = GxFpga.GXFPGA_LOAD_TARGET_VOLATILE\n elif target == 'eeprom':\n lt = GxFpga.GXFPGA_LOAD_TARGET_EEPROM\n else:\n raise ValueError('target must be either \"volatile\" or \"eeprom\"')\n\n if type(filename) is str:\n filename = filename.encode()\n\n if progress is None:\n progress = lambda step, percent: None\n elif progress == 'stdout':\n base = os.path.basename(filename)\n def progress(step, percent):\n if step == 'start':\n sys.stdout.write('Loading {}: 0%'.format(base))\n sys.stdout.flush()\n elif step == 'load':\n sys.stdout.write('\\b\\b\\b\\b{0:3d}%'.format(percent))\n sys.stdout.flush()\n elif step == 'done':\n sys.stdout.write('\\b\\b\\b\\bDone.\\n')\n sys.stdout.flush()\n\n try:\n progress('start', 0)\n except:\n raise ValueError(\"progress must be None, 'stdout', or a callable\")\n \n self._call(GxFpga.GxFpgaLoad, self._handle, lt, filename, GxFpga.GXFPGA_LOAD_MODE_ASYNC)\n while True:\n p = self._load_percentage()\n progress('load', p)\n if p == 100:\n break\n time.sleep(0.1)\n progress('done', 100)\n \n def read(self, location, addr, count=1):\n \"\"\"\n Read a value from the FPGA.\n \n :param location: 'reg' (register space, BAR 1) or 'mem' (memory, BAR 2)\n :param addr: the address to read (must be a multiple of 4)\n :param count: the number of 32-bit dwords to read\n \n :return: the values read, as a numpy.ndarray\n \"\"\"\n \n if location == 'reg':\n function = GxFpga.GxFpgaReadRegister\n elif location == 'mem':\n function = GxFpga.GxFpgaReadMemory\n else:\n raise ValueError(\"location must be 'reg' or 'mem'\")\n \n val = np.zeros(() if count == 1 else (count,), dtype=np.int32)\n valptr = val.ctypes.data_as(ctypes.POINTER(ctypes.c_int32))\n self._call(function, self._handle, addr, valptr, 4*count)\n \n return val\n \n def write(self, location, addr, values):\n \"\"\"\n Write a value to the FPGA.\n \n :param location: 'reg' (register space, BAR 1) or 'mem' (memory, BAR 2)\n :param addr: the address to write (must be a multiple of 4)\n :param values: the 32-bit value(s) to write, as something coercable to a\n numpy.ndarray or as some ctypes object.\n \"\"\"\n \n try:\n size = ctypes.sizeof(values)\n if size % 4 != 0:\n raise ValueError('data can only be written in multiples of 4 bytes')\n\n try:\n valptr = ctypes.cast(ctypes.pointer(values),\n ctypes.POINTER(ctypes.c_uint32))\n except TypeError as e:\n raise ValueError('values appear to be ctypes, but cast failed:' + e)\n\n except TypeError:\n vals = np.asarray(values, dtype=np.uint32)\n if vals.ndim == 0:\n size = 4\n elif vals.ndim == 1:\n size = 4 * len(vals)\n else:\n raise ValueError('cannot write arrays of greater than 1 dimension')\n valptr = vals.ctypes.data_as(ctypes.POINTER(ctypes.c_uint32))\n \n if location == 'reg':\n function = GxFpga.GxFpgaWriteRegister\n elif location == 'mem':\n function = GxFpga.GxFpgaWriteMemory\n else:\n raise ValueError(\"location must be 'reg' or 'mem'\")\n \n self._call(function, self._handle, addr, valptr, size)\n\n def _call_summary(self, fn, buflen=256):\n \"\"\"\n Call a GxFpgaGet*Summary() function which takes a handle,\n a string buffer, and the buffer's length.\n\n :param fn: the GxFpga function to call\n :param buflen: the size of the string buffer to use\n :return: the fetched string\n \"\"\"\n buf = ctypes.create_string_buffer(buflen)\n self._call(fn, self._handle, buf, buflen)\n return buf.value\n\n @property\n def eeprom_summary(self):\n \"\"\"\n The EEPROM status string, as read from the board.\n \"\"\"\n return self._call_summary(GxFpga.GxFpgaGetEepromSummary)\n\n def load_from_eeprom(self):\n \"\"\"\n Load the FPGA bitstream stored in EEPROM on the board.\n \"\"\"\n self._call(GxFpga.GxFpgaLoadFromEeprom, self._handle)\n\n @property\n def driver_summary(self):\n \"\"\"\n The Marvin Test GxFpga driver info.\n\n :return: the driver information tuple(string, major_version, minor_version)\n \"\"\"\n buflen = 256\n buf = ctypes.create_string_buffer(buflen)\n ver = ctypes.c_uint32()\n self._call(GxFpga.GxFpgaGetDriverSummary, buf, buflen, ctypes.byref(ver))\n ver = ver.value\n\n return (buf.value, ver >> 16, ver & 0xffff)\n\n @property\n def board_summary(self):\n \"\"\"\n The board summary information as a string.\n\n :return: the board summary string\n \"\"\"\n return self._call_summary(GxFpga.GxFpgaGetBoardSummary)\n","sub_path":"python/marvin/fpga.py","file_name":"fpga.py","file_ext":"py","file_size_in_byte":7515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"317865838","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 ('sites', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='SiteInstance',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),\n ('slug', models.CharField(max_length=10)),\n ('site', models.OneToOneField(to='sites.Site')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"288735785","text":"from flask_socketio import SocketIO, join_room\nfrom flask_login import current_user\nfrom flask_jwt_extended import decode_token\nfrom flask_jwt_extended.utils import verify_token_claims, UserClaimsVerificationError\nfrom flask import request, current_app\nfrom .models import rconn\nfrom . import misc\nimport json\nfrom wheezy.html.utils import escape_html\nimport logging\n\n\nclass SocketIOWithLogging(SocketIO):\n @property\n def __logger(self):\n return logging.getLogger(current_app.logger.name + \".socketio\")\n\n def emit(self, event, *args, **kwargs):\n self.__logger.debug(\"EMIT %s %s %s\", event, args[0], kwargs)\n super(SocketIOWithLogging, self).emit(event, *args, **kwargs)\n\n def on(self, message, namespace=None):\n def decorator(handler):\n def func(*args):\n self.__logger.debug(\"RECV %s %s\", message, args[0] if args else \"\")\n handler(*args)\n\n return super(SocketIOWithLogging, self).on(message, namespace)(func)\n\n return decorator\n\n\nsocketio = SocketIOWithLogging()\n\n\n@socketio.on(\"msg\", namespace=\"/snt\")\ndef chat_message(g):\n if g.get(\"msg\") and current_user.is_authenticated:\n message = {\"user\": current_user.name, \"msg\": escape_html(g.get(\"msg\")[:250])}\n rconn.lpush(\"chathistory\", json.dumps(message))\n rconn.ltrim(\"chathistory\", 0, 20)\n socketio.emit(\"msg\", message, namespace=\"/snt\", room=\"chat\")\n\n\n@socketio.on(\"connect\", namespace=\"/snt\")\ndef handle_message():\n if current_user.get_id():\n join_room(\"user\" + current_user.uid)\n socketio.emit(\n \"uinfo\",\n {\n \"taken\": current_user.score,\n \"ntf\": current_user.notifications,\n \"mod_ntf\": current_user.mod_notifications(),\n },\n namespace=\"/snt\",\n room=\"user\" + current_user.uid,\n )\n\n\n@socketio.on(\"getchatbacklog\", namespace=\"/snt\")\ndef get_chat_backlog():\n msgs = rconn.lrange(\"chathistory\", 0, 20)\n for m in msgs[::-1]:\n socketio.emit(\"msg\", json.loads(m.decode()), namespace=\"/snt\", room=request.sid)\n\n\n@socketio.on(\"deferred\", namespace=\"/snt\")\ndef handle_deferred(data):\n \"\"\"Subscribe for notification of when the work associated with a\n target token (some unique string) is done. The do-er of the work\n may have already finished and placed the result in Redis.\"\"\"\n target = data.get(\"target\")\n if target:\n target = str(target)\n join_room(target)\n result = rconn.get(target)\n if result is not None:\n result = json.loads(result)\n socketio.emit(\n result[\"event\"], result[\"value\"], namespace=\"/snt\", room=target\n )\n\n\ndef send_deferred_event(event, token, data, expiration=30):\n \"\"\"Both send an event, and stash the event and its data in Redis so it\n can be sent to any tardy subscribers.\"\"\"\n rconn.setex(\n name=token, time=expiration, value=json.dumps({\"event\": event, \"value\": data})\n )\n socketio.emit(event, data, namespace=\"/snt\", room=token)\n\n\n@socketio.on(\"subscribe\", namespace=\"/snt\")\ndef handle_subscription(data):\n sub = data.get(\"target\")\n if not sub:\n return\n if not str(sub).startswith(\"user\"):\n join_room(sub)\n\n\n@socketio.on(\"token-login\", namespace=\"/snt\")\ndef token_login(data):\n tokendata = decode_token(data[\"jwt\"])\n try:\n verify_token_claims(tokendata)\n except UserClaimsVerificationError:\n return\n join_room(\"user\" + tokendata[\"identity\"])\n\n socketio.emit(\n \"notification\",\n {\"count\": misc.get_notification_count(tokendata[\"identity\"])},\n namespace=\"/snt\",\n room=\"user\" + tokendata[\"identity\"],\n )\n","sub_path":"app/socketio.py","file_name":"socketio.py","file_ext":"py","file_size_in_byte":3734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"349683296","text":"import random\nimport statistics\n\n\n\ndef add_ball(balls, boxes=3):\n balls.append(random.randint(0, boxes-1))\n\n\ndef check_empty(balls, boxes=3):\n record = [0 for i in range(boxes)]\n\n for ball in balls:\n record[ball] += 1\n\n for r in record:\n if r == 0: return True\n\n return False\n\n\ndef simulation(trials=100, n=5, boxes=3):\n count_true = 0\n\n for i in range(trials):\n print(\"running trial\", i)\n if run_once(n, boxes):\n count_true += 1\n\n return count_true/trials\n\n\ndef run_once(n, boxes):\n balls = []\n\n for i in range(n):\n add_ball(balls, boxes)\n\n print(balls)\n\n if check_empty(balls, boxes):\n print(True)\n return True\n else:\n print(False)\n return False\n\n\nprint(simulation(trials=(1000), n=5, boxes=3))","sub_path":"testballs.py","file_name":"testballs.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"55941572","text":"#!/usr/bin/env python\n#\n# Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration\n#\n# Script to create an AthenaAttributeList with a single attribute \"xint\".\n# Usage example: dmtest_condwriter.py --rs=1 --ls=1 'sqlite://;schema=test.db;dbname=OFLP200' AttrList_noTag 42\n#\n\nfrom __future__ import print_function\n\nimport sys\nfrom PyCool import cool\nfrom CoolConvUtilities import AtlCoolLib, AtlCoolTool\n\nclass createTestDB(AtlCoolLib.coolTool):\n\n def setup(self,args):\n # set values of non-optional parameters\n self.tag=str(args[0])\n self.xint=int(args[1])\n \n def usage(self):\n \"\"\" Define the additional syntax for options \"\"\"\n self._usage1()\n print ('TAG xint')\n self._usage2()\n \n def execute(self):\n\n folder='/DMTest/TestAttrList'\n\n # do update - setup folder specification and create if needed\n spec = cool.RecordSpecification()\n spec.extend(\"xint\", cool.StorageType.Int32)\n print (\">== Store object in folder\",folder)\n cfolder = AtlCoolLib.ensureFolder(self.db, folder, spec,\n AtlCoolLib.athenaDesc(self.runLumi, 'AthenaAttributeList'),\n cool.FolderVersioning.MULTI_VERSION)\n if (cfolder is None): sys.exit(1)\n # now write data\n payload = cool.Record(spec)\n payload['xint'] = self.xint\n print ('>== Store object with IOV [',self.since,',',self.until,'] and tag',self.tag,'xint',self.xint)\n try:\n if (self.tag==\"HEAD\"):\n cfolder.storeObject(self.since,self.until,payload,0)\n else:\n cfolder.storeObject(self.since,self.until,payload,0,self.tag)\n print (\">== Storing COOL object succeeded. Current content:\")\n except Exception:\n import traceback\n traceback.print_exc()\n print ('>== Storing COOL object FAILED')\n sys.exit(1)\n\n # print full content\n act = AtlCoolTool.AtlCoolTool(self.db)\n print (act.more(folder))\n\nmytool = createTestDB('dmtest_condwriter.py',False,3,3,[])\n","sub_path":"Control/DataModelTest/DataModelTestDataCommon/scripts/dmtest_condwriter.py","file_name":"dmtest_condwriter.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"397069491","text":"import math\nn = int(input())\na_tmp = input().split()\na = []\nfor i in range(n):\n a.append(int(a_tmp[i]))\na1 = []\nfor i in range(n):\n a1.append(a[i]-1-i)\nprint(a1)\nb_max = max(a1)\nb_min = min(a1)\nsadness = []\nfor b in range(b_min, b_max+1):\n print(b)\n abs = [math.fabs(a1[i]-b) for i in range(n)]\n sadness.append(int(sum(abs)))\nprint('min', min(sadness))\nprint(sadness)\n","sub_path":"Beginner102/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"250773183","text":"\"\"\"\nCopyright © 2020 Forescout Technologies, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nimport logging\n\ncredentials = {}\nvsa_server_details = {}\nresponse = {}\n\ncredentials[\"username\"] = params[\"connect_kaseyavsa_username\"]\ncredentials[\"password\"] = params[\"connect_kaseyavsa_password\"]\n\nvsa_server_details[\"address\"] = params[\"connect_kaseyavsa_server_ipaddress\"]\nvsa_server_details[\"port\"] = params[\"connect_kaseyavsa_server_port\"]\n\ncode, client, session_token = KASEYAVSA_API_LIB.KASEYAVSA_HTTP_CLIENT(credentials, vsa_server_details, ssl_context)\n\nkaseyavsa_property_map = {\n \"AgentId\": \"connect_kaseyavsa_agentid\",\n \"AssetId\": \"connect_kaseyavsa_assetid\",\n \"OSName\": \"connect_kaseyavsa_osname\",\n \"MachineGroup\": \"connect_kaseyavsa_machine_group\",\n \"LastSeenDate\": \"connect_kaseyavsa_last_seen_date\"\n}\n\n\nlogging.debug(\"RESOLVE: Login to VSA Server [{}] returned code [{}]\".format(vsa_server_details[\"address\"], code))\n\nif code == 200:\n properties = []\n if \"mac\" in params:\n mac = ':'.join(params[\"mac\"][i:i + 2] for i in range(0, 12, 2))\n logging.debug(\"Attempting API Query for MAC [{}]\".format(mac))\n query_code, query_results = KASEYAVSA_API_LIB.KASEYAVSA_QUERY_ASSETS(client, vsa_server_details, session_token, mac)\n if not query_results[\"TotalRecords\"] == 0:\n host_details = query_results[\"Result\"][0]\n\n logging.debug(\"API Query returned code [{}] and response [{}]\".format(query_code, query_results))\n\n properties = {}\n for key, value in host_details.items():\n if key in kaseyavsa_property_map:\n if key != \"LastSeenDate\":\n if value != \"\":\n properties[kaseyavsa_property_map[key]] = str(value)\n else:\n properties[kaseyavsa_property_map[key]] = \"None\"\n else:\n _date_time_obj = datetime.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f')\n properties[kaseyavsa_property_map[key]] = int(datetime.datetime.timestamp(_date_time_obj))\n\n response[\"properties\"] = properties\n else:\n response[\"error\"] = \"Could not find this endpoint in the Kaseya VSA Server.\"\n else:\n response[\"error\"] = \"No MAC address to query the endpoint.\"\nelse:\n response[\"error\"] = \"API Connection Failed, check configuration.\"\n\nlogging.debug(\"Returning response object to infrastructure. response=[{}]\".format(response))","sub_path":"Kaseya VSA/Kaseya VSA 1.0.0/kaseyavsa_resolve.py","file_name":"kaseyavsa_resolve.py","file_ext":"py","file_size_in_byte":3517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"369006639","text":"import argparse\nimport os\nimport random\nimport socket\nimport string\nimport subprocess\nimport sys\nfrom pathlib import Path\nfrom string import Formatter\n\nimport numpy as np\n\nfrom development.modules.clsMail import MailCls\nfrom development.modules.config import PACKAGE_DIR\n\n\ndef update_class_instance(respy_obj, spec_dict):\n \"\"\" Update model specification from the baseline initialization file.\n \"\"\"\n\n respy_obj.unlock()\n\n # Varying the baseline level of ambiguity requires special case. The same is true\n # for the discount rate.\n if \"level\" in spec_dict[\"update\"].keys():\n respy_obj.attr[\"optim_paras\"][\"level\"] = np.array(\n [spec_dict[\"update\"][\"level\"]]\n )\n if \"delta\" in spec_dict[\"update\"].keys():\n respy_obj.attr[\"optim_paras\"][\"delta\"] = np.array(\n [spec_dict[\"update\"][\"delta\"]]\n )\n\n for key_ in spec_dict[\"update\"].keys():\n if key_ in [\"level\", \"delta\"]:\n continue\n respy_obj.set_attr(key_, spec_dict[\"update\"][key_])\n\n respy_obj.lock()\n\n return respy_obj\n\n\ndef strfdelta(tdelta, fmt):\n \"\"\" Get a string from a timedelta.\n \"\"\"\n f, d = Formatter(), {}\n l = {\"D\": 86400, \"H\": 3600, \"M\": 60, \"S\": 1}\n k = list(map(lambda x: x[1], list(f.parse(fmt))))\n rem = int(tdelta.total_seconds())\n for i in (\"D\", \"H\", \"M\", \"S\"):\n if i in k and i in l.keys():\n d[i], rem = divmod(rem, l[i])\n return f.format(fmt, **d)\n\n\ndef cleanup():\n os.system(\"git clean -d -f\")\n\n\ndef compile_package(is_debug=False):\n \"\"\" Compile the package for use.\n \"\"\"\n python_exec = sys.executable\n cwd = os.getcwd()\n os.chdir(PACKAGE_DIR + \"/respy\")\n subprocess.check_call(python_exec + \" waf distclean\", shell=True)\n if not is_debug:\n subprocess.check_call(python_exec + \" waf configure build\", shell=True)\n else:\n subprocess.check_call(python_exec + \" waf configure build --debug \", shell=True)\n\n os.chdir(cwd)\n\n\ndef send_notification(which, **kwargs):\n \"\"\" Finishing up a run of the testing battery.\n \"\"\"\n # This allows to run the scripts even when no notification can be send.\n home = Path(os.environ.get(\"HOME\") or os.environ.get(\"HOMEPATH\"))\n if not os.path.exists(str(home / \".credentials\")):\n return\n\n hours, is_failed, num_tests, seed = None, None, None, None\n\n # Distribute keyword arguments\n if \"is_failed\" in kwargs.keys():\n is_failed = kwargs[\"is_failed\"]\n\n if \"hours\" in kwargs.keys():\n hours = \"{}\".format(kwargs[\"hours\"])\n\n if \"procs\" in kwargs.keys():\n procs = str(kwargs[\"procs\"])\n\n if \"num_tests\" in kwargs.keys():\n num_tests = \"{}\".format(kwargs[\"num_tests\"])\n\n if \"seed\" in kwargs.keys():\n seed = \"{}\".format(kwargs[\"seed\"])\n\n if \"idx_failures\" in kwargs.keys():\n idx_failures = \", \".join(str(e) for e in kwargs[\"idx_failures\"])\n\n if \"old_release\" in kwargs.keys():\n old_release = kwargs[\"old_release\"]\n\n if \"new_release\" in kwargs.keys():\n new_release = kwargs[\"new_release\"]\n\n if \"failed_seeds\" in kwargs.keys():\n failed_seeds = kwargs[\"failed_seeds\"]\n\n hostname = socket.gethostname()\n\n if which == \"scalability\":\n subject = \" RESPY: Scalability Testing\"\n message = \" Scalability testing is completed on @\" + hostname + \".\"\n elif which == \"reliability\":\n subject = \" RESPY: Reliability Testing\"\n message = \" Reliability testing is completed on @\" + hostname + \".\"\n elif which == \"property\":\n subject = \" RESPY: Property Testing\"\n message = (\n \" A \"\n + hours\n + \" hour run of the testing battery on @\"\n + hostname\n + \" is completed.\"\n )\n\n elif which == \"regression\":\n subject = \" RESPY: Regression Testing\"\n if is_failed:\n message = (\n \"Failure during regression testing @\"\n + hostname\n + \" for test(s): \"\n + idx_failures\n + \".\"\n )\n else:\n message = \" Regression testing is completed on @\" + hostname + \".\"\n\n elif which == \"release\":\n subject = \" RESPY: Release Testing\"\n if is_failed:\n message = (\n \" Failure during release testing with seed \"\n + seed\n + \" on @\"\n + hostname\n + \".\"\n )\n else:\n message = (\n \" Release testing completed successfully after \"\n + hours\n + \" hours on @\"\n + hostname\n + \". We compared release \"\n + old_release\n + \" against \"\n + new_release\n + \" for a total of \"\n + num_tests\n + \" tests.\"\n )\n elif which == \"robustness\":\n subject = \" RESPY: Robustness Testing\"\n if is_failed is True:\n failed_pct = len(failed_seeds) / float(num_tests) * 100\n failed_pct = \"({} %)\".format(failed_pct)\n message = (\n \" Failure during robustness testing on @{}. In total {} \"\n + \"tests were run in {} hours on {} cores. {} tests failed \"\n + \"{}. The failed tests have the following seeds: {}.\"\n )\n message = message.format(\n hostname,\n num_tests,\n hours,\n procs,\n len(failed_seeds),\n failed_pct,\n str(failed_seeds),\n )\n else:\n message = (\n \" Robustness testing completed successfully after \"\n + hours\n + \" hours, running on \"\n + procs\n + \" cores on @\"\n + hostname\n + \". In total \"\n + num_tests\n + \" were run.\"\n )\n else:\n raise AssertionError\n\n mail_obj = MailCls()\n mail_obj.set_attr(\"subject\", subject)\n mail_obj.set_attr(\"message\", message)\n\n if which == \"property\":\n mail_obj.set_attr(\"attachment\", \"property.respy.info\")\n elif which == \"scalability\":\n mail_obj.set_attr(\"attachment\", \"scalability.respy.info\")\n elif which == \"reliability\":\n mail_obj.set_attr(\"attachment\", \"reliability.respy.info\")\n elif which == \"robustness\":\n mail_obj.set_attr(\"attachment\", \"robustness.respy.info\")\n\n mail_obj.lock()\n\n mail_obj.send()\n\n\ndef aggregate_information(which, fnames):\n \"\"\" This function simply aggregates the information from the different specifications.\n \"\"\"\n if which == \"scalability\":\n fname_info = \"scalability.respy.info\"\n elif which == \"reliability\":\n fname_info = \"reliability.respy.info\"\n else:\n raise AssertionError\n\n dirnames = []\n for fname in fnames:\n dirnames += [fname.replace(\".ini\", \"\")]\n\n with open(fname_info, \"w\") as outfile:\n outfile.write(\"\\n\")\n for dirname in dirnames:\n\n if not os.path.exists(dirname):\n continue\n\n outfile.write(\" \" + dirname + \"\\n\")\n os.chdir(dirname)\n with open(fname_info, \"r\") as infile:\n outfile.write(infile.read())\n os.chdir(\"../\")\n outfile.write(\"\\n\\n\")\n\n\ndef process_command_line_arguments(description):\n \"\"\" Process command line arguments for the request.\n \"\"\"\n parser = argparse.ArgumentParser(description=description)\n\n parser.add_argument(\n \"--debug\",\n action=\"store_true\",\n dest=\"is_debug\",\n default=False,\n help=\"use debugging specification\",\n )\n\n args = parser.parse_args()\n is_debug = args.is_debug\n\n return is_debug\n\n\ndef get_random_dirname(length):\n \"\"\" This function creates a random directory name.\n\n The random name is used for a temporary testing directory. It starts with two\n underscores so that it does not clutter the root directory.\n\n TODO: Sensible length default.\n\n \"\"\"\n return \"__\" + \"\".join(random.choice(string.ascii_lowercase) for _ in range(length))\n","sub_path":"development/modules/auxiliary_shared.py","file_name":"auxiliary_shared.py","file_ext":"py","file_size_in_byte":8192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"315159595","text":"'''\nGiven a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.\n'''\n\ndef searchInsert(nums, target):\n for i in range(0,len(nums)):\n if (nums[i] == target):\n return(i)\n for i in range(0,len(nums)):\n if nums[i] > target:\n return(i)\n return(len(nums))\n\nprint(searchInsert([1,3,5,6], 7))\n\n\n ","sub_path":"insert_element.py","file_name":"insert_element.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"161845906","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 3 16:56:13 2020\n\n@author: Anthony\n\"\"\"\n\nimport random\n\nimport ordonnancement as o\nimport flowshop as f\nimport operator\nimport numpy as np\n\n\n# schedules jobs according to a sequence and returns the corresponding length\ndef evaluate(sequence, nb_machines) :\n ordo = o.Ordonnancement(nb_machines)\n ordo.ordonnancer_liste_job(sequence)\n return ordo.duree()\n\n# creates a random scheduling and prints its information\n\"\"\"def random_scheduling(F) :\n sequence = []\n while F.l_job != [] :\n sequence.append(F.l_job.pop(random.randint(0, len(F.l_job) - 1)))\n ordo = o.Ordonnancement(F.nb_machines)\n ordo.ordonnancer_liste_job(sequence)\n ordo.afficher()\n print(\"The length of this scheduling is {}\".format(evaluate(sequence, F.nb_machines)))\"\"\"\n\n# Simple test of the 'evaluate' and 'random_scheduling' functions\n\"\"\"F = f.Flowshop()\nF.definir_par(\"jeu2.txt\")\nrandom_scheduling(F)\"\"\"\n\n#####################################################\"\n\n\n# Useful auxilary functions\n\ndef fst(couple):\n a, b = couple\n return a\n\n\ndef snd(couple):\n a, b = couple\n return b\n\n\n\n\n\n# schedules jobs according to a sequence and returns the corresponding length\ndef evaluate(sequence, nb_machines):\n ordo = o.Ordonnancement(nb_machines)\n ordo.ordonnancer_liste_job(sequence)\n time = ordo.duree()\n return time\n\n\n# creates a random sequences from the jobs given in the flowshop F\ndef random_sequence(F):\n sequence = []\n jobs = [J for J in F.l_job]\n while jobs != []:\n sequence.append(jobs.pop(random.randint(0, len(jobs) - 1)))\n return sequence\n\n\n# creates a random scheduling and prints its information\ndef random_scheduling(F):\n sequence = random_sequence(F)\n ordo = o.Ordonnancement(F.nb_machines)\n ordo.ordonnancer_liste_job(sequence)\n ordo.afficher()\n print(\"The length of this scheduling is {}\".format(evaluate(sequence, F.nb_machines)))\n return sequence\n\n\n# Swaps the two elements at the given indexes\ndef swap(sequence, index1, index2):\n copy = [J for J in sequence]\n copy[index1], copy[index2] = sequence[index2], sequence[index1]\n return copy\n\n\n# Inserts the element index2 at the position index1\ndef insert(sequence, index1, index2):\n copy = [J for J in sequence]\n if index1 > index2:\n index1, index2 = index2, index1\n copy[index1] = sequence[index2]\n for k in range(index1 + 1, index2 + 1):\n copy[k] = sequence[k - 1]\n return copy\n\n\n# Gets a random neighbour with the swap and insertion operators\ndef random_neighbour(sequence):\n index1, index2 = random.randint(0, len(sequence) - 1), random.randint(0, len(sequence) - 1)\n while index2 == index1:\n index2 = random.randint(0, len(sequence) - 1)\n if random.randint(0, 1) == 0:\n return swap(sequence, index1, index2)\n else:\n return insert(sequence, index1, index2)\n\n\n# Computes the simulated annealing and returns a sequence of jobs and the associated time\n# For each iteration the temperature is multiplied by the 'temperature_multiplier' parameter\n# Once the temperature is under the 'final_temperature' parameter, the algorithm stops\ndef recuit(F, initial_temperature, temperature_multiplier, final_temperature):\n sequence = random_sequence(F)\n time = evaluate(sequence, F.nb_machines)\n temperature = initial_temperature\n while temperature >= final_temperature:\n nei_seq = random_neighbour(sequence)\n nei_time = evaluate(nei_seq, F.nb_machines)\n if nei_time <= time or random.random() <= np.exp((time - nei_time) / temperature):\n sequence = nei_seq\n time = nei_time\n temperature *= temperature_multiplier\n return sequence, time\n\n\n# Auxilary function for the 'one cut point' reproduction from the left\ndef LeftAuxReproduction1(seq1, seq2, cut_point,nb_machines):\n n = len(seq1)\n first_part = seq1[:cut_point]\n child_seq = first_part\n for k in range(cut_point, n):\n if seq2[k] not in first_part:\n child_seq.append(seq2[k])\n for i in range(cut_point):\n if seq2[i] not in child_seq:\n child_seq.append(seq2[i])\n time = evaluate(child_seq, nb_machines)\n return child_seq, time\n\n\n# Auxilary function for the 'one cut point' reproduction from the right\ndef RightAuxReproduction1(seq1, seq2, cut_point,nb_machines):\n n = len(seq1)\n child_seq = [J for J in seq2]\n first_part = seq1[cut_point:]\n ind=cut_point\n for k in range(cut_point):\n if seq1[k] not in first_part:\n ind-=1\n child_seq[ind]=seq1[k]\n child_seq1=child_seq[ind:]\n for i in range(cut_point,n):\n if seq1[i] not in child_seq1:\n ind-=1\n child_seq[ind]=seq1[i]\n time = evaluate(child_seq, nb_machines)\n return child_seq, time\n\n\n# Random reproduction of two sequences with one cut point\ndef Leftreproduction1(seq1, seq2, nb_machines):\n cut_point = random.randint(0, len(seq1) - 1)\n return LeftAuxReproduction1(seq1, seq2, cut_point, nb-machines)\n\n\n# Best possible reproduction of two sequences with one cut point\ndef bestReproduction1(seq1, seq2, nb_machines):\n best_child = seq1\n best_time = 100000\n print(\"yoooo\")\n print(evaluate(seq1,nb_machines))\n print(evaluate(seq2,nb_machines))\n for cut_point in range(len(seq1)):\n child_seq, time = LeftAuxReproduction1(seq1, seq2, cut_point,nb_machines)\n print(\"yo\")\n print(time)\n if time < best_time:\n best_time = time\n best_child = child_seq\n child_seq, time = RightAuxReproduction1(seq1, seq2, cut_point,nb_machines)\n if time < best_time:\n best_time = time\n best_child = child_seq\n return best_child, best_time\n\n\n# Auxilary function for the 'two cut points' reproduction\ndef auxReproduction2(seq1, seq2, cut_point1, cut_point2, F):\n first_part = seq1[:cut_point1]\n last_part = seq1[cut_point2:]\n mid_part = []\n for J in seq2[cut_point1: cut_point2]:\n if J not in first_part and J not in last_part:\n mid_part.append(J)\n for J in seq1[cut_point1: cut_point2]:\n if J not in mid_part:\n mid_part.append(J)\n child_seq = first_part + mid_part + last_part\n time = evaluate(child_seq, F.nb_machines)\n return child_seq, time\n\n\n# Random reproduction of two sequences with one cut point\ndef reproduction2(seq1, seq2, F):\n cut_point1, cut_point2 = 0, 0\n while cut_point1 >= cut_point2:\n cut_point1, cut_point2 = random.randint(0, len(seq1) - 1), random.randint(0, len(seq1) - 1)\n return auxReproduction2(seq1, seq2, cut_point1, cut_point2, F)\n\n\n# Best possible reproduction of two sequences with one cut point\ndef bestReproduction2(seq1, seq2, F):\n best_child = seq1\n best_time = 100000\n for cut_point1 in range(1, len(seq1) - 1):\n for cut_point2 in range(cut_point1 + 1, len(seq1) - 1):\n child_seq, time = auxReproduction2(seq1, seq2, cut_point1, cut_point2, F)\n if time < best_time:\n best_time = time\n best_child = child_seq\n return best_child, best_time\n\n\n# Generates an initial population of solutions with the simulated annealing,\n# Then makes them reproduce themselves following a 'binary tree' structure :\n# Each generation is half the size of the previous one\ndef binaryTreeReproductions(initialPopulation, reproductionAlgorithm):\n recuits = []\n for k in range(initialPopulation):\n sequence, time = recuit(F, 20, 0.99, 1)\n recuits.append((sequence, time))\n print([snd(x) for x in recuits], min([snd(x) for x in recuits]))\n population = recuits\n while len(population) > 1:\n new_population = []\n for k in range(len(population) // 2):\n new_population.append(reproductionAlgorithm(fst(population[2 * k]), fst(population[2 * k + 1]), F))\n population = new_population\n print(population[0])\n\n\n# Creates an initial population through annealing, then reduces it to one solution\n# At each step it seeks a good possible reproduction between the first element of the population and the others\n# Then it kills the parents and adds the new found solution to the population\n# The goal is to reduce the time, so it always looks for reproductions which the child is better than both the parents\ndef seekBestReproductions(poplen, reproductionAlgorithm,ITERATIONS,PMATE):\n recuits = []\n for k in range(poplen):\n sequence, time = recuit(F, 20, 0.99, 1)\n recuits.append((sequence, time))\n print([snd(x) for x in recuits], min([snd(x) for x in recuits]))\n\n population = recuits\n print(population)\n nb_machines=F.nb_machines\n n=0\n while n40:\n print(\"print all tweets? Y/n\")\n con=input()\n if con[0]!='Y':\n return\n print(list)\n for l in list:\n print(texts[l])\n\ndef main():\n wordDict,textWordList,texts=getData()\n print(\"Processing...\")\n iil=makeList(wordDict,textWordList)\n while True:\n print(\"===============\")\n print(\"Input command:\")\n command=input()\n r = bq.ExecuteTree.ExecuteTree.ExecuteQuery(command,iil)\n print(\"=====result=====\")\n printDocs(r,texts)\n return;\n \n\nif __name__==\"__main__\":\n main();\n #abt=bq.ExpParser.Expressions.Expressions()\n #abt.parse(\"a&(b|c)&d|!(e&(f|l&m&n)|!(!o&p));\")#a&(b|c)&d|!(e&(f|l&m&n)|!(!o&p)) !(!(a))","sub_path":"Work3_BRM/Work3_BRM.py","file_name":"Work3_BRM.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"87182355","text":"import sys\nsys.path.append('../..')\nimport pyion\n\n# Create a proxy to node 2 and attach to it\nproxy = pyion.get_bp_proxy(2)\nproxy.bp_attach()\n\n# Listen to 'ipn:2.1' for incoming data\nwith proxy.bp_open('ipn:2.1') as eid:\n while eid.is_open:\n try:\n # This is a blocking call.\n print('Received:', eid.bp_receive())\n except InterruptedError:\n # User has triggered interruption with Ctrl+C\n break\n","sub_path":"test1rx.py","file_name":"test1rx.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"156384592","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Nov 19 17:15:38 2019\r\n\r\n@author: admin\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport os\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\n\r\nimport pickle\r\n\r\nos.chdir(\"D:/siva/Deployment/upvotes/\")\r\ntrain=pd.read_csv(\"train.csv\")\r\n\r\ncolumns= train.columns\r\n \r\nlis = []\r\nfor i in range(0, train.shape[1]):\r\n #print(i)\r\n if(train.iloc[:,i].dtypes == 'object'):\r\n train.iloc[:,i] = pd.Categorical(train.iloc[:,i])\r\n #print(marketing_train[[i]])\r\n train.iloc[:,i] = train.iloc[:,i].cat.codes \r\n train.iloc[:,i] = train.iloc[:,i].astype('object') \r\n lis.append(train.columns[i])\r\n \r\ncat_data=train.loc[:,lis] \r\nnum_data=train[['ID', 'Reputation', 'Answers', 'Username', 'Views', 'Upvotes']]\r\nnum_cols=num_data.columns\r\n\r\n\r\n###missing values\r\nmissing_values=train.isnull().sum()\r\n##no missing values in the dataset\r\n\r\n####outliers check\r\nimport matplotlib.pylab as pal\r\n \r\nfig,(ax1,ax2)=plt.subplots(1,2)\r\n\r\nax1.boxplot(train.iloc[:,6])\r\nax2.hist(train.iloc[:,6])\r\n\r\n\r\nfrom scipy import stats\r\nz=np.abs(stats.zscore(train['Reputation']))\r\n\r\n\r\nfor i in range(0,len(num_cols)):\r\n print(num_cols[i])\r\n q75, q25 = np.percentile(train[num_cols[i]], [75 ,25])\r\n iqr=q75-q25\r\n min=q25-(iqr*1.5)\r\n max=q75+(iqr*1.5)\r\n print(max)\r\n print(min)\r\n train.loc[train.loc[:,num_cols[i]] < min,num_cols[i]]=np.nan\r\n train.loc[train.loc[:,num_cols[i]] > max,num_cols[i]]=np.nan\r\n\r\n\r\n\r\n#Create dataframe with missing percentage\r\nmissing_val = pd.DataFrame(train.isnull().sum())\r\n\r\n#Reset index\r\nmissing_val = missing_val.reset_index()\r\n\r\n#Rename variable\r\nmissing_val = missing_val.rename(columns = {'index': 'Variables', 0: 'Missing_percentage'})\r\n\r\n#Calculate percentage\r\nmissing_val['Missing_percentage']= (missing_val['Missing_percentage']/len(train))*100\r\n\r\n#descending order\r\nmissing_val = missing_val.sort_values('Missing_percentage', ascending = False).reset_index(drop = True)\r\n\r\n#save output results \r\n#missing_val.to_csv(\"Miising_perc.csv\", inex = False)\r\n\r\n\r\n#####imputing mean values\r\ntrain=train.dropna(axis=0)\r\n\r\n#from sklearn.preprocessing import Imputer\r\n#values = train.values\r\n#imputer = Imputer(strategy='median')\r\n#transformed_values = imputer.fit_transform(values)\r\n#train=pd.DataFrame(transformed_values).round(2)\r\n#train.columns=columns\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nimport numpy as np\r\nimport statsmodels.api as sm\r\nimport pylab\r\n\r\n#test = np.random.normal(0,1, 1000)\r\n\r\nsm.qqplot(num_data.iloc[:,3], line='45')\r\npylab.show()\r\n\r\n\r\n\r\nfrom sklearn import preprocessing \r\n \r\n\"\"\" MIN MAX SCALER \"\"\"\r\nfrom sklearn.preprocessing import MinMaxScaler \r\nmin_max_scaler = preprocessing.MinMaxScaler(feature_range =(0, 1)) \r\n \r\n# Scaled feature \r\nx_after_min_max_scaler = min_max_scaler.fit_transform(num_data) \r\nnum_data=pd.DataFrame(x_after_min_max_scaler) \r\n\r\n\r\n\r\n\r\n\r\n#train['Reputation']=(train['Reputation'] - train['Reputation'].astype(int).min())/(train['Reputation'].astype(int).max() - train['Reputation'].astype(int).min())\r\n\r\n#train['Reputation'] = (train['Reputation'] - train['Reputation'].mean())/train['Reputation'].std()\r\n\r\n####feature selection\r\ndf_corr=train.loc[:,num_cols]\r\n#set the widhth and height of the plot\r\nf,ax=plt.subplots(figsize=(7,5))\r\n \r\ncorr=df_corr.corr() \r\n\r\n #Plot using seaborn library\r\nsns.heatmap(corr, mask=np.zeros_like(corr, dtype=np.bool), cmap=sns.diverging_palette(220, 10, as_cmap=True),\r\n square=True, ax=ax) \r\n###features reduction\r\ntrain=train.drop(['ID','Username'],axis=1)\r\n \r\n ##########splitting data \r\nX_train=train.iloc[:,0:4] \r\ny_train=train.iloc[:,4] \r\nfrom sklearn.model_selection import train_test_split \r\n#X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=0)\r\n#\r\n\r\n#from sklearn.preprocessing import StandardScaler\r\n#sc_X = StandardScaler()\r\n#X_train = sc_X.fit_transform(X_train)\r\n#X_test = sc_X.transform(X_test)\r\n#sc_y = StandardScaler()\r\n#y_train = sc_y.fit_transform(y_train)\r\n\r\n\r\n\r\n#####mulitlinear regression\r\n#from sklearn.linear_model import LinearRegression\r\n#regressor=LinearRegression()\r\n#regressor.fit(X_train,y_train)\r\n####predicting \r\n#y_pred_ml=regressor.predict(X_test)\r\n##regressor.summary()\r\n#\r\n#########building the optimal model\r\n#\r\n#import statsmodels.formula.api as sm\r\n#X=np.append(arr=X,values=np.ones((737453,1)).astype(int),axis=1)\r\n#\r\n#X1=X.iloc[:,:].values\r\n#X_opt=X1[:,:]\r\n#\r\n#import statsmodels.formula.api as sm\r\n#\r\n#regressor_OLS=sm.OLS(endog=y,exog=X).fit()\r\n#regressor_OLS.summary()\r\n#\r\n#################\r\n#from sklearn.metrics import mean_squared_error,mean_absolute_error,r2_score,regression,mean_squared_error\r\n#from math import sqrt\r\n#\r\n#\r\n#\r\n#def metrics(y_test,y_pred):\r\n# MSE=mean_squared_error(y_test,y_pred)\r\n# \r\n# MAE=mean_absolute_error(y_test,y_pred)\r\n# rmse=sqrt(mean_squared_error(y_test, y_pred))\r\n# r2=r2_score(y_test,y_pred)\r\n# adj_r2=1-(1-r2**2)*((X_test.shape[1]-1)/(X_test.shape[0]-X_test.shape[1]-1))\r\n# return MSE,MAE,rmse,r2,adj_r2\r\n# \r\n#\r\n#metrics(y_test,y_pred_ml)\r\n###############decision tree\r\n#from sklearn.tree import DecisionTreeRegressor\r\n#tree_regressor=DecisionTreeRegressor()\r\n#tree_regressor.fit(X_train,y_train)\r\n#y_dec_pre=tree_regressor.predict(X_test)\r\n##metrics(y_test,y_dec_pre)\r\n\r\n\r\n#####random forest regressor\r\nfrom sklearn.ensemble import RandomForestRegressor\r\ntree_rf=RandomForestRegressor()\r\ntree_rf=tree_rf.fit(X_train,y_train)\r\n#y_pre_rf=tree_rf.predict(X_test)\r\n##metrics(y_test,y_pre_rf)\r\n\r\n\r\n\r\n####saving to disc\r\nmodel=pickle.dump(tree_rf,open('upvotes.pkl','wb'))\r\n\r\n\r\n###loading model to compare the results\r\nmodel=pickle.load(open('upvotes.pkl','rb'))\r\n\r\nprint(tree_rf.predict([[0,3942.0,2.0,7855.0]]))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"model_upvotes.py","file_name":"model_upvotes.py","file_ext":"py","file_size_in_byte":5810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"176855395","text":"import inquirer\nfrom bestsellers import *\nfrom memory_profiler import profile\n\n@profile\ndef main():\n QUESTION_1 = \"Look up year range\"\n QUESTION_2 = \"Look up month/year\"\n QUESTION_3 = \"Search for author\"\n QUESTION_4 = \"Search for title\"\n QUESTION_5 = \"Quit\"\n\n questions = [\n inquirer.List(\"question\", message=\"What would you like to do?\", choices=[\n QUESTION_1, QUESTION_2, QUESTION_3, QUESTION_4, QUESTION_5\n ])\n ]\n\n answers = inquirer.prompt(questions)\n \n if answers['question'] == QUESTION_1:\n questions = [\n inquirer.Text(\"start_year\", message=\"Enter beginning year\"),\n inquirer.Text(\"end_year\", message=\"Enter ending year\")\n ]\n\n answers = inquirer.prompt(questions)\n find_by_year_range(\"./bestsellers.txt\", int(answers[\"start_year\"]), int(answers[\"end_year\"]))\n elif answers['question'] == QUESTION_2:\n questions = [\n inquirer.Text(\"month\", message=\"Enter month (as a number, 1-12)\"),\n inquirer.Text(\"year\", message=\"Enter year\")\n ]\n\n answers = inquirer.prompt(questions)\n find_by_month_year(\"./bestsellers.txt\", int(answers[\"month\"]), int(answers[\"year\"]))\n \n elif answers['question'] == QUESTION_3:\n questions = [\n inquirer.Text(\"author\", message=\"Enter an author's name (or part of a name)\"),\n ]\n\n answers = inquirer.prompt(questions)\n find_by_author(\"./bestsellers.txt\", answers[\"author\"])\n \n elif answers['question'] == QUESTION_4:\n questions = [\n inquirer.Text(\"title\", message=\"Enter a title (or part of a title)\"),\n ]\n\n answers = inquirer.prompt(questions)\n find_by_title(\"./bestsellers.txt\", answers[\"title\"])\n \n elif answers['question'] == QUESTION_5:\n print(\"Bye!\")\n exit()\n\n\n\n\nif __name__ == \"__main__\":\n while True:\n main()\n\n questions = [\n inquirer.Confirm(\"ask\", message=\"Do you want to continue?\")\n ]\n\n answers = inquirer.prompt(questions)\n\n if not answers['ask']:\n print(\"Bye!\")\n break\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"480708418","text":"from typing import Optional\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\n\ndef plot_adaboost(X: np.ndarray,\n y: np.ndarray,\n clf=None,\n sample_weights: Optional[np.ndarray] = None,\n annotate: bool = False,\n ax: Optional[mpl.axes.Axes] = None) -> None:\n \"\"\" Plot ± samples in 2D, optionally with decision boundary \"\"\"\n\n assert set(y) == {-1, 1}, 'Expecting response labels to be ±1'\n\n if not ax:\n fig, ax = plt.subplots(figsize=(5, 5), dpi=100)\n fig.set_facecolor('white')\n\n pad = 1\n x_min, x_max = X[:, 0].min() - pad, X[:, 0].max() + pad\n y_min, y_max = X[:, 1].min() - pad, X[:, 1].max() + pad\n\n if sample_weights is not None:\n sizes = np.array(sample_weights) * X.shape[0] * 100\n else:\n sizes = np.ones(shape=X.shape[0]) * 100\n\n X_pos = X[y == 1]\n sizes_pos = sizes[y == 1]\n ax.scatter(*X_pos.T, s=sizes_pos, marker='+', color='red')\n\n X_neg = X[y == -1]\n sizes_neg = sizes[y == -1]\n ax.scatter(*X_neg.T, s=sizes_neg, marker='.', c='blue')\n\n if clf:\n plot_step = 0.01\n xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step),\n np.arange(y_min, y_max, plot_step))\n\n Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])\n Z = Z.reshape(xx.shape)\n\n # If all predictions are positive class, adjust color map acordingly\n if list(np.unique(Z)) == [1]:\n fill_colors = ['r']\n else:\n fill_colors = ['b', 'r']\n\n ax.contourf(xx, yy, Z, colors=fill_colors, alpha=0.2)\n\n if annotate:\n for i, (x, y) in enumerate(X):\n offset = 0.05\n ax.annotate(f'$x_{i + 1}$', (x + offset, y - offset))\n\n ax.set_xlim(x_min + 0.5, x_max - 0.5)\n ax.set_ylim(y_min + 0.5, y_max - 0.5)\n ax.set_xlabel('$x_1$')\n ax.set_ylabel('$x_2$')\n\n\ndef truncate_adaboost(clf, t: int):\n \"\"\" Truncate a fitted AdaBoost up to (and including) a particular iteration \"\"\"\n assert t > 0, 't must be a positive integer'\n from copy import deepcopy\n new_clf = deepcopy(clf)\n new_clf.stumps = clf.stumps[:t]\n new_clf.stump_weights = clf.stump_weights[:t]\n return new_clf\n\n\ndef plot_staged_adaboost(X, y, clf, iters=10):\n \"\"\" Plot weak learner and cumulaive strong learner at each iteration. \"\"\"\n\n # larger grid\n fig, axes = plt.subplots(figsize=(8, iters * 3),\n nrows=iters,\n ncols=2,\n sharex=True,\n dpi=50) # changed from dpi=100\n\n fig.set_facecolor('white')\n\n _ = fig.suptitle('Decision boundaries by iteration')\n for i in range(iters):\n ax1, ax2 = axes[i]\n\n # Plot weak learner\n _ = ax1.set_title(f'\\n\\nα(t) = {clf.stump_weights[i]}, ε(t) = {clf.errors[i]}\\nWeak learner at t={i + 1}')\n plot_adaboost(X, y, clf.stumps[i],\n sample_weights=clf.sample_weights[i],\n annotate=False, ax=ax1)\n\n # Plot strong learner\n trunc_clf = truncate_adaboost(clf, t=i + 1)\n _ = ax2.set_title(f'Strong learner at t={i + 1}')\n plot_adaboost(X, y, trunc_clf,\n sample_weights=clf.sample_weights[i],\n annotate=False, ax=ax2)\n\n plt.tight_layout()\n plt.subplots_adjust(top=0.95)\n plt.show()\n","sub_path":"PlotAdaBoost.py","file_name":"PlotAdaBoost.py","file_ext":"py","file_size_in_byte":3451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"30068062","text":"'''\nAny two nodes in a binary tree have a common ancestor, namely the root. \nThe lowest comon ancestor (LCA) of any two nodes in a binary tree is the node furthest from \nthe root that is an ancestor of both nodes.\n\nDesign an algorithm for computing the LCA of 2 nodes in a binary tree in which nodes do not\nhave a parent field.\n'''\nclass BinaryTreeNode:\n def __init__(self, data=None, left=None, right=None):\n self.data = data\n self.left = left\n self.right = right\n\ntree = BinaryTreeNode(3, \n BinaryTreeNode(5, BinaryTreeNode(6), BinaryTreeNode(2, BinaryTreeNode(7), BinaryTreeNode(4))), \n BinaryTreeNode(1, BinaryTreeNode(0), BinaryTreeNode(8)))\n\n'''\nMy approach: Traverse till we find 1st node. Record all parents we've visit thus far.\nDo the same to find node2.\nAt this point we found ancestors for node1 and node2. Finding the LCA is trivial.\nTime-complexity: O(n^2) because we traverse the array1 and see if an element exist\nin array2. This can be O(2n) if we use a hash for the 2nd node traversal\naccumulation. We would travese the first array and check if element is in hash\n\nSpace-complexity: O(2h) because we stored parents for traversals. Not to mention, we also have\ncall stacks\n'''\n\n'''\ndef lca(tree, node0, node1):\n nodes_ancestors = []\n\n # Find the node and collect all of its ancestors\n def preOrderTraverse(tree, node, ancestors):\n if not tree:\n return\n ancestors.append(tree.data)\n\n if tree.data == node:\n nodes_ancestors.append(ancestors)\n return\n\n preOrderTraverse(tree.left, node, list(ancestors))\n preOrderTraverse(tree.right, node, list(ancestors))\n return\n \n preOrderTraverse(tree, node0, [])\n preOrderTraverse(tree, node1, [])\n for i in reversed(range(len(nodes_ancestors[0]))):\n if nodes_ancestors[0][i] in nodes_ancestors[1]:\n return nodes_ancestors[0][i]\n\n'''\n\n'''\nEPI Solution: We do not need to perform multiple passes. If the two nodes are in a subtree,\nwe can compute the LCA directly, instead of simply returning a Boolean indicating that both\nnodes are in that subtree. The program below returns an object with 2 fields-the first is\nan integer indicating how many of the 2 nodes were present in that subtree, and the second\nis their LCA, if both nodes were present.\n\nThe algorithm is structurally similar to a recursive postorder traversal, and the complexities\nare the same. Specifically, the time complexity and space complexity are O(n) and O(h),\nrespectively, where h is the height of the tree\n'''\nimport collections\ndef lca(tree, node0, node1):\n Status = collections.namedtuple('Status', ('num_target_nodes', 'ancestor'))\n\n # Returns an object consisting of an int and a node. The int field is 0,\n # 1, or 2 depending on how many of {node0, node1} are present in tree. If\n # both are present in tree, when ancestor is assigned to a non-null value,\n # it is the LCA.\n def lca_helper(tree, node0, node1):\n if not tree:\n return Status(0, None)\n \n left_result = lca_helper(tree.left, node0, node1)\n if left_result.num_target_nodes == 2:\n # Found both nodes in the left subtree.\n return left_result\n \n right_result = lca_helper(tree.right, node0, node1)\n if right_result.num_target_nodes == 2:\n # Found both nodes in right subtree.\n return right_result\n \n num_target_nodes = (\n left_result.num_target_nodes + right_result.num_target_nodes + \n (node0, node1).count(tree))\n return Status(num_target_nodes, tree\n if num_target_nodes == 2 else None)\n\n x = lca_helper(tree, node0, node1).ancestor\n return x\n\nnode0 = tree.left\nnode1 = tree.left.right.right\nresult = lca(tree, node0, node1)\nprint(result)\n\n ","sub_path":"Python/EPI/Binary Trees/lca_no_parent.py","file_name":"lca_no_parent.py","file_ext":"py","file_size_in_byte":3862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"325531466","text":"from django.db import models\nfrom django.contrib.auth.models import User\n# from movieratings.models import Movie, Rater, Rating\n# from django.contrib.auth import get_user_model\n\nclass Movie(models.Model):\n title = models.CharField(max_length=200)\n genre = models.CharField(max_length=200)\n\n def __str__(self):\n return \"{}, {}\".format(self.title, self.genre)\n\n\nclass Rater(models.Model):\n gender = models.CharField(max_length=2)\n age = models.IntegerField()\n occupation = models.IntegerField()\n user = models.OneToOneField(User, null=True)\n # zipcode = models.CharField(max_length=10)\n\n def __str__(self):\n return \"{}: {}, {}, {}\".format(self.id, self.gender, self.age, self.occupation)\n\n def get_allratings_of_rater(name_id):\n all_rater_ratings = Rater.objects.all(id=name_id)\n return all_rater_ratings\n\n def get_average_rating_of_this_rater(name_id):\n all_of_his_ratings = Rater.get_allratings_of_rater.objects.filter(name_id)\n total = sum(all_of_his_ratings) / all_of_his_ratings.objects.all().count()\n return total\n\n\nclass Rating(models.Model):\n score = models.IntegerField()\n # timestamp = models.DateTimeField()\n movie = models.ForeignKey(Movie, on_delete=models.CASCADE)\n rater = models.ForeignKey(Rater, on_delete=models.CASCADE)\n\n def __str__(self):\n return (\"{}. {} - {}. {} - {}.\".format(self.score, self.movie, self.rater))\n\n\nclass Occupation(models.Model):\n\n ACADEMIC = 'academic/educator'\n ARTIST = 'artist'\n CLERICAL = 'clerical/admin'\n COLLEGE = 'college/grad student'\n CUSTOMER = 'customer service'\n DOCTOR = 'doctor/health care'\n EXECUTIVE = 'executive/managerial'\n FARMER = 'farmer'\n HOMEMAKER = 'homemaker'\n STUDENT = 'K-12 student'\n LAWYER = 'lawyer'\n PROGRAMMER = 'programmer'\n RETIRED = 'retired'\n SALES = 'sales/marketing'\n SCIENTIST = 'scientist'\n SELF = 'self-employed'\n TECHNICIAN = 'technician/engineer'\n TRADESMAN = 'tradesman/craftsman'\n UNEMPLOYED = 'unemployed'\n WRITER = 'writer'\n\n\n STATUS_CHOICES = ((0, 'other'), (1, 'academic/educator'), (2, 'artist'),\n (3, 'clerical/admin'), (4, 'college/grad student'), (5, 'customer service'),\n (6, 'doctor/health care'), (7, 'executive/managerial'), (8, 'farmer'),\n (9, 'homemaker'), (10, 'K-12 student'), (11, 'lawyer'), (12, 'programmer'),\n (13, 'retired'), (14, 'sales/marketing'), (15, 'scientist'),\n (16, 'self-employed'), (17, 'technician/engineer'), (18, 'tradesman/craftsman'),\n (19, 'unemployed'), (20, 'writer'))\n\n occupation_word = models.CharField(max_length=44, choices=STATUS_CHOICES)\n\n rater = models.ForeignKey(Rater, on_delete=models.CASCADE)\n\n def change_occupation(self):\n return self.occupation_word\n\n # all_raters = Rater.objects.all()\n # for each in all_raters:\n # temp = each.occupation\n # change = Rater.objects.update(each.occupation = occ_key[temp])\n\n # def specific_movie_rating(name_id):\n # all_movie_ratings = Rating.objects.filter(movie_id=name_id)\n # return all_movie_ratings\n #\n # def get_movie_average_rating(which_one):\n # too_few = False\n # the_movie = Rating.objects.filter(movie_id=which_one)\n # agg_score = 0\n # for each in the_movie:\n # agg_score += each.score\n # try:\n # avg_rating = agg_score/len(the_movie)\n # except:\n # avg_rating = 0\n #\n # if len(the_movie) < 20:\n # too_few = True\n # return (avg_rating, too_few)\n #\n # def get_top_rated_movies(num):\n # averages = []\n # top = []\n # top_movies = Movie.objects.all().count()\n # for i in range(top_movies):\n # avg, not_enough_reviews = Rating.get_movie_average_rating(i+1)\n # if not_enough_reviews is False:\n # averages.append((avg, i+1))\n # print(\"\\n\"*50)\n # c = (i+1) / 1683\n # print(\"Percentage complete: \", c, \"%\")\n # averages.sort(reverse=True)\n # for i in range(num):\n # top.append(averages[i])\n # return top # returns list of TUPLES !\n","sub_path":"movielens/movieratings/models-TRW.py","file_name":"models-TRW.py","file_ext":"py","file_size_in_byte":4298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"607354983","text":"class Node:\n def __init__(self, value, next_node=None):\n self.value = value\n self.next_node = next_node\n\n def get_value(self):\n return self.value\n\n def get_next_node(self):\n return self.next_node\n\n def set_next_node(self, next_node):\n self.next_node = next_node\n\n\nclass LinkedList:\n def __init__(self, value=None):\n self.head_node = Node(value)\n\n def get_head_node(self):\n return self.head_node\n\n def insert_beginning(self, new_value):\n new_node = Node(new_value)\n new_node.set_next_node(self.head_node)\n self.head_node = new_node\n\n def remove_node(self, value_to_remove):\n current_node = self.head_node\n if current_node.get_value() == value_to_remove:\n self.head_node = current_node.get_next_node()\n while current_node:\n next_node = current_node.get_next_node()\n\n if next_node == None:\n break\n\n if next_node.get_value() == value_to_remove:\n current_node.set_next_node(next_node.get_next_node())\n next_node = None\n\n current_node = current_node.get_next_node()\n return\n\n def stringify_list(self):\n string_list = ''\n current_node = self.get_head_node()\n while current_node:\n if current_node.value != None:\n string_list += str(current_node.get_value())\n\n current_node = current_node.get_next_node()\n return string_list\n\n\nll = LinkedList('D')\nll.insert_beginning('C')\nll.insert_beginning('B')\nll.insert_beginning(\"A\")\nll.insert_beginning('F')\nll.insert_beginning('G')\nll.insert_beginning(\"H\")\nll.remove_node('D')\nll.remove_node('C')\nll.remove_node('H')\n\nprint(ll.stringify_list())\n\n\n\n\n\n","sub_path":"data_structures/linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"340099843","text":"from tkinter import *\nfrom tkinter import ttk\nfrom alg_crypt import railEncrypt, railDecrypt\n\ndef getRails():\n try:\n value = int(rails.get())\n except ValueError:\n value = 0\n return value\n \ndef encrypt(*args):\n strIn = ''.join([x.lower() for x in decStr.get() if x.isalpha()])\n if not strIn:\n return\n value = getRails()\n if value <= 0 or value >= len(strIn):\n return\n strOut = railEncrypt(strIn, value)\n encStr.set(strOut)\n \ndef decrypt(*args):\n strIn = ''.join([x.lower() for x in encStr.get() if x.isalpha()])\n if not strIn:\n return\n value = getRails()\n if value <= 0 or value >= len(strIn):\n return\n strOut = railDecrypt(strIn, value)\n decStr.set(strOut)\n \nroot = Tk()\nroot.title('Rail fence cipher')\n\nmainframe = ttk.Frame(root)\nmainframe.grid(column=0, row=0)\nmainframe.columnconfigure(0, weight=1)\nmainframe.rowconfigure(0, weight=1)\n\ndecStr = StringVar()\nencStr = StringVar()\nrails = StringVar()\n\nttk.Label(mainframe, text='Decrypted').grid(column=1, row=1)\ndec_entry = ttk.Entry(mainframe, width=30, textvariable=decStr)\ndec_entry.grid(column=2, row=1)\nttk.Button(mainframe, text='Encrypt', command=encrypt).grid(column=3, row=1)\n\nttk.Label(mainframe, text='Encrypted').grid(column=1, row=2)\nenc_entry = ttk.Entry(mainframe, width=30, textvariable=encStr)\nenc_entry.grid(column=2, row=2)\nttk.Button(mainframe, text='Decrypt', command=decrypt).grid(column=3, row=2)\n\nttk.Label(mainframe, text='Rails').grid(column=1, row=3)\nrails_entry = ttk.Entry(mainframe, width=2, textvariable=rails)\nrails_entry.grid(column=2, row=3, sticky=W)\n\nfor child in mainframe.winfo_children(): \n child.grid_configure(padx=5, pady=5)\n\nroot.mainloop()\n","sub_path":"Cryptography1/tkfence.py","file_name":"tkfence.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"3754390","text":"import unittest\nfrom stolas.markov import MarkovChain, Word\n\n\nclass MarkovChainParseTestCase(unittest.TestCase):\n \"\"\"Tests for MarkovChain.parse\"\"\"\n\n def test_internal_parsed_flag_set(self):\n # Calling parse method should set _parsed to True\n\n markov = MarkovChain(order=1)\n self.assertEqual(markov._parsed, False)\n markov.parse(\"It is a truth universally acknowledged, \"\n \"that a single man in possession of a good \"\n \"fortune must be in want of a wife.\")\n self.assertEqual(markov._parsed, True)\n\n def test_parse_valid_text(self):\n # Parse method should set .chain correctly\n\n markov = MarkovChain(order=1)\n self.assertEqual(markov._chain, {})\n\n input_text = \"a b c\"\n markov.parse(input_text)\n\n self.assertEqual(\n set(markov._chain.keys()),\n set(['a', 'b'])\n )\n\n self.assertEqual(\n markov._chain['a'],\n [Word('b', 1)]\n )\n\n self.assertEqual(\n markov._chain['b'],\n [Word('c', 1)]\n )\n\n def test_at_sign_not_parsed(self):\n # In order to avoid tooting random people\n # the @ character must never enter the chain\n # and should be ignored\n\n markov = MarkovChain(order=1)\n self.assertEqual(markov._chain, {})\n\n input_text = \"a b @d c\"\n markov.parse(input_text)\n\n self.assertEqual(\n set(markov._chain.keys()),\n set(['a', 'b'])\n )\n\n self.assertEqual(\n markov._chain['a'],\n [Word('b', 1)]\n )\n\n self.assertEqual(\n markov._chain['b'],\n [Word('c', 1)]\n )\n\n def test_multiple_parse_calls(self):\n # Calling parse more than one should\n # append to the existing chain\n # but each call should be seperate\n\n markov = MarkovChain(order=1)\n self.assertEqual(markov._chain, {})\n\n input_text_one = \"a b c\"\n input_text_two = \"d e f\"\n\n # Note that c does NOT go to d\n markov.parse(input_text_one)\n markov.parse(input_text_two)\n\n self.assertEqual(\n set(markov._chain.keys()),\n set(['a', 'b', 'd', 'e'])\n )\n\n self.assertEqual(\n markov._chain['a'],\n [Word('b', 1)]\n )\n\n self.assertEqual(\n markov._chain['b'],\n [Word('c', 1)]\n )\n\n self.assertEqual(\n markov._chain['d'],\n [Word('e', 1)]\n )\n\n self.assertEqual(\n markov._chain['e'],\n [Word('f', 1)]\n )\n\n def test_parse_newlinest(self):\n # Newlines must be treated like any other character\n\n markov = MarkovChain(order=1)\n self.assertEqual(markov._chain, {})\n\n input_text = \"a \\nb \\nc\\nAAA end\"\n markov.parse(input_text)\n\n self.assertEqual(\n set(markov._chain.keys()),\n set(['a', '\\nb', '\\nc\\nAAA'])\n )\n\n self.assertEqual(\n markov._chain['a'],\n [Word('\\nb', 1)]\n )\n\n self.assertEqual(\n markov._chain['\\nb'],\n [Word('\\nc\\nAAA', 1)]\n )\n\n def test_order_four_input(self):\n input_text = (\"According to all known laws of aviation,\"\n \"there is no way a bee should be able to fly.\")\n\n markov = MarkovChain(order=4)\n\n markov.parse(input_text)\n\n self.assertIn(\"According to all known\", markov._chain.keys())\n self.assertEqual(\n markov._chain[\"According to all known\"],\n [Word(\"laws\", 1)]\n )\n\n self.assertIn(\"is no way a\", markov._chain.keys())\n self.assertEqual(\n markov._chain[\"is no way a\"],\n [Word(\"bee\", 1)]\n )\n\n self.assertIn(\"should be able to\", markov._chain.keys())\n self.assertEqual(\n markov._chain[\"should be able to\"],\n [Word(\"fly.\", 1)]\n )\n\n def test_duplicate_parsing_files(self):\n input_text = (\"According to all known laws of aviation,\"\n \"there is no way a bee should be able to fly.\")\n\n markov = MarkovChain(order=4)\n\n markov.parse(input_text)\n markov.parse(input_text)\n markov.parse(input_text)\n markov.parse(input_text)\n\n self.assertIn(\"According to all known\", markov._chain.keys())\n self.assertEqual(\n markov._chain[\"According to all known\"],\n [Word(\"laws\", 1)]\n )\n\n self.assertIn(\"is no way a\", markov._chain.keys())\n self.assertEqual(\n markov._chain[\"is no way a\"],\n [Word(\"bee\", 1)]\n )\n\n self.assertIn(\"should be able to\", markov._chain.keys())\n self.assertEqual(\n markov._chain[\"should be able to\"],\n [Word(\"fly.\", 1)]\n )\n\n\nclass MarkovChainRandomWordTestCase(unittest.TestCase):\n \"\"\"Tests for MarkovChain._get_random_word\"\"\"\n\n def test_single_option(self):\n\n markov = MarkovChain()\n markov._chain = {\n 'START': [\n Word('A', 1)\n ]\n }\n\n for _ in range(1000):\n letter = markov._get_random_word('START')\n self.assertEqual(letter, 'A')\n\n def test_even_odds(self):\n\n markov = MarkovChain()\n markov._chain = {\n 'START': [\n Word('A', 10),\n Word('B', 10)\n ]\n }\n\n a_count = 0\n b_count = 0\n for _ in range(10000):\n letter = markov._get_random_word('START')\n\n if letter == 'A':\n a_count += 1\n elif letter == 'B':\n b_count += 1\n else:\n self.fail(\"Expected 'A' or 'B' got {0}\".format(\n letter\n ))\n\n self.assertEqual(a_count + b_count, 10000)\n self.assertGreaterEqual(a_count, 4500)\n self.assertLessEqual(a_count, 5500)\n\n def test_10_1_odds(self):\n\n markov = MarkovChain()\n markov._chain = {\n 'START': [\n Word('A', 10),\n Word('B', 1)\n ]\n }\n\n a_count = 0\n b_count = 0\n for _ in range(10000):\n letter = markov._get_random_word('START')\n\n if letter == 'A':\n a_count += 1\n elif letter == 'B':\n b_count += 1\n else:\n self.fail(\"Expected 'A' or 'B' got {0}\".format(\n letter\n ))\n\n self.assertEqual(a_count + b_count, 10000)\n self.assertGreaterEqual(a_count, 9000)\n\n\nclass MarkovChainGetTextTestCase(unittest.TestCase):\n \"\"\"Tests for MarkovChain.get_text\"\"\"\n\n def test_get_text_null_input(self):\n # If we have nothing in _chain then we\n # want to return an empty string\n\n markov = MarkovChain(order=4)\n self.assertEqual(markov._chain, {})\n self.assertEqual(markov._parsed, False)\n\n output = markov.get_text()\n self.assertEqual(output, \"\")\n\n def test_get_text_length(self):\n\n markov = MarkovChain(order=4)\n markov.parse(\"a b c d e f g\")\n\n output = markov.get_text(length=200)\n self.assertLessEqual(len(output), 200)\n\n def test_run_on_bug(self):\n # There was a bug causing the ends of sentences\n # to get mauled\n\n markov = MarkovChain(order=2)\n markov.parse(\"a b a b a b a b a b\")\n\n output = markov.get_text(1000)\n self.assertNotIn(\"ab\", output)\n\n def test_start_words_used(self):\n # Check that we actually use the start words\n\n markov = MarkovChain(order=1)\n markov.parse(\"a b c b c b c b c b\")\n\n output = markov.get_text(1000)\n if not output.startswith(\"a\"):\n self.fail(\"Output did not start with a!\")\n\n\nclass MarkovChainErrorTestCase(unittest.TestCase):\n\n def test_order_zero_raises_exception(self):\n with self.assertRaises(ValueError):\n MarkovChain(order=0)\n\n def test_order_negative_raises_exception(self):\n with self.assertRaises(ValueError):\n MarkovChain(order=-1)\n\n def test_order_string_raises_exception(self):\n with self.assertRaises(ValueError):\n MarkovChain(order=\"four\")\n\n\nclass MarkovChainSentenceStartTestCase(unittest.TestCase):\n \"\"\"Tests for MarkovChain.start_words\"\"\"\n\n def test_null_parsing(self):\n # We should have an empty list for start_words\n # if we have not parsed owt\n\n markov = MarkovChain(order=2)\n\n self.assertEqual(markov._start_words, [])\n\n def test_single_input_order_one(self):\n input_text = (\"According to all known laws of aviation,\"\n \"there is no way a bee should be able to fly.\")\n\n markov = MarkovChain(order=1)\n\n markov.parse(input_text)\n\n self.assertEqual(\n markov._start_words,\n [\"According\"]\n )\n\n def test_single_input_order_four(self):\n input_text = (\"According to all known laws of aviation,\"\n \"there is no way a bee should be able to fly.\")\n\n markov = MarkovChain(order=4)\n\n markov.parse(input_text)\n\n self.assertEqual(\n markov._start_words,\n [\"According to all known\"]\n )\n\n self.assertIn(markov._start_words[0], markov._chain.keys())\n\n def test_multiple_inputs(self):\n markov = MarkovChain(order=1)\n\n markov.parse(\"Hello there!\")\n markov.parse(\"Tired: Single line content\\n\"\n \"Wired: Multiple lines of content\")\n markov.parse(\"Yet more content\")\n\n self.assertEqual(\n markov._start_words,\n [\"Hello\", \"Tired:\", \"Yet\"]\n )\n\n def test_at_filtered_out(self):\n markov = MarkovChain(order=1)\n\n markov.parse(\"@a_person Hello there!\")\n\n self.assertEqual(\n markov._start_words,\n [\"Hello\"]\n )\n","sub_path":"stolas/tests/test_markov.py","file_name":"test_markov.py","file_ext":"py","file_size_in_byte":10043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"96240711","text":"\"\"\"The \"Bob\" exercise\"\"\"\n#\n# Skeleton file for the Python \"Bob\" exercise.\n#\n\ndef hey(what):\n \"\"\"Bob's response\"\"\"\n\n what = what.strip()\n\n is_yelling = what.isupper()\n are_words = any(c.isalpha() for c in what)\n\n if what == \"\":\n return 'Fine. Be that way!'\n\n if is_yelling and are_words:\n return 'Whoa, chill out!'\n\n if what[-1] == \"?\":\n return 'Sure.'\n\n return 'Whatever.'\n","sub_path":"all_data/exercism_data/python/bob/8da4e5dfce23475b97a8f660d2278710.py","file_name":"8da4e5dfce23475b97a8f660d2278710.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"515367357","text":"pg_stocks=[\n\"ACES\"\n, \"ACIC\"\n, \"AEVA\"\n, \"AGC\"\n, \"AGE\"\n, \"AGTC\"\n, \"AHCO\"\n, \"ALAC\"\n, \"AMRK\"\n, \"APPH\"\n, \"APSG\"\n, \"ARKF\"\n, \"ARKG\"\n, \"ARKK\"\n, \"ARKQ\"\n, \"ARKW\"\n, \"ARKX\"\n, \"ARVL\"\n, \"ASM\"\n, \"ASTR\"\n, \"AVPT\"\n, \"AYRO\"\n, \"BAR\"\n, \"BEDZ\"\n, \"BEEM\"\n, \"BETZ\"\n, \"BLDE\"\n, \"BLNK\"\n, \"BLOK\"\n, \"BND\"\n, \"BNGO\"\n, \"BOTZ\"\n, \"BSN\"\n, \"BTWN\"\n, \"BUG\"\n, \"BYND\"\n, \"CANO\"\n, \"CELU\"\n, \"CGC\"\n, \"CHEK\"\n, \"CHPT\"\n, \"CLOU\"\n, \"CNRG\"\n, \"CODX\"\n, \"COMB\"\n, \"COPX\"\n, \"CPER\"\n, \"CTEC\"\n, \"DCRN\"\n, \"DEH\"\n, \"DIDI\"\n, \"DM\"\n, \"DMYQ\"\n, \"DNNGY\"\n, \"EATZ\"\n, \"EDUT\"\n, \"ELMS\"\n, \"ETCG\"\n, \"EVGN\"\n, \"EVGO\"\n, \"FAN\"\n, \"FFIE\"\n, \"FINX\"\n, \"FLNT\"\n, \"FREQ\"\n, \"FREY\"\n, \"FTCV\"\n, \"FUSE\"\n, \"FUV\"\n, \"GBTC\"\n, \"GELYY\"\n, \"GENI\"\n, \"GERM\"\n, \"GLD\"\n, \"GLDM\"\n, \"GMBTU\"\n, \"GOEV\"\n, \"GOLD\"\n, \"GP\"\n, \"GRNV\"\n, \"HTEC\"\n, \"HTOO\"\n, \"HYLN\"\n, \"HYRE\"\n, \"IBIO\"\n, \"ICLN\"\n, \"ID\"\n, \"IDIV\"\n, \"INDI\"\n, \"INO\"\n, \"INVZ\"\n, \"IPO\"\n, \"IPOS\"\n, \"IRBO\"\n, \"IRDM\"\n, \"ITAC\"\n, \"IZRL\"\n, \"JMIA\"\n, \"KNDI\"\n, \"LAZR\"\n, \"LCID\"\n, \"LEV\"\n, \"LGHL\"\n, \"LI\"\n, \"LIT\"\n, \"LSF\"\n, \"ME\"\n, \"MITC\"\n, \"MJ\"\n, \"MOTN\"\n, \"MPLN\"\n, \"MSOS\"\n, \"MVP\"\n, \"MVST\"\n, \"NERD\"\n, \"NGAC\"\n, \"NIO\"\n, \"NKLA\"\n, \"NNDM\"\n, \"NNOX\"\n, \"NVVE\"\n, \"OBCI\"\n, \"OLD\"\n, \"ONLN\"\n, \"OPEN\"\n, \"ORA\"\n, \"ORGN\"\n, \"OUST\"\n, \"PAYO\"\n, \"PBD\"\n, \"PBW\"\n, \"PHGE\"\n, \"PLTR\"\n, \"POTX\"\n, \"PRNT\"\n, \"PSFE\"\n, \"PSTH\"\n, \"PTRA\"\n, \"QCLN\"\n, \"QELL\"\n, \"QQQJ\"\n, \"QS\"\n, \"REE\"\n, \"RIDE\"\n, \"RKFL\"\n, \"RMO\"\n, \"RMTI\"\n, \"JOBY\"\n, \"HIPO\"\n, \"SEER\"\n, \"SFTW\"\n, \"SFYF\"\n, \"SNPR\"\n, \"SOFI\"\n, \"SOLO\"\n, \"SPAK\"\n, \"SPCX\"\n, \"SPFR\"\n, \"SPRB\"\n, \"SVOK\"\n, \"SWBK\"\n, \"TAN\"\n, \"TBLA\"\n, \"THCX\"\n, \"TLMD\"\n, \"TLRY\"\n, \"TPAY\"\n, \"TPGY\"\n, \"TRIB\"\n, \"TTCF\"\n, \"U\"\n, \"UFO\"\n, \"USO\"\n, \"VERU\"\n, \"VGLT\"\n, \"VIAC\"\n, \"VIAO\"\n, \"VLDR\"\n, \"VPN\"\n, \"VTI\"\n, \"VWAGY\"\n, \"VWE\"\n, \"WKHS\"\n, \"WMT\"\n, \"WOOD\"\n, \"XBI\"\n, \"XL\"\n, \"XPEV\"\n, \"YOLO\"\n, \"ZEV\"\n, \"ZIM\"\n, \"ZOM\"\n, \"XL\"\n, \"XLC\"\n, \"XPEV\"\n, \"YOLO\"\n, \"ZEV\"\n, \"ZIM\"\n, \"ZOM\"]\n","sub_path":"pg_stocks.py","file_name":"pg_stocks.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"85107404","text":"#!/usr/bin/env python3\n\n'''\nDownload countline data for one or more days and store it\nin json files in ACP style\n'''\n\n\nimport argparse\nimport json\nimport os\nimport sys\n\nfrom datetime import datetime, date, time, timedelta, timezone\n\nimport dateutil.parser\n\nimport requests\n\nCOUNTLINES = {\n '13079': {'name': 'Milton Road', 'in': 'NE-bound', 'out': 'SW-bound'},\n }\n\n\nVCLASSES = (\"pedestrian\", \"cyclist\", \"motorbike\", \"car\",\n \"taxi\", \"van\", \"minibus\", \"bus\", \"rigid\",\n \"truck\", \"emergency car\", \"emergency van\",\n \"fire engine\")\n\n\nFIVE_MINUTES = timedelta(minutes=5)\nONE_HOUR = timedelta(hours=1)\nONE_DAY = timedelta(days=1)\nMIDNIGHT = time(tzinfo=timezone.utc)\n\n\nusername = os.getenv('USERNAME')\npassword = os.getenv('PASSWORD')\n\ntoken = None\n\n\ndef vivacity_time(t):\n '''\n Return t as a string in the particular version of ISO8601\n expected by the Vivacity API\n '''\n\n return (t.astimezone(tz=timezone.utc)\n .replace(tzinfo=None)\n .isoformat(timespec='milliseconds') + 'Z')\n\n\ndef get_token():\n\n print('Getting a new token', file=sys.stderr)\n\n assert username is not None and password is not None, (\n 'USERNAME and/or PASSWORD environment variable missing')\n\n r = requests.post(\n 'https://api.vivacitylabs.com/get-token',\n data={'username': username, 'password': password},\n headers={'api-version': '2'}\n )\n r.raise_for_status()\n global token\n token = r.json()\n token['ts'] = datetime.utcnow()\n\n\ndef get_data(start, duration):\n '''\n Get raw data for time range `start` to `start+duration`\n '''\n\n # Get or renew the token as needed\n if not token or (datetime.utcnow()-token['ts']).total_seconds() > 0.9*token['expires_in']:\n get_token()\n\n headers = {\n 'api-version': '2',\n 'Authorization': 'Bearer ' + token['access_token']\n }\n\n params = {\n 'timeFrom': vivacity_time(start),\n 'timeTo': vivacity_time(start+duration),\n }\n\n r = requests.get(\n 'https://api.vivacitylabs.com/counts',\n params=params,\n headers=headers\n )\n r.raise_for_status()\n if r.status_code == 204:\n return {}\n else:\n return r.json()\n\n\ndef store_data(results, directory):\n '''\n Store the data in `results` in conventional ACP format in `directory`\n\n Results:\n {\n : {\n : {\n : [\n {\n time: ,\n counts: {\n : count,\n ...\n },\n ...\n ],\n ...\n },\n ...\n },\n ...\n }\n\n '''\n\n for this_date, day_data in results.items():\n\n day_dir = os.path.join(\n directory,\n this_date.strftime('%Y'),\n this_date.strftime('%m'),\n this_date.strftime('%d'))\n os.makedirs(day_dir, exist_ok=True)\n\n for countline, countline_data in day_data.items():\n\n countline_dir = os.path.join(day_dir, countline)\n os.makedirs(countline_dir, exist_ok=True)\n\n for direction, count_blocks in countline_data.items():\n\n filename = os.path.join(countline_dir, direction + '.txt')\n with open(filename, 'w') as file:\n for count_block in count_blocks:\n json.dump(count_block, file)\n file.write('\\n')\n\n\ndef accumulate_data(results, response, start, duration):\n '''\n Add API response data in `response` to `results` for each countline\n in COUNTLINES, assuming that `response` contains data for the period\n `start` to `start+duration` in 5 minute lumps.\n\n Include counts for all countlines, for all possible classes of vehicle\n (even if zero) and data for every 5 minute lump, even if all readings\n are zero (which is why we need COUNLINES, VCLASSES and `start` and\n `duration` - we can't derive them from what's in `results` because\n it could in principle be empty)\n\n API data:\n\n {\n : {\n : {\n \"from\": ,\n \"to\": \n \"counts\": [\n {\n \"class\": ,\n \"countIn\": ,\n \"countOut\": \n },\n ...\n ]\n },\n ...\n },\n ...\n }\n\n Results has a top-level grouping by `date` to make directory and\n file management easier.\n\n Results:\n {\n : {\n : {\n : [\n {\n time: ,\n counts: {\n : count,\n ...\n },\n ...\n ],\n ...\n },\n ...\n },\n ...\n }\n\n '''\n\n # For each countline in `response`...\n for countline in COUNTLINES:\n countline_data = response.get(countline, {})\n\n # ...loop over the timestamped observations\n this_time = start\n while this_time < start+duration:\n\n date = this_time.date()\n observation = countline_data.get(vivacity_time(this_time), {'counts': []})\n\n # Add empty dicts to `results` as needed\n if date not in results:\n results[date] = {}\n if countline not in results[date]:\n results[date][countline] = {}\n\n # For each possible direction\n for their_direction, our_direction in {'countIn': 'in', 'countOut': 'out'}.items():\n\n # Add an empty list if needed\n if our_direction not in results[date][countline]:\n results[date][countline][our_direction] = []\n\n # populate a results block and append it to results\n block = {\n 'ts': this_time.timestamp(),\n 'timestamp': this_time.isoformat(),\n 'from': observation.get('from', None),\n 'to': observation.get('to', None),\n 'countline': countline,\n 'direction': our_direction,\n 'counts': {vclass: 0 for vclass in VCLASSES}\n }\n for count in observation['counts']:\n block['counts'][count['class']] = count[their_direction]\n results[date][countline][our_direction].append(block)\n\n this_time += FIVE_MINUTES\n\n\ndef get_day(date, path):\n '''\n Get data for one day in one hour chunks and store it\n '''\n\n print('Processing', date, file=sys.stderr)\n\n time = datetime.combine(date, MIDNIGHT)\n results = {}\n\n for counter in range(24):\n response = get_data(time, ONE_HOUR)\n accumulate_data(results, response, time, ONE_HOUR)\n time = time + ONE_HOUR\n\n store_data(results, path)\n\n\ndef get_days(start, end, path):\n '''\n Get data for each day from `start` to `end` inclusive and store\n it in the directory `path`\n '''\n day = start\n while day <= end:\n get_day(day, path)\n day += ONE_DAY\n\n\ndef parse_args():\n\n parser = argparse.ArgumentParser(epilog='''\n and can be anything dateutil.parser.parse understands\n ''')\n\n parser.add_argument('last', type=dateutil.parser.parse,\n default=(datetime.now()-ONE_DAY), nargs='?',\n help='last (or only) day to download (default yesterday)')\n parser.add_argument('--dest', default='vivacity_data',\n help='directory in which to store data (default \\'%(default)s\\')')\n group = parser.add_mutually_exclusive_group()\n group.add_argument('--first', '-f', type=dateutil.parser.parse,\n help='first day to download')\n group.add_argument('--days', '-d', type=int, help='number of days to download')\n\n args = parser.parse_args()\n\n if args.days:\n args.first = args.last - timedelta(days=args.days - 1)\n elif args.first is None:\n args.first = args.last\n\n return args\n\n\ndef run():\n\n params = parse_args()\n\n get_days(params.first.date(), params.last.date(), params.dest)\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"vivacity/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":8192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"202375147","text":"#####Fonctions#####\r\ndef DonnerLettre(cle,n):\r\n while n>=len(cle):\r\n n=n-len(cle)\r\n lettre_donnee=cle[n]\r\n print(lettre_donnee)\r\n\r\n return lettre_donnee\r\n \r\ndef CodageLettre(lettre,donnez_lettre):\r\n rang=ord(lettre)\r\n if ord('a')<=ord(donnez_lettre)<=ord('z'):\r\n liste=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\r\n elif ord('A')<=ord(donnez_lettre)<=ord('Z'):\r\n liste=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']\r\n\r\n i=0\r\n while liste[i]!=donnez_lettre:\r\n i+=1\r\n \r\n \r\n if 65<=ord(lettre)<=90:\r\n lettre_codee=chr(rang-i)\r\n\r\n if ord(lettre_codee)<65:\r\n lettre_codee=chr((rang-i)+26)\r\n \r\n\r\n elif 97<=ord(lettre)<=122:\r\n lettre_codee=chr(rang-i)\r\n\r\n if ord(lettre_codee)<97:\r\n lettre_codee=chr((rang-i)+26)\r\n\r\n return lettre_codee\r\n\r\ndef CodagePhrase(phrase,lettre_phrase,donnez_lettre,n):\r\n lettre_codee=CodageLettre(lettre_phrase,donnez_lettre)\r\n phrase=phrase[0:n]+lettre_codee+phrase[n+1:len(phrase)]\r\n print(phrase)\r\n \r\n return phrase\r\n\r\n\r\n#####Programme Principale#####\r\nphrase=input(\"Quelle phrase voulez-vous décoder ?\\n\")\r\ncle=input(\"Quelle est la clé de codage ?\\n\")\r\nprint(phrase)\r\ni=0\r\nfor n in range(0,len(phrase)):\r\n if phrase[n]!=\"!\" and phrase[n]!=\".\" and phrase[n]!=\" \" and phrase[n]!=\",\" and phrase[n]!=\";\" and phrase[n]!=\"?\" and phrase[n]!=\"'\" and phrase[n]!=\"\":\r\n donnez_lettre=DonnerLettre(cle,i)\r\n phrase=CodagePhrase(phrase,phrase[n],donnez_lettre,n)\r\n i+=1\r\n\r\nprint(\"La phrase décodée est :\\n\"+phrase)\r\n","sub_path":"Programme_PrincipaleV1 décodage.py","file_name":"Programme_PrincipaleV1 décodage.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"408402967","text":"# -*- coding: utf-8 -*-\n# @Author : zgh\n# @Email : 849080458@qq.com\n# @File : manage.py\n# @Software: PyCharm\n\nfrom public.config import config\nimport pymysql\nfrom conf import Allpath\nfrom public.logger import Log\nimport time\n\nnow = time.strftime('%Y-%m-%d_%H_%M_%S')\nlogger=Log('auto_cases',Allpath.log_path)\n\n\nclass getMysqlInfo:\n def __init__(self,config_path,conf):\n # 传入参数:路径、便签、对象\n self.config=config().read_config(config_path,'DBCONFIG',conf)\n logger.info(\"本次数据库调用配置成功!\")\n\n def get_cnn(self):\n # 出入获取的配置文件,建立游标\n cnn=pymysql.connect(**self.config)\n return cnn\n\n\n def auto_insert(self):\n list_1 = {}\n cnn = self.get_cnn()\n cursor = cnn.cursor()\n # 执行SQL语句\n cur = cursor.execute(\"select * from autotest.aqhy\")\n # 查看数据库数据\n data = cursor.description\n data_1 = []\n test = []\n for i in range(len(data)):\n data_1.append(data[i][0])\n # print(data[i][0])\n test.append('%(' + data[i][0] + ')s') # 生成value数列\n list_1[data[i][0]] = ''\n table_sql = \"INSERT INTO aqhy (\" + ','.join(data_1) + \")\" + \" VALUES \" + \"(\" + ','.join(test) + \")\"\n return table_sql\n\n def Instert_mysql(self,data):\n sql=getMysqlInfo(Allpath.db_conf_path, 'config1').auto_insert()\n cnn = self.get_cnn()\n cursor = cnn.cursor()\n try:\n # 传入sql语句,对应字段值\n cursor.executemany(sql,data)\n cnn.commit()\n logger.info('sql写入统计测试记录成功!')\n except Exception as e:\n logger.info('sql写入统计测试记录失败!!!%s' % e)\n raise e\n cnn.close()\n\n def get_mysql_info(self,my_sql,code):\n cnn=self.get_cnn()\n cursor=cnn.cursor()\n # 传入sql语句,对应字段值\n cursor.execute(my_sql)\n desc = cursor.description # 获取字段的描述,默认获取数据库字段名称,重新定义时通过AS关键重新命名即可\n if code==1:#查询所有的\n data_dict = [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()] # 列表表达式把数据组装起来\n elif code==0:#查询一条信息\n data_dict = [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchone()] # 列表表达式把数据组装起来\n cnn.close()\n # print(data_dict)\n result={'restult':\"\",'sum':'','ok':'','fail':'','error':'','error_1':''}\n result['restult']=data_dict[0]['restult']\n\n sum = []\n ok = []\n fail = []\n error = []\n error_1 = []\n for i in range(1,len(data_dict)+1):\n ii=len(data_dict)-i\n sum.append(data_dict[ii]['sum'])\n ok.append(data_dict[ii]['ok'])\n fail.append(data_dict[ii]['fail'])\n error.append(data_dict[ii]['error'])\n error_1.append(data_dict[ii]['error_1'])\n result['sum'] = sum\n result['ok'] = ok\n result['fail'] = fail\n result['error'] = error\n result['error_1'] = error_1\n # print(result)\n return result\n\n\nif __name__ == '__main__':\n data=[{'restult': \"{'testname': '质量保障部—章广华', 'time': '2019-11-11 11:55:14', 'sumtime': '0:00:00.125677', 'testresult': '共 1 条接口用例,错误 1 条', 'tonggl': '0.00%'}\", 'sum': 1, 'ok': 0, 'fail': 0, 'error': 1, 'error_1': '100.00%', 'date': '2019-11-11_11_55_13'}]\n # sql_result = getMysqlInfo(Allpath.db_conf_path, 'config1').Instert_mysql(data)\n sql_result=getMysqlInfo(Allpath.db_conf_path,'config1').get_mysql_info(\"select * from aqhy ORDER BY date DESC LIMIT 10;\",1)\n # sql = getMysqlInfo(Allpath.db_conf_path, 'config1').auto_insert()\n print(sql_result)\n","sub_path":"interface_atuo_cases0508/interface_auto_cases_for_AQHY/public/get_mysql_info.py","file_name":"get_mysql_info.py","file_ext":"py","file_size_in_byte":3926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"551173547","text":"from collections import namedtuple\n\nif __name__ == '__main__':\n n = int(raw_input())\n fields = raw_input()\n Student = namedtuple('Student', fields)\n sum_ = 0\n for i in range(n):\n id_, mark, name, class_ = raw_input().split()\n student = Student(id_, mark, name, class_)\n sum_ += float(student.MARKS)\n print (\"{0:.2f}\".format(sum_ / float(n)))\n","sub_path":"Hackerrank/Easy/py-collections-namedtuple/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"300020143","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n#matplotlib inline\n #IMORTING THE DATASET.\ndataset = pd.read_csv('KDDCup99_binary_classlable.csv')\nX = dataset.iloc[:, :38]\ny = dataset.iloc[:, [38]]\n\n\n#SPLITTING OF THE TRAIN AND TEST SET\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)\n\n\n#CHANGING CATEGORICAL VALUES TO NUMERIC VALUES.\n'''from sklearn.preprocessing import LabelEncoder\nencode = LabelEncoder()\nX[:,1] = encode.fit_transform(X[:,1])\nX[:,2] = encode.fit_transform(X[:,2])\nX[:,3] = encode.fit_transform(X[:,3])'''\n\n\n#PLOTING THE CLASS LABELS\npd.value_counts(dataset['class_label']).plot.bar()\nplt.title('IDS class histogram')\nplt.xlabel('Class')\nplt.ylabel('Frequency')\ndataset['class_label'].value_counts()\n\n\n#SHAPE VIEWING\nX = np.array(dataset.iloc[:, dataset.columns != 'class_label'])\ny = np.array(dataset.iloc[:, dataset.columns == 'class_label'])\nprint('Shape of X: {}'.format(X.shape))\nprint('Shape of y: {}'.format(y.shape))\n\n\nprint(\"Number transactions X_train dataset:\", X_train.shape)\nprint(\"Number transactions y_train dataset:\", y_train.shape)\nprint(\"Number transactions X_test dataset:\", X_test.shape)\nprint(\"Number transactions y_test dataset:\", y_test.shape)\n\n\n\n#APPLYING SMOTE OVERSAMPLING\nprint(\"Before OverSampling, counts of label '1': {}\".format(sum(y_train==1)))\n\nprint(\"Before OverSampling, counts of label '0': {} \\n\".format(sum(y_train==0)))\nfrom imblearn.over_sampling import SMOTE\nsm = SMOTE(random_state=2)\nX_train_res, y_train_res = sm.fit_sample(X_train, y_train.ravel())\n\nprint('After OverSampling, the shape of train_X: {}'.format(X_train_res.shape))\nprint('After OverSampling, the shape of train_y: {} \\n'.format(y_train_res.shape))\nprint(\"After OverSampling, counts of label '1': {}\".format(sum(y_train_res==1)))\nprint(\"After OverSampling, counts of label '0': {}\".format(sum(y_train_res==0)))\n\n\nfeatures = pd.DataFrame(X_train_res)\nfeatures.to_csv('features.csv')\n\nclasslable = pd.DataFrame(y_train_res)\nclasslable.to_csv('classlable.csv')\n\n\n\nA = [features,classlable] \nSMOTE_TRAIN_DATA = pd.DataFrame(A)","sub_path":"SMOTE/SMOTE.py","file_name":"SMOTE.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"540422555","text":"'''\nLAB Download Function\n---\nDownloading from the F2G LAB API requires public and secret AWS Keys. They can\nbe saved to environment variables AWS_ACCESS_KEY_ID and AWS_ACCESS_SECRET_KEY\n'''\n\nimport os\nimport logging\nimport sys\n\nimport time\nfrom datetime import datetime\nimport boto3\nimport requests\nimport json\n\nfrom lib.singleton import LazyConfigure\nfrom lib import visual\n\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef load_last_updated(path: str) -> datetime:\n '''load the last update time'''\n last_update = None\n if os.path.exists(path):\n with open(path, \"r\") as tfile:\n content = json.load(tfile)\n last_update = datetime.strptime(content['updated_at'], '%Y-%m-%d %H:%M:%S')\n return last_update\n\nclass Lab(LazyConfigure):\n\n def __init__(self):\n super().__init__()\n self.access_key = None\n self.secret_key = None\n self.lab_id = None\n\n def configure(\n self,\n lab_id: str = \"\",\n key: str = \"\",\n secret: str = \"\",\n ):\n super().configure()\n self.access_key = key\n self.secret_key = secret\n self.lab_id = lab_id\n self.connect_key = {\"api_key\": key, \"secret\": secret}\n self.header = {\"Accept\":\"application/json\", \"Authorization\":\"\"}\n\n def connect(self):\n '''connect to LAB and update header'''\n lab_connect = \"https://app.face2gene.com/api/labs/auth/connect\"\n response = requests.post(\n lab_connect,\n data=json.dumps(self.connect_key),\n headers={\"Content-Type\": \"application/json\", \"Accept\": \"application/json\"})\n\n if response.status_code == 200:\n token = json.loads(response.content.decode('utf-8'))['jwt']\n self.header[\"Authorization\"] = \"Bearer \" + token\n else:\n err_str = \"There is error while connecting to lab %s. Error code: %d\" % \\\n (self.lab_id, response.status_code)\n LOGGER.error(err_str)\n\n def download_lab_case(\n self,\n download_location: str = '',\n lab_case_id: str = ''\n ):\n '''Save entire AWS bucket defined by AWS_BUCKET_NAME to download\n location. '''\n os.makedirs(download_location, exist_ok=True)\n\n lab_connect = \"https://app.face2gene.com/api/labs/auth/connect\"\n lab_get_case_list = \"https://app.face2gene.com/api/lab-cases?lab_id=\" + self.lab_id\n lab_get_case = \"https://app.face2gene.com/api/lab-cases/\" + lab_case_id\n response = requests.post(\n lab_connect,\n data=json.dumps(self.connect_key),\n headers={\"Content-Type\": \"application/json\", \"Accept\": \"application/json\"})\n\n token = ''\n if response.status_code == 200:\n token = json.loads(response.content.decode('utf-8'))['jwt']\n else:\n err_str = \"There is error while connecting to lab \" + self.lab_id + \". Error code: \" + str(response.status_code)\n sys.exit(err_str)\n if token != '':\n auth = \"Bearer \" + token\n response = requests.get(lab_get_case, headers={\"Accept\":\"application/json\", \"Authorization\":auth})\n if response.status_code == 200:\n case_content = json.loads(response.content.decode('utf-8'))\n case_id = case_content[\"case_data\"][\"case_id\"]\n output = case_content\n file_path = os.path.join(download_location, case_id + \".json\")\n out_file = open(file_path, 'w')\n json.dump(output, out_file)\n out_file.close()\n else:\n err_str = \"There is error while downloading lab case \" + lab_case_id + \" from lab \" + self.lab_id + \". Error code: \" + str(response.status_code)\n sys.exit(err_str)\n return file_path\n\n def connect_case(self, lab_case_id):\n '''connect to LAB and get list of cases on specific page'''\n retry = 3\n content = {}\n while retry > 0:\n lab_get_case = \"https://app.face2gene.com/api/lab-cases/%d\" % lab_case_id\n response = requests.get(\n lab_get_case,\n headers = self.header\n )\n if response.status_code == 200:\n content = json.loads(response.content.decode('utf-8'))\n break\n elif retry > 0:\n self.connect()\n err_str = \"Retry There is error while downloading lab case %d from lab %s. Error code: %d\" % \\\n (lab_case_id, self.lab_id, response.status_code)\n LOGGER.debug(err_str)\n else:\n err_str = \"There is error while downloading lab cases \" + self.lab_id + \". Error code: \" + str(response.status_code)\n LOGGER.error(err_str)\n break\n retry -= 1\n return content\n\n def download_case(\n self,\n download_location,\n lab_case_id,\n count\n ):\n file_path = None\n case_content = self.connect_case(lab_case_id)\n if case_content:\n case_id = case_content[\"case_data\"][\"case_id\"]\n file_path = os.path.join(download_location, \"cases\", case_id + \".json\")\n last_update = load_last_updated(file_path)\n new_update = datetime.strptime(case_content['updated_at'], '%Y-%m-%d %H:%M:%S')\n if not load_last_updated(file_path):\n out_file = open(file_path, 'w')\n json.dump(case_content, out_file)\n out_file.close()\n status = 'Download case %s' % case_id\n count['download'] += 1\n elif new_update > last_update:\n update_count += 1\n out_file = open(file_path, 'w')\n json.dump(case_content, out_file)\n out_file.close()\n status = 'Update case %s' % case_id\n count['update'] += 1\n else:\n status = 'Skip case %s, file already exists' % case_id\n\n LOGGER.debug(status)\n else:\n err_str = \"There is error while downloading lab case %d from lab %s. Error code: %d\" % \\\n (lab_case_id, self.lab_id, response.status_code)\n count['error'] += 1\n LOGGER.error(err_str)\n return file_path, count\n\n def connect_all_cases(self, page):\n '''connect to LAB and get list of cases on specific page'''\n retry = 3\n content = {}\n self.connect()\n while retry > 0:\n lab_get_all_case = \"https://app.face2gene.com/api/labs/v2/%s/lab-cases?page=%d\" % \\\n (self.lab_id, page)\n response = requests.get(\n lab_get_all_case,\n headers = self.header\n )\n if response.status_code == 200:\n content = json.loads(response.content.decode('utf-8'))\n elif retry > 0:\n self.connect()\n err_str = \"Retry There is error while downloading lab cases on page %d from lab %s. Error code: %d\" % \\\n (page, self.lab_id, response.status_code)\n LOGGER.debug(err_str)\n else:\n err_str = \"There is error while downloading lab cases on page %d from lab %s. Error code: %d\" % \\\n (page, self.lab_id, response.status_code)\n LOGGER.error(err_str)\n break\n retry -= 1\n return content\n\n def download_all_lab_case(\n self,\n download_location: str = '',\n lab_case_id: str = ''\n ):\n '''Save entire AWS bucket defined by AWS_BUCKET_NAME to download\n location. '''\n os.makedirs(download_location, exist_ok=True)\n\n page = 1\n last_page = 1\n current_num = 0\n file_path = []\n count = {'download': 0, 'update': 0, 'error': 0}\n # while not the last page, download next page\n while not (page > last_page):\n content = self.connect_all_cases(page)\n if content:\n last_page = content['last_page']\n total = content['total']\n case_list = content['labCasesList']\n case_in_page = len(case_list)\n for i, case_content in enumerate(case_list):\n lab_case_id = case_content['lab_case_id']\n case_path, count = self.download_case(\n download_location,\n lab_case_id,\n count\n )\n if case_path:\n file_path.append(case_path)\n current_num += 1\n visual.print_status(\"Checking LAB\", 20, current_num, total)\n page += 1\n else:\n err_str = \"There is error while downloading lab cases \" + self.lab_id + \". Error code: \" + str(response.status_code)\n LOGGER.error(err_str)\n print(\"\")\n LOGGER.info(\n \"LAB Stats: Downloaded %d new %d updated of %d total files.\",\n count['download'], count['update'], current_num\n )\n return file_path\n","sub_path":"lib/api/lab.py","file_name":"lab.py","file_ext":"py","file_size_in_byte":9343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"271015665","text":"tabby_cat = \"\\tI'm tabbed in.\"\npersian_cat = \"I'm split\\non a line.\"\nbackslash_cat = \"I'm \\\\ a \\\\ cat.\"\n\nfat_cat = \"\"\"\nI'll do a list:\n \\t* Cat food\n \\t* Fishies\n \\t* Catnip\\n\\t* Grass\n \"\"\"\n\nprint(tabby_cat)\nprint(persian_cat)\nprint(backslash_cat)\nprint(fat_cat)\n\n# here we have the study drills\n\nfat_dog = '''\nThis is a fat dog:\n \\t* A tab\n \\r* A carriage return\n \\a* An ASCII bell\n '''\n\nprint(fat_dog)\n","sub_path":"exercises/ex10.py","file_name":"ex10.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"428195784","text":"\nfrom keras.datasets import mnist\nfrom keras.utils import np_utils \nfrom keras.models import Sequential \nfrom keras.layers import Dense, Activation\n\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\n\nX_train = X_train.reshape(X_train.shape[0], X_train.shape[1]*X_train.shape[2])\nX_test = X_test.reshape(X_test.shape[0], X_test.shape[1]*X_test.shape[2])\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\nX_train /= 255\nX_test /= 255\n\nY_train = np_utils.to_categorical(y_train, 10)\nY_test = np_utils.to_categorical(y_test, 10)\n\nmodel = Sequential() \nmodel.add(Dense(500, input_dim=784))\nmodel.add(Activation('relu'))\nmodel.add(Dense(500))\nmodel.add(Activation('relu'))\nmodel.add(Dense(10))\nmodel.add(Activation('softmax'))\n\nmodel.summary()\n\nmodel.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])\n\nmodel.fit(X_train, Y_train, batch_size=100, epochs=20)\n\nscore = model.evaluate(X_test, Y_test)\nprint('Test loss: ', score[0])\nprint('Test accuracy: ', score[1])\n\n","sub_path":"13/mnist_mlp_new.py","file_name":"mnist_mlp_new.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"616842532","text":"\n\n#calss header\nclass _DUH():\n\tdef __init__(self,): \n\t\tself.name = \"DUH\"\n\t\tself.definitions = [u'used to show that you think a person or statement is stupid, or that something is obvious']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'exclamations'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/exclamations/_duh.py","file_name":"_duh.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"149865451","text":"import logging\n\n_logger = logging.getLogger(__name__)\n\ntry:\n from zeep import Client\nexcept (ImportError, IOError) as err:\n _logger.debug(err)\n _logger.info(\n \"ERROR IMPORTING zeep, if not installed, please install it:\"\n \" e.g.: pip install zeep\")\n\nAUTH_SUCCESS = 'Вы успешно авторизировались'\n\nNO_AUTH = 'Вы не авторизированы'\n\nSEND_SUCCESS = 'Сообщения успешно отправлены'\n\nSTATUS_SUCCESS = 'Сообщение доставлено получателю'\n\nSTATUS_DEPART = [\n 'Отправлено', 'В очереди', 'Сообщение передано в мобильную сеть']\n\n\nclass TurboSmsClient(object):\n url = 'http://turbosms.in.ua/api/wsdl.html'\n auth = False\n balance = 0\n sender = 'sender'\n min_balance = 1\n\n def __init__(self, username, password) -> None:\n super().__init__()\n self.error = ''\n self.sms_error = ''\n self.sms_id = False\n self.username = username\n self.password = password\n self.client = Client(wsdl=self.url)\n\n def authenticate(self):\n result = self.client.service.Auth(\n login=self.username, password=self.password)\n if result == AUTH_SUCCESS:\n self.error = ''\n self.auth = True\n return True\n self.error = result\n self.auth = False\n return False\n\n def get_balance(self):\n if not self.authenticate():\n return False\n result = self.client.service.GetCreditBalance()\n try:\n balance = float(result)\n except Exception as e:\n self.error = 'Balance status {} error {}'.format(result, e)\n _logger.error(self.error)\n return False\n self.balance = balance\n if float(self.balance) < float(self.min_balance):\n self.error = 'Not enough money. Replenish the balance.'\n _logger.info(self.error)\n return False\n self.error = ''\n return True\n\n def send_sms(self, to, text):\n \"\"\"\n Send SMS to one phone number ONLY ONE, NOT list\n :param to: Phone number, digits only\n :param text: SMS text\n :return: True if success\n \"\"\"\n if not self.get_balance():\n return False\n if not (isinstance(to, str) and to.isdigit()):\n self.error = '\\'to\\' must string value of ' \\\n 'phone number with digits only'\n _logger.error(self.error)\n return False\n result = self.client.service.SendSMS(\n sender=self.sender, destination=to, text=text)\n if not (isinstance(result, list) and len(result)):\n self.error = 'Response result must be list of values, ' \\\n 'not {}'.format(result)\n _logger.error(self.error)\n return False\n if result[0] != SEND_SUCCESS:\n self.error = result[0]\n self.sms_id = False\n if len(result) > 1:\n self.sms_error = result[1]\n return False\n self.error = ''\n if len(result) == 1:\n self.error = 'Success sending has no sms id'\n _logger.error(self.error)\n return False\n self.sms_error = ''\n self.sms_id = result[1]\n return True\n\n def status(self, sms_id):\n if not self.authenticate():\n return False\n result = self.client.service.GetMessageStatus(sms_id)\n if result == STATUS_SUCCESS:\n return 'success'\n if result in STATUS_DEPART:\n return 'depart'\n self.sms_error = result\n return 'error'\n","sub_path":"turbosms_client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"10762879","text":"import spirecloudword\r\nfrom spirecloudword.configuration import *\r\n\r\nappId = \"your id\"\r\nappKey = \"your key\"\r\nbaseUrl = \"https://api.e-iceblue.cn\"\r\nconfiguration = Configuration(appId, appKey,baseUrl)\r\napi= spirecloudword.api.TextRangesApi(configuration)\r\n\r\nfile_name = 'Template.docx'\r\nparagraph_path = 'Section/0/Body/0/Paragraph/0'\r\nindex = 0\r\nresult = api.get_text_range_format(file_name, paragraph_path, index, folder=\"input\")","sub_path":"Python Word Examples/TextRangesApiDemo/getTextRangeFormat.py","file_name":"getTextRangeFormat.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"247270209","text":"#!/usr/bin/env python\nimport numpy as np\n\n## Functions\ndef argparse():\n import argparse\n parser = argparse.ArgumentParser(description = \"\"\"\n Will run nappy ADF plot.\n \"\"\")\n # Positional arguments\n parser.add_argument('symbol1', type=str, help='symbol1,2,3, are chemical symbols consisting bonds')\n parser.add_argument('symbol2', type=str, help='around the angle like symbol1-2-3. \"a\": any symbols.')\n parser.add_argument('symbol3', type=str, help='e.g.1. Ge Te Ge | e.g.2. a a a | e.g.3 a Te a')\n parser.add_argument('file_list', type=str, nargs='+', help='ASE readable atoms list file name. Multiple input files can be read.')\n # Optional arguments\n parser.add_argument('-n', '--image_slice', type=str, default=':', help='Image slice following python convention. default=\":\" (e.g.) -n :1000:10')\n parser.add_argument('-w', '--dDeg', type=float, default=1., help='Width of the angular degree. [default: 1.0]')\n parser.add_argument('-r', '--rcut', type=float, default=3., help='Cutoff radius of the bonding pair. [default: 3.0]')\n parser.add_argument('-g', '--gsmear', type=float, default=0., help='Width(simga, STD) of Gaussian smearing in degree unit. Zero means no smearing. [default: 0]')\n parser.add_argument('-a', '--no_average', dest='avg_bool', action='store_false', help='Not to take average over files. [default: take average]')\n parser.add_argument('-x', '--x_lower', type=float, default=0., help='Lower limit for the ADF plot [default: 0]')\n parser.add_argument('-b', '--large_plot', action='store_true', help='Plot large figure.')\n parser.add_argument('-s', '--dont_save', dest='save_bool', action='store_false', help='If provided, npz will not be saved. Default: Save array')\n parser.add_argument('-o', '--dont_load', dest='load_bool', action='store_false', help='If provided, npz will not be loaded. Default: Load if possible')\n parser.add_argument('-p', '--dont_plot', dest='plot_bool', action='store_false', help='If provided, plot will be skipped. Default: Plot ADF.')\n parser.add_argument('-m', '--Nprocs', type=int, default=1, help='Number of process for multiprocessing. [Default: serial compute]')\n parser.add_argument('-u', '--adf_upper', type=float, default=None, help='Upper bound for ADF plot [Default: automatic]')\n parser.add_argument('-l', '--adf_lower', type=float, default=0, help='Lower bound for ADF plot [Default: 0]')\n return parser.parse_args()\n\nif __name__ == '__main__':\n ## Intro\n import datetime\n now = datetime.datetime.now()\n time = now.strftime('%Y-%m-%d %H:%M:%S')\n print('')\n print('>>>>> Code by Young Jae Choi @ POSTECH <<<<<'.center(120))\n print(('Code runtime : '+time).center(120))\n print('')\n print('=================================================================================================='.center(120))\n print('Will run nappy ADF plot.'.center(120))\n print('=================================================================================================='.center(120))\n print('')\n args = argparse()\n from nappy.adf import adf_atom, adf, adf_gather\n from chemical_symbol_number_inverter import invert_chem_sym_num as ics\n\n ## def\n file_list = args.file_list\n symbol1 = args.symbol1\n symbol2 = args.symbol2\n symbol3 = args.symbol3\n dang = float(args.dDeg)\n drad = np.pi *dang/180.0\n rcut = float(args.rcut)\n gsmear_std = int(args.gsmear)\n avg_bool = args.avg_bool\n na = int(180.0/dang) +1\n # Slice process\n from ss_util import str_slice_to_list\n slice_list = str_slice_to_list(args.image_slice)\n # out name\n out_fname = 'adf-saved/{}_slice-{}-{}-{}_sym-{}-{}-{}_dDeg-{}_rcut-{}_avg-{}_.npz'.format(\n file_list[0], slice_list[0], slice_list[1], slice_list[2], symbol1, symbol2, symbol3, dang, rcut, avg_bool)\n out_fname2 = 'adf-saved/{}_slice-{}-{}-{}_sym-{}-{}-{}_dDeg-{}_rcut-{}_avg-{}_.npz'.format(\n file_list[0], slice_list[0], slice_list[1], slice_list[2], symbol3, symbol2, symbol1, dang, rcut, avg_bool)\n\n ## Main\n try:\n assert args.load_bool == True\n assert len(file_list) == 1\n npz = np.load(out_fname)\n except:\n try:\n assert args.load_bool == True\n assert len(file_list) == 1\n npz = np.load(out_fname2)\n except:\n do_calc = True\n if args.load_bool:\n print('Failed to load saved npz file. Calculation will be carried out')\n print('Case 1) Number of input file must be 1 to load npz. len(file_list)=={}'.format(len(file_list)))\n print('Case 2) Failed to load npz file \"{}\"'.format(out_fname))\n print(' or equivalent data \"{}\"'.format(out_fname2))\n else:\n print('File \"{}\" has been loaded.'.format(out_fname2))\n do_calc = False\n if do_calc:\n ## Read inputs\n alist = []\n from ase.io import read\n for infname in file_list:\n read_obj = read(infname, args.image_slice)\n if isinstance(read_obj, list):\n alist.extend(read_obj)\n else:\n alist.append(read_obj)\n if len(alist) == 0: raise ValueError('No an image provided.')\n\n ## Multiprocessing\n from time import time\n time_init = time()\n print('Caculation started.')\n from multiprocessing import Pool\n pool = Pool(args.Nprocs)\n tasks = [pool.apply_async(adf_gather, (alist[_::args.Nprocs], dang, rcut, symbol1, symbol2, symbol3)) for _ in range(args.Nprocs)]\n\n gather = []\n for task in tasks:\n task.wait(10)\n gather.append(task.get())\n gather = np.array(gather)\n\n for items in gather:\n angd = gather[0,0]\n agr = np.sum(gather[:,1], axis=0)\n nsum = np.sum(gather[:,2], axis=0)\n agr /= dang ## Normalized to continueous version. Total adf: Integral = average angle-pair numbers && Sum of all possible partial adf == total adf\n if args.avg_bool:\n agr /= nsum\n print('Caculation ended. Elapse time = {} (s)'.format(time()-time_init))\n print('Totally {} atoms in {} images have been calculated'.format(nsum, len(alist)))\n\n if args.save_bool and len(file_list) == 1:\n from ss_util import pick_folder_from_path as pffp\n folder = pffp(out_fname)\n from subprocess import call\n call('mkdir -p {}'.format(folder), shell=True)\n np.savez(out_fname, angd=angd, agr=agr)\n print('=================================================================================================='.center(120))\n print('ADF saved! ----------> {}'.format(out_fname).center(120))\n print('=================================================================================================='.center(120))\n else:\n print('File \"{}\" has been loaded successfully.'.format(out_fname))\n angd, agr = npz['angd'], npz['agr']\n\n if not gsmear_std == 0:\n print(' Gaussian smearing...')\n # from gaussian_smear import gsmear\n # agr= gsmear(angd,agr,gsmear_std)\n from scipy.ndimage.filters import gaussian_filter1d\n agr = gaussian_filter1d(agr, gsmear_std /dang)\n ## Debug option\n print('Average number of normalized angle-pairs.={}'.format(np.trapz(agr, angd)))\n\n ## Plot\n if args.plot_bool:\n import matplotlib.pyplot as plt\n font = {'family':'sans-serif', 'sans-serif':'Arial'}\n plt.rc('font', **font)\n plt.plot(angd,agr,'-',c='k')\n if (symbol1, symbol2, symbol3) == ('a','a','a'):\n plt.ylabel('Total ADF', fontsize='x-large')\n else:\n if symbol1 == 'X': symbol1 = 'V'\n if symbol2 == 'X': symbol2 = 'V'\n if symbol3 == 'X': symbol3 = 'V'\n plt.ylabel(r'$g \\rm _{{{}}}$'.format(symbol1+symbol2+symbol3)+r'$ \\it (\\alpha)$', fontsize='x-large')\n plt.xlabel('Bond angle (deg)', fontsize='x-large')\n if args.large_plot:\n plt.subplots_adjust(left=0.15, bottom=0.28, right=0.95, top=0.75, wspace=0.20, hspace=0.20)\n else:\n # plt.subplots_adjust(left=0.25, bottom=0.35, right=0.75, top=0.65, wspace=0.20, hspace=0.20)\n plt.subplots_adjust(left=0.30, bottom=0.40, right=0.71, top=0.65, wspace=0.20, hspace=0.20)\n plt.xticks(range(30,181,30),fontsize='x-large')\n plt.yticks(fontsize='x-large')\n plt.tick_params(axis=\"both\",direction=\"in\", labelsize='x-large')\n plt.xlim(args.x_lower, 185.)\n plt.ylim(args.adf_lower, args.adf_upper)\n plt.title(out_fname[11:-4], pad=10)\n plt.grid(alpha=0.5)\n plt.show()\n","sub_path":"nappy-adf.py","file_name":"nappy-adf.py","file_ext":"py","file_size_in_byte":8970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"369796421","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\n\n\ndef main():\n if len(sys.argv) != 2:\n return -1\n\n interfaces = [\"enp0s8\", \"enp0s9\", \"enp0s10\"]\n str_number = sys.argv[1]\n number = int(str_number)\n inverted = 3 - number\n\n os.system(\"sudo tc qdisc del dev enp0s3 root\")\n os.system(\"sudo tc qdisc add dev enp0s3 root netem delay 50ms\")\n\n for interface in interfaces:\n os.system(\"sudo ip link set \" + interface + \" down\")\n\n if number > 1:\n for i in range(0, number - 1):\n os.system(\"sudo ip link set \" + interfaces[i] + \" up\")\n os.system(\"sudo tc qdisc del dev \" + interfaces[i] + \" root\")\n os.system(\"sudo tc qdisc add dev \" + interfaces[i] + \" root netem delay 50ms\")\n\n return 0\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"example/link_config.py","file_name":"link_config.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"607462316","text":"import cv2\nimport os\nimport pandas as pd\nimport numpy as np\nimport pickle\n\n\n\n\ndef video_to_image(vid_path,save_dir):\n timeF=1\n save_dir = os.path.join(save_dir,'frame')\n print(save_dir)\n os.makedirs(save_dir, exist_ok=True)\n video_path=os.path.join(vid_path,'vid.avi')\n cap = cv2.VideoCapture(video_path)\n c = 1\n ret = True\n while ret: # 循环读取视频帧\n ret, frame = cap.read()\n if (c % timeF == 0) & ret == True: # 每隔timeF帧进行存储操作\n save_path=os.path.join(save_dir,str(c-1)+'.jpg')\n cv2.imwrite(save_path,frame) # 存储为图像\n c += 1\n cap.release()\n print(\"finish\")\n\ndef image_to_gray(vid_path,save_dir):\n save_dir = os.path.join(save_dir, 'gray_png')\n video_dir = os.path.join(vid_path,'frame')\n os.makedirs(save_dir, exist_ok=True)\n pic_path = video_dir\n pic = os.listdir(pic_path)\n print(pic)\n for f in range(len(pic)):\n image_path = pic_path + '/'+str(f)+'.jpg'\n #print(image_path)\n image = cv2.imread(image_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n cv2.imwrite(save_dir + '/'+str(f)+'.jpg', image) # 存储为图像\ndef crop_image(gray_path,save_dir,path):\n gray_dir = os.path.join(gray_path,'frame')\n save_dir = os.path.join(save_dir, 'face')\n os.makedirs(save_dir, exist_ok=True)\n pic_path = gray_dir\n pic = os.listdir(pic_path)\n print(pic)\n errorlist = []\n for f in range(len(pic)):\n\n image_path = pic_path + '/'+str(f)+'.jpg'\n img = cv2.imread(image_path)\n\n face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml')\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # Detect faces\n faces = face_cascade.detectMultiScale(gray, 1.1, 4)\n facesize=[]\n i=0\n # Draw rectangle around the faces\n for (x, y, w, h) in faces:\n # cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)\n facesize.append(w*h)\n num = facesize.index(max(facesize))\n i=i+1\n if len(faces):\n x, y, w, h=faces[num]\n crop_img = img[y:y + h, x:x + w]\n else:\n crop_img=img #若無法偵測人臉 輸出原圖\n errorlist.append(save_dir + '/' + str(f) + '.jpg') #記錄哪張圖無法輸出人臉\n print(save_dir + '/'+str(f)+'.jpg')\n cv2.imwrite(save_dir + '/'+str(f)+'.jpg', crop_img)\n print(errorlist)\n test = pd.DataFrame(columns=['name'], data=errorlist)\n test.to_csv(path +'/errorlist.csv',) #輸出無法偵測人臉的紀錄\ndef face_detection(image):\n\n face_cascade = cv2.CascadeClassifier('D:\\RGB_data\\haarcascade_frontalface_alt2.xml')\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n # Detect faces\n faces = face_cascade.detectMultiScale(gray, 1.1, 4)\n facesize = []\n i = 0\n # Draw rectangle around the faces\n for (x, y, w, h) in faces:\n facesize.append(w * h)\n num = facesize.index(max(facesize))\n i = i + 1\n if len(faces):\n x, y, w, h = faces[num]\n\n if (w ) * (h) >= 100 * 100:\n # rect_image=cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2)\n # crop_img = image[y:y + h, x:x + w]\n # crop_img = image.crop((x,y,w,h))\n # crop_img.show()\n x1, y1, w1, h1 = x, y, w, h\n no_face = False\n else:\n x = 0\n y = 0\n w = 0\n h = 0\n no_face = True\n else:\n crop_img = image # 若無法偵測人臉 輸出原圖\n rect_image = image\n x = 0\n y = 0\n w = 0\n h = 0\n no_face = True\n\n return x,y,w,h,no_face\n\ndef face_to_head_cheel_nosave(img):\n size = img.size\n height = size[0] # height(rows) of image\n width = size[1] # width(colums) of image\n head_img = img.crop((0,0,width,int(height / 3))) # 額頭為最上面1/3\n cheek_img = img.crop((0,int(height / 2),width,int(height * 5 / 6)) ) # 臉頰為中間向下1/3\n\n return head_img,cheek_img\ndef face_to_head_cheek_save(face_path,save_dir):\n face_dir = os.path.join(face_path, 'face')\n savehead_dir = os.path.join(save_dir, 'head')\n os.makedirs(savehead_dir, exist_ok=True)\n savecheek_dir = os.path.join(save_dir, 'cheek')\n os.makedirs(savecheek_dir, exist_ok=True)\n pic_path = face_dir\n pic = os.listdir(pic_path)\n print(pic)\n for f in range(len(pic)):\n image_path = pic_path + '/'+str(f)+'.jpg'\n img = cv2.imread(image_path)\n size=img.shape\n height = size[0] # height(rows) of image\n width = size[1] # width(colums) of image\n head_img = img[0:int(height / 3), 0:width] # 額頭為最上面1/3\n cheek_img = img[int(height / 2):int(height * 5 / 6), 0:width] # 臉頰為中間向下1/3\n cv2.imwrite(savehead_dir + '/' + str(f) + '.jpg', head_img)\n cv2.imwrite(savecheek_dir + '/' + str(f) + '.jpg', cheek_img)\n print(savehead_dir + '/' + str(f) + '.jpg')\n print(savecheek_dir + '/' + str(f) + '.jpg')\n\n\n\ndef crop_all_face(dataset_dir):\n for i in all_file_path:\n print(\"start \", i)\n path=os.path.join(dataset_dir,i)\n timeF = 1 # 视频帧计数间隔频率\n #video_to_image(path,save_dir=path)\n #crop_image(path,save_dir=path,path=path)\n face_to_head_cheek(path,save_dir=path)\n\n\ndef crop_error_image():\n coordinate=['1.jpg']\n subject=['subject41']\n error=pd.read_csv(\"C:\\RGB_data\\DATASET_2\\subject11\\errorlist.csv\")\n subject_path=os.path.join(dataset_dir,subject[0])\n face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n gray_path=os.path.join(subject_path,'frame')\n gray_path = os.path.join(gray_path, coordinate[0])\n gray = cv2.imread(gray_path)\n faces = face_cascade.detectMultiScale(gray, 1.1, 4)\n\n image_dlr=os.path.join(subject_path,'frame')\n save_dlr=\"C:\\RGB_data\\error\"\n\n a=0\n x, y, w, h=faces[a][0],faces[a][1],faces[a][2],faces[a][3]\n\n\n for i in range(101,2000):\n img=str(i)+'.jpg'\n image_path=os.path.join(image_dlr,img)\n image=cv2.imread(image_path)\n crop_img=image[y:y+h,x:x+w]\n save_path=os.path.join(save_dlr,img)\n cv2.imwrite(save_path,crop_img)\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"rppg/image_process.py","file_name":"image_process.py","file_ext":"py","file_size_in_byte":6334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"450556241","text":"#!/usr/bin/python3.7\n# -*- coding: utf-8 -*-\n# @Time : 2020/3/22 上午 10:49\n# @Email : pasalai@qq.com\n# @Github : github.com/laishouchao\n# @File : tool.py\n# @Software: PyCharm\n\nimport requests\nimport sys\nimport easygui as ui\nimport pandas as pd\nfrom lxml import etree\n\n\ndef requests_info(website):\n url = \"http://dns.bugscaner.com/\" + website + \".html\"\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3941.4 Safari/537.36\"}\n responses = requests.get(url=url, headers=headers).content.decode('utf-8')\n return responses\n\n\nclass do_somting():\n def __init__(self, web_site):\n # 发送请求初始化xpath\n self.web_site = web_site\n # self.all_info = []\n\n def getinfo(self):\n # 获取网址IP信息统计数据\n self.tree = etree.HTML(requests_info(self.web_site))\n base_info_1 = self.tree.xpath('//div/div[3]/div/text()')[0]\n base_info_2 = self.tree.xpath('//div/div[3]/div/strong/text()')\n base_info_3 = self.tree.xpath('//div/div[3]/div/text()')[1]\n base_info_4 = self.tree.xpath('//div/div[3]/div/span/text()')\n base_info_5 = self.tree.xpath('//div/div[3]/div/text()')[2]\n base_info = base_info_1 + str(base_info_2[0]) + base_info_3 + str(base_info_4[0]) + base_info_5\n ui.msgbox(msg=base_info.replace(\" \", \"\").replace(\"\\n\", \"\"), title=\"网站\" + self.web_site + \"扫描结果\")\n # print(\"[√]完成:\" + base_info)\n\n def get_table(self):\n self.tree = etree.HTML(requests_info(self.web_site))\n # 获取详细信息\n tr_list = self.tree.xpath('//tbody/tr')\n\n for tr in tr_list:\n tips = []\n url = tr.xpath('td[2]/a/text()')\n tips.append(url[0])\n status = tr.xpath('td[3]/span/text()')\n tips.append(status[0])\n title = tr.xpath('td[4]/*/text()')\n tips.append(title[0])\n cms = tr.xpath('td[5]/text()')\n tips.append(cms[0])\n huanjing = tr.xpath(\"td[6]/text()\")\n tips.append(huanjing[0])\n # ui.textbox(msg=\"网站\" + website + \"同IP网站的详细信息\", title=\"网站\" + website + \"同IP网站的详细信息\", text=tips)\n all_info.append(tips)\n print(tips)\n\n def page_num(self):\n # 获取返回数据的页数(直接通过总条数和显示条数计算获得)\n tips_num = self.tree.xpath('//div/div/span/text()')[0]\n pages = int(int(tips_num) / 15) + 2 # 15条每页,取整+1\n # print(pages)\n for page_num in range(2, pages):\n temp = self.web_site\n website = self.web_site + \"_\" + str(page_num)\n do_somthing_init = do_somting(web_site=website)\n do_somthing_init.get_table()\n self.web_site = temp\n\n def savexls(self):\n output = open('data.txt', 'w', encoding='gbk')\n output.write('url,status,title,cms,huanjing\\n')\n for row in all_info:\n rowtxt = '{},{},{},{}'.format(row[0], row[1], row[2], row[3])\n output.write(rowtxt + \"\\n\")\n output.close()\n with open(\"data.txt\", encoding=\"gbk\") as rp:\n text = rp.read()\n ui.textbox(msg=\"网站\" + website + \"同IP网站的详细信息\", title=\"网站\" + website + \"同IP网站的详细信息\", text=text)\n weizhi = ui.filesavebox(msg=\"表格保存\", title=\"表格保存\", default=\"./\" + website + \"结果.xls\", filetypes=\"xls\")\n print(\"[!]正在保存结果至\" + website + \"结果.xls\")\n data_pd = pd.DataFrame(data=all_info, columns=[\"url\", \"状态值\", \"网站标题\", \"可能的CMS\", \"网站环境(包括中间件、开发框架、语言等信息)\"])\n try:\n data_pd.to_excel(weizhi)\n except IOError:\n ui.msgbox(\"[x]保存失败,请检查是否已经打开该文件,或本程序是否有本文件夹及文件的读写权限\")\n print(\"[x]保存失败,请检查是否已经打开该文件,或本程序是否有本文件夹及文件的读写权限\")\n else:\n ui.msgbox(\"[√]保存成功!\")\n print(\"[√]保存成功\")\n\n\n# 临时代码测试\n\n# main()\nif __name__ == '__main__':\n\n if ui.ccbox(msg=\"本软件仅供测试使用,对使用过程中造成的一切后果,作者不承担任何责任。\", title=\"免责声明\", choices=[\"同意承担使用本软件造成的一切责任\", \"算了吧,退出\"]):\n website = ui.enterbox(msg=\"请输入网址,如:www.sdyunet.cn\", title=\"同IP网站信息检测\", default=\"www.sdyunet.cn\")\n # print(website)\n all_info = []\n # website = input(\"[!]请输入网址,如www.site.com:\\n\")\n do_somthing_init = do_somting(web_site=website)\n do_somthing_init.getinfo()\n do_somthing_init.get_table()\n do_somthing_init.page_num()\n do_somthing_init.savexls()\n else:\n sys.exit(0)\n","sub_path":"tool.py","file_name":"tool.py","file_ext":"py","file_size_in_byte":4993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"96289807","text":"from math import e\n\nclass RatingExtractor:\n def __init__(self):\n print(\"rating initialized\")\n\n #Returns value between -q and q. for rating input between 0 and 10.\n #Parameters:\n #rating: indicates the rating for the destination\n #q: indicates the percentage of rating for general score. (default is 10.)\n @staticmethod\n def get_rating_weight_no_quantity(rating, q=10):\n if rating > 10 or rating < 0:\n return None\n else:\n m = (2*q) / 10 #10 because rating varies between 0 and 10\n b = -q\n return (m*rating) + b\n\n #Returns value between -q and q. for rating input between 0 and 10.\n #Parameters:\n #rating: indicates the rating for the destination\n #q: indicates the percentage of rating for general score. (default is 10.)\n #c: rating count\n #T: indicates the amount of rating as a threshold where score will be halved.\n @staticmethod\n def get_rating_weight_with_quantity(rating, c, T, q=10):\n if rating > 10 or rating < 0:\n return None\n else:\n m = (2*q) / 10 #10 because rating varies between 0 and 10\n b = -q\n val = (m*rating) + b\n\n M = e**((-T*0.68)/c)\n\n return val * M\n\n #Returns overall rating score\n #Parameters:\n #r: indicates the rating for the destination\n #rc: rating count\n #pf: positive feedback count\n #bf: negative feedback count\n @staticmethod\n def get_rating_with_count_and_reviews(r, rc, pf, bf):\n if r > 10 or r < 0:\n return None\n else:\n positive_diff = (10 - r) / 2\n positive_rating = r + positive_diff\n\n negative_diff = r / 2\n negative_rating = r - negative_diff\n\n updated_rating = ((r * rc) + (pf * positive_rating) + (bf * negative_rating)) / (rc + pf + bf)\n\n return RatingExtractor.get_rating_weight_with_quantity(updated_rating,rc,250000,100)\n","sub_path":"version2/server/rating_extractor.py","file_name":"rating_extractor.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"285540363","text":"import numpy as np\nimport threading\n\n\n# RK4 algorithm for a particle\nclass RK4Particle(threading.Thread):\n def __init__(self, step_size: float, init_pos: np.ndarray, init_vel: np.ndarray, mass: float):\n self.step_size = step_size\n self.positions = [init_pos]\n self.velocities = [init_vel]\n self.mass = mass\n\n threading.Thread.__init__(self)\n\n # Start method if used as a Thread\n def run(self):\n i = 1\n while not self.rk4_done():\n # print(\"{0}: Step {1}\".format(self.getName(), i))\n i += 1\n\n self.step()\n\n print(\"{0}: Done\".format(self.getName()))\n\n # Acceleration at position\n def acc(self, coords: np.ndarray, vel: np.ndarray) -> np.ndarray:\n raise NotImplementedError()\n\n # Current velocity\n def vel(self) -> np.ndarray:\n return self.velocities[-1]\n\n # Current position\n def pos(self) -> np.ndarray:\n return self.positions[-1]\n\n # Stopping condition\n def rk4_done(self) -> bool:\n raise NotImplementedError()\n\n # One step of RK4 algorithm, general implementation\n # Can provide custom step size for adaptive methods\n def step(self, step_size=None):\n pos = self.pos()\n vel = self.vel()\n\n # If custom step size is not provided, use the value given at class init\n if step_size is None:\n step_size = self.step_size\n\n # k variables for velocity and position\n k1_v = self.acc(pos, vel)\n k1_r = vel\n\n k2_v = self.acc(pos + (step_size / 2) * k1_r, k1_r)\n k2_r = vel + (step_size / 2) * k1_v\n\n k3_v = self.acc(pos + (step_size / 2) * k2_r, k2_r)\n k3_r = vel + (step_size / 2) * k2_v\n\n k4_v = self.acc(pos + step_size * k3_r, k3_r)\n k4_r = vel + step_size * k3_v\n\n # New position and velocity\n vel_n = vel + (step_size / 6) * (k1_v + 2 * (k2_v + k3_v) + k4_v)\n pos_n = pos + (step_size / 6) * (k1_r + 2 * (k2_r + k3_r) + k4_r)\n\n self.velocities.append(vel_n)\n self.positions.append(pos_n)\n","sub_path":"rk4.py","file_name":"rk4.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"232143504","text":"# 2010-06-29 by Gnacik\r\n# Based on official server Franz and Rpg\r\n\r\nfrom l2server.gameserver.model.quest import State\r\nfrom l2server.gameserver.model.quest.jython import QuestJython as JQuest\r\nfrom l2server.util import Rnd\r\n\r\nqn = \"10280_MutatedKaneusSchuttgart\"\r\n\r\n# NPCs\r\nVISHOTSKY = 31981\r\nATRAXIA = 31972\r\nVENOMOUS_STORACE = 18571\r\nKEL_BILETTE = 18573\r\n\r\n# Items\r\nTISSUE_VS = 13838\r\nTISSUE_KB = 13839\r\n\r\n\r\nclass Quest(JQuest):\r\n def __init__(self, id, name, descr):\r\n JQuest.__init__(self, id, name, descr)\r\n self.questItemIds = [TISSUE_VS, TISSUE_KB]\r\n\r\n def onAdvEvent(self, event, npc, player):\r\n htmltext = event\r\n st = player.getQuestState(qn)\r\n if not st: return\r\n\r\n if event == \"31981-03.htm\":\r\n st.setState(State.STARTED)\r\n st.set(\"cond\", \"1\")\r\n st.playSound(\"ItemSound.quest_accept\")\r\n elif event == \"31972-03.htm\":\r\n st.unset(\"cond\")\r\n st.rewardItems(57, 210000)\r\n st.exitQuest(False)\r\n st.playSound(\"ItemSound.quest_finish\")\r\n return htmltext\r\n\r\n def onTalk(self, npc, player):\r\n htmltext = Quest.getNoQuestMsg(player)\r\n st = player.getQuestState(qn)\r\n if not st: return htmltext\r\n\r\n npcId = npc.getNpcId()\r\n cond = st.getInt(\"cond\")\r\n\r\n if npcId == VISHOTSKY:\r\n if st.getState() == State.COMPLETED:\r\n htmltext = \"31981-06.htm\"\r\n elif st.getState() == State.CREATED and player.getLevel() >= 58:\r\n htmltext = \"31981-01.htm\"\r\n elif st.getState() == State.CREATED and player.getLevel() < 58:\r\n htmltext = \"31981-00.htm\"\r\n elif st.getQuestItemsCount(TISSUE_VS) > 0 and st.getQuestItemsCount(TISSUE_KB) > 0:\r\n htmltext = \"31981-05.htm\"\r\n elif cond == 1:\r\n htmltext = \"31981-04.htm\"\r\n elif npcId == ATRAXIA:\r\n if st.getState() == State.COMPLETED:\r\n htmltext = Quest.getAlreadyCompletedMsg(player)\r\n elif st.getQuestItemsCount(TISSUE_VS) > 0 and st.getQuestItemsCount(TISSUE_KB) > 0:\r\n htmltext = \"31972-02.htm\"\r\n else:\r\n htmltext = \"31972-01.htm\"\r\n return htmltext\r\n\r\n def onKill(self, npc, player, isPet):\r\n npcId = npc.getNpcId()\r\n party = player.getParty()\r\n if party:\r\n PartyMembers = []\r\n for member in party.getPartyMembers().toArray():\r\n st = member.getQuestState(qn)\r\n if st and st.getState() == State.STARTED and st.getInt(\"cond\") == 1:\r\n if npcId == VENOMOUS_STORACE and st.getQuestItemsCount(TISSUE_VS) == 0:\r\n PartyMembers.append(st)\r\n elif npcId == TISSUE_KB and st.getQuestItemsCount(TISSUE_KB) == 0:\r\n PartyMembers.append(st)\r\n if len(PartyMembers) == 0: return\r\n winnerst = PartyMembers[Rnd.get(len(PartyMembers))]\r\n if npcId == VENOMOUS_STORACE and winnerst.getQuestItemsCount(TISSUE_VS) == 0:\r\n winnerst.giveItems(TISSUE_VS, 1)\r\n winnerst.playSound(\"ItemSound.quest_itemget\")\r\n elif npcId == KEL_BILETTE and winnerst.getQuestItemsCount(TISSUE_KB) == 0:\r\n winnerst.giveItems(TISSUE_KB, 1)\r\n winnerst.playSound(\"ItemSound.quest_itemget\")\r\n else:\r\n st = player.getQuestState(qn)\r\n if not st: return\r\n if st.getState() != State.STARTED: return\r\n\r\n if npcId == VENOMOUS_STORACE and st.getQuestItemsCount(TISSUE_VS) == 0:\r\n st.giveItems(TISSUE_VS, 1)\r\n st.playSound(\"ItemSound.quest_itemget\")\r\n elif npcId == KEL_BILETTE and st.getQuestItemsCount(TISSUE_KB) == 0:\r\n st.giveItems(TISSUE_KB, 1)\r\n st.playSound(\"ItemSound.quest_itemget\")\r\n return\r\n\r\n\r\nQUEST = Quest(10280, qn, \"Mutated Kaneus - Schuttgart\")\r\n\r\nQUEST.addStartNpc(VISHOTSKY)\r\nQUEST.addTalkId(VISHOTSKY)\r\nQUEST.addTalkId(ATRAXIA)\r\n\r\nQUEST.addKillId(VENOMOUS_STORACE)\r\nQUEST.addKillId(KEL_BILETTE)\r\n","sub_path":"data/scripts/quests/10280_MutatedKaneusSchuttgart/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"359414939","text":"import os\nimport requests\n\nfrom time import time\nfrom time import sleep\nfrom TwitterAPI import TwitterAPI\nfrom tqdm import tqdm\n\nfrom .social_manager import SocialManager\nfrom ..db import db\nfrom .. import logger\n\n\nclass TwitterManager(SocialManager):\n db_hash = 'twitter_accounts'\n\n STATUS_CHOICES = [\n \"\"\"🇵🇴🇷🇳 🔞\n\nKeep calm and watch this porn! 🍌\n\n{title}:\n{url}\"\"\",\n \"\"\"🇵🇴🇷🇳 🔞\n\nWatch this porn with your lover... ♀♂️️\n\nFull video here => {url}\n{title}\"\"\",\n \"\"\"🇵🇴🇷🇳 🔞\n\nDid you see? 🙈 {title}\n\n{url}\"\"\",\n \"\"\"🇵🇴🇷🇳 🔞\n\nfun4all ♀♂️️ sex is allowed\n\nContinue... {url}\n{title}\"\"\",\n \"\"\"🇵🇴🇷🇳 🔞\n\nBe evil 😈 ...\n... just in bed\n\n{title},\nfull video {url}\"\"\",\n \"\"\"🇵🇴🇷🇳 🔞\n\nWe love sex too ❤️\n\nWatch full video {url}\n{title}\"\"\",\n \"\"\"🇵🇴🇷🇳 🔞\n\nAvailable to fun, come here.\n👌💢\n\nSee {title} here...\n{url}\"\"\",\n \"\"\"🇵🇴🇷🇳 🔞\n\n{url}\n🔝🔝 Click and watch full video!\n\n{title}\"\"\",\n ]\n\n def __init__(self, ck, cs, tk, ts, like_tweets_from=None, me=None,\n **kwargs):\n self.ck = ck\n self.cs = cs\n self.tk = tk\n self.ts = ts\n self.like_tweets_from = like_tweets_from\n self._me = me\n\n super().__init__(**kwargs)\n\n @property\n def api(self):\n return TwitterAPI(self.ck, self.cs, self.tk, self.ts)\n\n @property\n def me(self):\n if not self._me:\n self.update_me()\n return self._me\n\n @property\n def last_tweet_liked_db_hash(self):\n return f'twitter_last_tweet_liked_{self.id}'\n\n def validate(self):\n try:\n self.update_me()\n me = self.me\n if me:\n return True\n except Exception as e:\n pass\n return False\n\n def get_id(self):\n return self.me.get('id')\n\n def get_data(self):\n return {\n 'ck': self.ck,\n 'cs': self.cs,\n 'tk': self.tk,\n 'ts': self.ts,\n 'me': self.me,\n 'like_tweets_from': self.like_tweets_from,\n }\n\n def update_me(self):\n r = self.api.request('account/verify_credentials')\n try:\n r.response.raise_for_status()\n except requests.exceptions.RequestException as e:\n logger.error(f'status code: {r.response.status_code}')\n logger.error(f'content: {r.response.content}')\n raise e\n self._me = r.json()\n\n def upload_video(self, video_file, **kwargs):\n return self.upload_media(\n video_file,\n 'video/mp4',\n 'tweet_video',\n **kwargs)\n\n def upload_gif(self, gif_file, **kwargs):\n return self.upload_media(\n gif_file,\n 'image/gif',\n 'tweet_gif',\n **kwargs)\n\n def upload_media(self, media_file, media_type, media_category, **kwargs):\n bytes_sent = 0\n total_bytes = os.stat(media_file.name).st_size\n\n r = self.api.request(\n 'media/upload',\n {\n 'command': 'INIT',\n 'media_type': media_type,\n 'media_category': media_category,\n 'total_bytes': total_bytes,\n })\n try:\n r.response.raise_for_status()\n except requests.exceptions.RequestException as e:\n logger.error(f'status code: {r.response.status_code}')\n logger.error(f'content: {r.response.content}')\n raise e\n\n media_id = r.json().get('media_id')\n if not media_id:\n raise Exception('no media id')\n\n segment_index = 0\n with tqdm(total=total_bytes, unit='bytes') as pbar:\n while bytes_sent < total_bytes:\n chunk = media_file.read(256 * 1024)\n r = self.api.request(\n 'media/upload',\n {\n 'command': 'APPEND',\n 'media_id': media_id,\n 'segment_index': segment_index,\n },\n {\n 'media': chunk,\n })\n try:\n r.response.raise_for_status()\n except requests.exceptions.RequestException as e:\n logger.error(f'status code: {r.response.status_code}')\n logger.error(f'content: {r.response.content}')\n raise e\n segment_index += 1\n chunck_size = media_file.tell()\n bytes_sent = chunck_size\n pbar.update(chunck_size)\n\n r = self.api.request(\n 'media/upload',\n {\n 'command': 'FINALIZE',\n 'media_id': media_id,\n })\n try:\n r.response.raise_for_status()\n except requests.exceptions.RequestException as e:\n logger.error(f'status code: {r.response.status_code}')\n logger.error(f'content: {r.response.content}')\n raise e\n\n while True:\n r = self.api.request(\n 'media/upload',\n {\n 'command': 'STATUS',\n 'media_id': media_id,\n },\n method_override='GET')\n try:\n r.response.raise_for_status()\n except requests.exceptions.RequestException as e:\n logger.error(f'status code: {r.response.status_code}')\n logger.error(f'content: {r.response.content}')\n raise e\n logger.debug(f'status: {r.response.content}')\n state = r.json().get('processing_info', {}).get('state')\n logger.debug(f'state: {state}')\n if state not in ['in_progress', 'failed', 'succeeded']:\n raise Exception('invalid state')\n if state == 'failed':\n raise Exception('failed')\n if state == 'succeeded':\n break\n logger.debug('waiting 5 secs to new status...')\n sleep(5)\n\n r_params = {\n 'media_ids': media_id,\n }\n r_params.update(kwargs)\n r = self.api.request(\n 'statuses/update',\n r_params)\n try:\n r.response.raise_for_status()\n except requests.exceptions.RequestException as e:\n logger.error(f'status code: {r.response.status_code}')\n logger.error(f'content: {r.response.content}')\n raise e\n tweet_id = r.json().get('id')\n return tweet_id\n\n def enable_to_like_tweet(self, user_id):\n last_liked_tweet_byte = db.hget(self.last_tweet_liked_db_hash, user_id)\n last_liked_tweet = float(last_liked_tweet_byte.decode()) \\\n if last_liked_tweet_byte else 0\n next_like_tweet = last_liked_tweet + (60 * 60 * 12)\n return time() > next_like_tweet\n\n def last_like_tweet(self, user_id):\n db.hset(self.last_tweet_liked_db_hash, user_id, time())\n","sub_path":"iycaro/core/social_managers/twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":7119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"569417878","text":"from astropy.io import fits\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import interpolate, optimize, ndimage\nfrom photutils.centroids import centroid_com, centroid_2dg # centroid_quadratic,\nimport time\nfrom astropy import convolution\n\n\ndef gaussian(height, center_x, center_y, width_x, width_y):\n \"\"\"Returns a gaussian function with the given parameters\"\"\"\n return lambda x,y: height*np.exp(-(((center_x-x)/width_x)**2+((center_y-y)/width_y)**2)/2)\n\ndef moments(data):\n \"\"\"Returns (height, x, y, width_x, width_y)\n the gaussian parameters of a 2D distribution by calculating its\n moments \"\"\"\n total = data.sum()\n X, Y = np.indices(data.shape)\n x = (X*data).sum()/total\n y = (Y*data).sum()/total\n col = data[:, int(y)]\n width_x = np.sqrt(np.abs((np.arange(col.size)-x)**2*col).sum()/col.sum())\n row = data[int(x), :]\n width_y = np.sqrt(np.abs((np.arange(row.size)-y)**2*row).sum()/row.sum())\n height = data.max()\n return height, x, y, width_x, width_y\n\ndef fitgaussian(data):\n \"\"\"Returns (height, x, y, width_x, width_y)\n the gaussian parameters of a 2D distribution found by a fit\"\"\"\n params = moments(data)\n errorfunction = lambda p: np.ravel(gaussian(*p)(*np.indices(data.shape)) -\n data)\n p, success = optimize.leastsq(errorfunction, params)\n return p\n\n\ndef fitconvolve(sigma, data1, data2):\n \"\"\"\n\n :return:\n \"\"\"\n\n if sigma[0] <= 1e-15 or np.isinf(sigma[0]) or sigma[1] <= 1e-15 or np.isinf(sigma[1]):\n zero = np.inf\n\n else:\n # convolve I-band PSF (data1) with kernel with unknown FWHM (sigma[0], sigma[1]) to match H-band PSF (data2)\n zero = np.nansum(ndimage.gaussian_filter(data1, [sigma[0], sigma[1]]) - data2)\n\n return [zero, 0.]\n\ndef fitsigma(sigma, data1, data2):\n\n return np.nansum(ndimage.gaussian_filter(data1, [sigma[0], sigma[1]]) - data2)\n\ndef vfit(sigma, *kwargs):\n\n return [fitsigma(sigma, *kwargs), 0.]\n\ndef twoD_gaussian(x, height, center_x, center_y, width_x, width_y):\n \"\"\"Returns a gaussian function with the given parameters\"\"\"\n return height*np.exp(-(((center_x-x[0])/width_x)**2+((center_y-x[1])/width_y)**2)/2)\n\ndef do_2dgaussfit(data, plots=False):\n data = np.nan_to_num(data)\n params = fitgaussian(data)\n fit = gaussian(*params)\n (height, x, y, width_x, width_y) = params\n # print(params)\n\n if plots:\n plt.contour(fit(*np.indices(data.shape)))\n ax = plt.gca()\n\n plt.text(0.95, 0.05, \"\"\"x : %.1f\\ny : %.1f\\nwidth_x : %.1f\\nwidth_y : %.1f\"\"\" % (x, y, width_x, width_y),\n fontsize=16, horizontalalignment='right', verticalalignment='bottom', transform=ax.transAxes)\n plt.show()\n return params\n\n\ng2698 = '/Users/jonathancohn/Documents/dyn_mod/galfit/u2698/'\ngf = '/Users/jonathancohn/Documents/dyn_mod/galfit/'\nfj = '/Users/jonathancohn/Documents/dyn_mod/for_jonathan/'\nhst_p = '/Users/jonathancohn/Documents/hst_pgc11179/'\nhst_n = '/Users/jonathancohn/Documents/hst_ngc384/'\nn384_h = fj + 'NGC0384_F160W_drz_sci.fits'\nn384_adj_h = fj + 'NGC0384_F160W_drz_sci_adjusted.fits'\nn384_hmask = fj + 'NGC0384_F160W_drz_mask.fits'\nn384_hmask_extended = fj + 'NGC0384_F160W_drz_mask_extended.fits'\nn384_f814w_pixscale03 = fj + 'NGC0384_F814W_drc_sci.fits'\npsfH = fj + 'psfH.fits'\n\np11179_h = fj + 'PGC11179_F160W_drz_sci.fits'\np11179_adj_h = fj + 'PGC11179_F160W_drz_sci_adjusted.fits'\n\n# DRIZZLED F814W IMAGES\nn384_f814w_pxf08 = hst_n + 'n384_f814w_drizflc_pxf08_006_sci.fits'\np11179_f814w_pxf08 = hst_p + 'p11179_f814w_drizflc_006_sci.fits' # pxf08!\n\n# WRITE CONVOLVED I-BAND IMAGES\nn384_I_convolved_wamp = hst_n + 'n384_f814w_drizflc_pxf08_006_sci_convolved_wamp.fits'\nn384_I_convolved_namp = hst_n + 'n384_f814w_drizflc_pxf08_006_sci_convolved_namp.fits'\np11179_I_convolved_wamp = hst_p + 'p11179_f814w_drizflc_pxf08_006_sci_convolved_wamp.fits'\np11179_I_convolved_namp = hst_p + 'p11179_f814w_drizflc_pxf08_006_sci_convolved_namp.fits'\n\n# FINAL PSFs\np11179_driz_f814w_psf = hst_p + 'p11179_f814w_drizflc_pxf08_006_psf_take2_sci.fits'\np11179_driz_f814w_psfcen = hst_p + 'p11179_f814w_drizflc_pxf08_006_psf_centroid_sci.fits'\np11179_driz_f814w_psfben = hst_p + 'p11179_f814w_drizflc_pxf08_006_psf_benstyle_sci.fits'\nn384_driz_f814w_psf = hst_n + 'n384_f814w_drizflc_pxf08_006_psf_take2_sci.fits'\nn384_driz_f814w_psfcen = hst_n + 'n384_f814w_drizflc_pxf08_006_psf_centroid_sci.fits'\nn384_driz_f814w_psfben = hst_n + 'n384_f814w_drizflc_pxf08_006_psf_benstyle_sci.fits'\n\nzp_H = 24.662 # https://www.stsci.edu/hst/instrumentation/wfc3/data-analysis/photometric-calibration/ir-photometric-calibration\nzp_I = 24.699 # ACTUALLY UVIS1!! (UVIS2=24.684)\n# https://www.stsci.edu/hst/instrumentation/wfc3/data-analysis/photometric-calibration/uvis-photometric-calibration\n\nwith fits.open(p11179_driz_f814w_psf) as hdu:\n hdr_pgc_psf_f814w = hdu[0].header\n dat_pgc_psf_f814w = hdu[0].data\n\nwith fits.open(p11179_driz_f814w_psfcen) as hdu:\n hdr_pgc_psfcen_f814w = hdu[0].header\n dat_pgc_psfcen_f814w = hdu[0].data\n\nwith fits.open(p11179_driz_f814w_psfben) as hdu:\n hdr_pgc_psfben_f814w = hdu[0].header\n dat_pgc_psfben_f814w = hdu[0].data\n\nwith fits.open(n384_driz_f814w_psf) as hdu:\n hdr_ngc_psf_f814w = hdu[0].header\n dat_ngc_psf_f814w = hdu[0].data\n\nwith fits.open(n384_driz_f814w_psfcen) as hdu:\n hdr_ngc_psfcen_f814w = hdu[0].header\n dat_ngc_psfcen_f814w = hdu[0].data\n\nwith fits.open(n384_driz_f814w_psfben) as hdu:\n hdr_ngc_psfben_f814w = hdu[0].header\n dat_ngc_psfben_f814w = hdu[0].data\n\nwith fits.open(psfH) as hdu:\n hdr_psfH = hdu[0].header\n dat_psfH = hdu[0].data\n\nwith fits.open(n384_f814w_pxf08) as hdu:\n hdr_nI = hdu[0].header\n dat_nI = hdu[0].data\n\nwith fits.open(p11179_f814w_pxf08) as hdu:\n hdr_pI = hdu[0].header\n dat_pI = hdu[0].data\n\nres = 0.06 # arcsec/pix\n\n# METHOD 2\nt0 = time.time()\nprint('start')\ndef twoD_gaussian(x, height, center_x, center_y, width_x, width_y):\n \"\"\"Returns a gaussian function with the given parameters\"\"\"\n return height*np.exp(-(((center_x-x[0])/width_x)**2+((center_y-x[1])/width_y)**2)/2)\n\ndef conv(pars, dataI):\n height, center_x, center_y, width_x, width_y = pars\n\n x = np.linspace(0, len(dataI), len(dataI))\n y = np.linspace(0, len(dataI[0]), len(dataI[0]))\n x, y = np.meshgrid(x, y)\n\n twoDG = np.exp(-(((center_x - x) / width_x) ** 2 + ((center_y - y) / width_y) ** 2) / 2)\n\n return convolution.convolve(dataI * height, twoDG)\n\ndef zero_conv(pars, dataH, dataI):\n\n icon = conv(pars, dataI)\n icon /= np.nanmax(icon)\n\n return np.abs(np.nansum((icon - dataH)**2))\n\ndef conv_noamp(pars, dataI):\n center_x, center_y, width_x, width_y = pars\n\n x = np.linspace(0, len(dataI), len(dataI))\n y = np.linspace(0, len(dataI[0]), len(dataI[0]))\n x, y = np.meshgrid(x, y)\n\n twoDG = np.exp(-(((center_x - x) / width_x) ** 2 + ((center_y - y) / width_y) ** 2) / 2)\n\n return convolution.convolve(dataI, twoDG)\n\ndef zero_conv_noamp(pars, dataH, dataI):\n\n icon = conv_noamp(pars, dataI)\n icon /= np.nanmax(icon)\n\n return np.abs(np.nansum((icon - dataH)**2))\n\ndef matchfwhm(pars, dath, dati):\n sigx, sigy = pars\n g2dh = do_2dgaussfit(dath)\n convolved = ndimage.gaussian_filter(dati, [sigx, sigy]) # convolve with kernel!\n g2dicon = do_2dgaussfit(convolved)\n sigma_diffs = np.array([(g2dicon[3] - g2dh[3])**2, (g2dicon[4] - g2dh[4])**2])\n\n return np.abs(sum(sigma_diffs))\n\n\n# NORMALIZE PSFs!\ndat_psfH /= np.nanmax(dat_psfH)\ndat_ngc_psfcen_f814w /= np.nanmax(dat_ngc_psfcen_f814w)\ndat_pgc_psfcen_f814w /= np.nanmax(dat_pgc_psfcen_f814w)\n\n# psfH peak is centered on 40,40; current peak is at NGC 1927,1922 -> 1882:1882+81, 1887:1887+81\ndat_npsfi = dat_ngc_psfcen_f814w[1882:1882+81, 1887:1887+81] # correct!\ndat_ppsfi = dat_pgc_psfcen_f814w[1606:1606+81, 1542:1542+81]\n# psfH peak is centered on 40,40; current peak is at PGC 1646.4766,1582.24407 -> 1606:1606+81, 1542:1542+81\n#g2di = do_2dgaussfit(dat_psfi) # [1.04957099e-03 1.46476646e+02 8.22440674e+01 8.65402657e-01 8.51768218e-01] # p11179\n#plt.imshow(dat_ppsfi, origin='lower')\n#plt.colorbar()\n#plt.show()\n#plt.imshow(dat_npsfi, origin='lower')\n#plt.colorbar()\n#plt.show()\n#plt.imshow(dat_psfH, origin='lower')\n#plt.colorbar()\n#plt.show()\n#plt.imshow((dat_npsfi - dat_psfH)/dat_psfH, origin='lower')\n#plt.text(5, 70, '(PSF_I - PSF_H)/PSF_H', color='w')\n#plt.colorbar()\n#plt.show()\n#print(oops)\n\n# METHOD 1\n# calculate sigmas from 2D gaussians\n# gn = do_2dgaussfit(dat_ngc_psfcen_f814w[1820:2021, 1800:2021]) # [1.10704459e-03 1.92214472e+03 1.92717995e+03 8.18216509e-01 8.47028032e-01]\n# gp = do_2dgaussfit(dat_pgc_psfcen_f814w[1500:1701, 1500:1701]) # [1.04957099e-03 1.64647665e+03 1.58224407e+03 8.65402658e-01 8.51768218e-01]\ngn = do_2dgaussfit(dat_npsfi) # [1.10704459e-03 1.92214472e+03 1.92717995e+03 8.18216509e-01 8.47028032e-01]\ngp = do_2dgaussfit(dat_ppsfi) # [1.04957099e-03 1.64647665e+03 1.58224407e+03 8.65402658e-01 8.51768218e-01]\ngH = do_2dgaussfit(dat_psfH) # [ 0.04847133 40.03064685 39.91339118 1.45843277 1.49161195]\n\ndiff_sigma_px = np.sqrt(gH[3]**2 - gp[3]**2) # diff in quadrature! # 1.2072894820619162\ndiff_sigma_py = np.sqrt(gH[4]**2 - gp[4]**2) # diff in quadrature! # 1.2277824434215172\ndiff_sigma_nx = np.sqrt(gH[3]**2 - gn[3]**2) # diff in quadrature! # 1.1739269102067171\ndiff_sigma_ny = np.sqrt(gH[4]**2 - gn[4]**2) # diff in quadrature! # 1.2244987215858145\n\nn_psficon_m1 = ndimage.gaussian_filter(dat_npsfi, [diff_sigma_nx, diff_sigma_ny]) # convolve with kernel!\nn_daticon_m1 = ndimage.gaussian_filter(dat_nI, [diff_sigma_nx, diff_sigma_ny]) # convolve with kernel!\np_psficon_m1 = ndimage.gaussian_filter(dat_ppsfi, [diff_sigma_px, diff_sigma_py]) # convolve with kernel!\np_daticon_m1 = ndimage.gaussian_filter(dat_pI, [diff_sigma_px, diff_sigma_py]) # convolve with kernel!\n\nprint(np.nansum(dat_nI))\nprint(np.nansum(n_daticon_m1))\nprint(np.nansum(dat_npsfi))\nprint(np.nansum(n_psficon_m1))\nn_psficon_m1 /= np.nanmax(n_psficon_m1)\np_psficon_m1 /= np.nanmax(p_psficon_m1)\nprint(np.nansum(n_psficon_m1))\n# print(oops)\n# PSFs: n_psficon_m1,p_psficon_m1 ;; GALAXY IMAGES: n_daticon_m1,p_daticon_m1\nprint('m1 done')\n''' #\nfig, ax = plt.subplots(2, 2, figsize=(8,8))\nfig.subplots_adjust(wspace=0.1, hspace=0.1)\nfig.suptitle('Method 1')\nim00 = ax[0][0].imshow((n_psficon_m1 - dat_psfH), origin='lower')\nax[0][0].text(1, 70, 'NGC (PSF_I - PSF_H)', color='w')\ncbar00 = fig.colorbar(im00, ax=ax[0][0], pad=0.02)\nim01 = ax[0][1].imshow((p_psficon_m1 - dat_psfH), origin='lower')\nax[0][1].text(1, 70, 'PGC (PSF_I - PSF_H)', color='w')\ncbar01 = fig.colorbar(im01, ax=ax[0][1], pad=0.02)\nim10 = ax[1][0].imshow((n_psficon_m1 - dat_psfH)/dat_psfH, origin='lower')\nax[1][0].text(1, 70, 'NGC (PSF_I - PSF_H)/PSF_H', color='w')\ncbar10 = fig.colorbar(im10, ax=ax[1][0], pad=0.02)\nim11 = ax[1][1].imshow((p_psficon_m1 - dat_psfH)/dat_psfH, origin='lower')\nax[1][1].text(1, 70, 'PGC (PSF_I - PSF_H)/PSF_H', color='w')\ncbar11 = fig.colorbar(im11, ax=ax[1][1], pad=0.02)\nplt.show()\nprint(oops)\n# ''' #\n\n# METHOD 2A\nsig_guess = (1.2,1.2)\nn_sol_m2a = optimize.fmin(matchfwhm, x0=sig_guess, args=(dat_psfH, dat_npsfi))\ng2dh = do_2dgaussfit(dat_psfH)\nn_psficon_m2a = ndimage.gaussian_filter(dat_npsfi, [n_sol_m2a[0], n_sol_m2a[1]]) # convolve with kernel!\nprint(np.nansum(dat_npsfi), np.nansum(n_psficon_m2a), 'm2a are these the same? (PSF)')\nn_psficon_m2a /= np.nanmax(n_psficon_m2a) # re-normalize?!\nprint(np.nansum(n_psficon_m2a), 'normed')\ng2diconn_m2a = do_2dgaussfit(n_psficon_m2a)\n\np_sol_m2a = optimize.fmin(matchfwhm, x0=sig_guess, args=(dat_psfH, dat_ppsfi))\np_psficon_m2a = ndimage.gaussian_filter(dat_ppsfi, [p_sol_m2a[0], p_sol_m2a[1]]) # convolve with kernel!\np_psficon_m2a /= np.nanmax(p_psficon_m2a) # re-normalize?!\ng2diconp_m2a = do_2dgaussfit(p_psficon_m2a)\nprint(n_sol_m2a)\nprint(p_sol_m2a)\nprint(g2dh)\nprint(g2diconn_m2a)\nprint(g2diconp_m2a)\n\nn_daticon_m2a = ndimage.gaussian_filter(dat_nI, [n_sol_m2a[0], n_sol_m2a[1]]) # convolve with kernel!\np_daticon_m2a = ndimage.gaussian_filter(dat_pI, [p_sol_m2a[0], p_sol_m2a[1]]) # convolve with kernel!\n# PSFs: n_psficon_m2a,p_psficon_m2a ;; GALAXY IMAGES: n_daticon_m2a,p_daticon_m2a\nprint(np.nansum(dat_nI))\nprint(np.nansum(n_daticon_m2a), 'are these the same?')\n\n#fig, ax = plt.subplots(1, 2, figsize=(8,8))\n#fig.subplots_adjust(wspace=0.1, hspace=0.1)\n#im0 = ax[0].imshow((n_psficon_m2a - dat_psfH)/dat_psfH, origin='lower') # / dat_psfH\n#ax[0].text(5, 70, 'NGC (PSF_I - PSF_H)/PSF_H', color='w') # /PSF_H\n#cbar0 = fig.colorbar(im0, ax=ax[0], pad=0.02)\n#im1 = ax[1].imshow((p_psficon_m2a - dat_psfH)/dat_psfH, origin='lower') # / dat_psfH\n#ax[1].text(5, 70, 'PGC (PSF_I - PSF_H)/PSF_H', color='w') # /PSF_H\n#cbar1 = fig.colorbar(im1, ax=ax[1], pad=0.02)\n#plt.show()\n''' #\nfig, ax = plt.subplots(2, 2, figsize=(8,8))\nfig.subplots_adjust(wspace=0.1, hspace=0.1)\nfig.suptitle('Method 2a')\nim00 = ax[0][0].imshow((n_psficon_m2a - dat_psfH), origin='lower')\nax[0][0].text(1, 70, 'NGC (PSF_I - PSF_H)', color='w')\ncbar00 = fig.colorbar(im00, ax=ax[0][0], pad=0.02)\nim01 = ax[0][1].imshow((p_psficon_m2a - dat_psfH), origin='lower')\nax[0][1].text(1, 70, 'PGC (PSF_I - PSF_H)', color='w')\ncbar01 = fig.colorbar(im01, ax=ax[0][1], pad=0.02)\nim10 = ax[1][0].imshow((n_psficon_m2a - dat_psfH)/dat_psfH, origin='lower')\nax[1][0].text(1, 70, 'NGC (PSF_I - PSF_H)/PSF_H', color='w')\ncbar10 = fig.colorbar(im10, ax=ax[1][0], pad=0.02)\nim11 = ax[1][1].imshow((p_psficon_m2a - dat_psfH)/dat_psfH, origin='lower')\nax[1][1].text(1, 70, 'PGC (PSF_I - PSF_H)/PSF_H', color='w')\ncbar11 = fig.colorbar(im11, ax=ax[1][1], pad=0.02)\nplt.show()\nprint(oops)\n# ''' #\nprint('m2a done')\n\n\n# METHOD 2B - with amplitude\nuse_guess = (1., 40., 40., 1.2, 1.2)\nn_sol_m2b = optimize.fmin(zero_conv, x0=use_guess, args=(dat_psfH, dat_npsfi))\nn_psficon_m2b = conv(n_sol_m2b, dat_npsfi)\nprint(np.nansum(dat_npsfi), np.nansum(n_psficon_m2b), 'are these the same? (PSF)')\nn_psficon_m2b /= np.nanmax(n_psficon_m2b)\nprint(np.nansum(n_psficon_m2b), 'normalized')\nn_daticon_m2b = conv(n_sol_m2b, dat_nI[1882:1882+81, 1887:1887+81])\nprint(np.nansum(dat_nI[1882:1882+81, 1887:1887+81]), np.nansum(n_daticon_m2b), 'are these the same? (dat, 2b withamp)')\n# print(oops)\n\np_sol_m2b = optimize.fmin(zero_conv, x0=use_guess, args=(dat_psfH, dat_ppsfi))\np_psficon_m2b = conv(p_sol_m2b, dat_ppsfi)\np_psficon_m2b /= np.nanmax(p_psficon_m2b)\nprint(n_sol_m2b)\nprint(p_sol_m2b)\n# print(oop)\n#p_daticon_m2b = conv(p_sol_m2b, dat_pI)\n# PSFs: n_psficon_m2b,p_psficon_m2b ;; GALAXY IMAGES: n_daticon_m2b,p_daticon_m2b\nprint('m2b done')\n''' #\nfig, ax = plt.subplots(2, 2, figsize=(8,8))\nfig.subplots_adjust(wspace=0.1, hspace=0.1)\nfig.suptitle('Method 2b')\nim00 = ax[0][0].imshow((n_psficon_m2b - dat_psfH), origin='lower')\nax[0][0].text(1, 70, 'NGC (PSF_I - PSF_H)', color='w')\ncbar00 = fig.colorbar(im00, ax=ax[0][0], pad=0.02)\nim01 = ax[0][1].imshow((p_psficon_m2b - dat_psfH), origin='lower')\nax[0][1].text(1, 70, 'PGC (PSF_I - PSF_H)', color='w')\ncbar01 = fig.colorbar(im01, ax=ax[0][1], pad=0.02)\nim10 = ax[1][0].imshow((n_psficon_m2b - dat_psfH)/dat_psfH, origin='lower')\nax[1][0].text(1, 70, 'NGC (PSF_I - PSF_H)/PSF_H', color='w')\ncbar10 = fig.colorbar(im10, ax=ax[1][0], pad=0.02)\nim11 = ax[1][1].imshow((p_psficon_m2b - dat_psfH)/dat_psfH, origin='lower')\nax[1][1].text(1, 70, 'PGC (PSF_I - PSF_H)/PSF_H', color='w')\ncbar11 = fig.colorbar(im11, ax=ax[1][1], pad=0.02)\nplt.show()\n#print(oops)\n# ''' #\n\n# METHOD 2B - no amplitude\nguess_noamp = (40., 40., 1.2, 1.2)\nn_sol_m2bnoamp = optimize.fmin(zero_conv_noamp, x0=guess_noamp, args=(dat_psfH, dat_npsfi))\nn_psficon_m2bnoamp = conv_noamp(n_sol_m2bnoamp, dat_npsfi)\nprint(np.nansum(dat_npsfi), np.nansum(n_psficon_m2bnoamp), '(2b noamp, PSF)')\nn_psficon_m2bnoamp /= np.nanmax(n_psficon_m2bnoamp)\nn_daticon_m2bnoamp = conv_noamp(n_sol_m2bnoamp, dat_nI[1882:1882+81, 1887:1887+81])\nprint(np.nansum(n_psficon_m2bnoamp), 'PSF, normalized')\nprint(np.nansum(dat_nI[1882:1882+81, 1887:1887+81]), np.nansum(n_daticon_m2bnoamp), 'dat, 2b noamp')\nprint(oops)\nplt.imshow(dat_nI[1882:1882+81, 1887:1887+81] - n_daticon_m2b, origin='lower')\nplt.colorbar()\nplt.show()\nplt.imshow(dat_nI[1882:1882+81, 1887:1887+81] - n_daticon_m2bnoamp, origin='lower')\nplt.colorbar()\nplt.show()\nprint(oops)\n\np_sol_m2bnoamp = optimize.fmin(zero_conv_noamp, x0=guess_noamp, args=(dat_psfH, dat_ppsfi))\np_psficon_m2bnoamp = conv_noamp(p_sol_m2bnoamp, dat_ppsfi)\np_psficon_m2bnoamp /= np.nanmax(p_psficon_m2bnoamp)\np_daticon_m2bnoamp = conv_noamp(p_sol_m2bnoamp, dat_pI)\n# PSFs: n_psficon_m2bnoamp,p_psficon_m2bnoamp ;; GALAXY IMAGES: n_daticon_m2bnoamp,p_daticon_m2bnoamp\nprint(n_sol_m2bnoamp)\nprint(p_sol_m2bnoamp)\nprint('m2bnoamp done')\n\nprint(n_psficon_m1.shape)\nprint(n_psficon_m2a.shape)\nprint(n_psficon_m2b.shape)\n''' #\nfig, ax = plt.subplots(2, 2, figsize=(8,8))\nfig.subplots_adjust(wspace=0.1, hspace=0.1)\nfig.suptitle('Method 2b no amplitude')\nim00 = ax[0][0].imshow((n_psficon_m2bnoamp - dat_psfH), origin='lower')\nax[0][0].text(1, 70, 'NGC (PSF_I - PSF_H)', color='w')\ncbar00 = fig.colorbar(im00, ax=ax[0][0], pad=0.02)\nim01 = ax[0][1].imshow((p_psficon_m2bnoamp - dat_psfH), origin='lower')\nax[0][1].text(1, 70, 'PGC (PSF_I - PSF_H)', color='w')\ncbar01 = fig.colorbar(im01, ax=ax[0][1], pad=0.02)\nim10 = ax[1][0].imshow((n_psficon_m2bnoamp - dat_psfH)/dat_psfH, origin='lower')\nax[1][0].text(1, 70, 'NGC (PSF_I - PSF_H)/PSF_H', color='w')\ncbar10 = fig.colorbar(im10, ax=ax[1][0], pad=0.02)\nim11 = ax[1][1].imshow((p_psficon_m2bnoamp - dat_psfH)/dat_psfH, origin='lower')\nax[1][1].text(1, 70, 'PGC (PSF_I - PSF_H)/PSF_H', color='w')\ncbar11 = fig.colorbar(im11, ax=ax[1][1], pad=0.02)\nplt.show()\nprint(oops)\n# ''' #\n\n\n# MAKE PLOTS\n# PSFs: n_psficon_m1,p_psficon_m1 ;; GALAXY IMAGES: n_daticon_m1,p_daticon_m1\n# PSFs: n_psfconvolved_m2a,p_psfconvolved_m2a ;; GALAXY IMAGES: n_dataconvolved_m2a,p_dataconvolved_m2a\n# PSFs: n_psficon_m2b,p_psficon_m2b ;; GALAXY IMAGES: n_daticon_m2b,p_daticon_m2b\n# PSFs: n_psficon_m2bnoamp,p_psficon_m2bnoamp ;; GALAXY IMAGES: n_daticon_m2bnoamp,p_daticon_m2bnoamp\n''' #\nfig, ax = plt.subplots(2, 3, figsize=(20,7))\nfig.subplots_adjust(wspace=0.1, hspace=0.1)\nim0 = ax[0][0].imshow(dat_npsfi, origin='lower')\nax[0][0].text(5, 70, 'NGC PSF I-band', color='w')\ncbar0 = fig.colorbar(im0, ax=ax[0][0], pad=0.02)\n\nim01 = ax[0][1].imshow(n_psficon_m1, origin='lower')\nax[0][1].text(5, 70, 'NGC PSF I-band M1', color='w')\ncbar01 = fig.colorbar(im01, ax=ax[0][1], pad=0.02)\n\nim02 = ax[0][2].imshow(n_psficon_m2a, origin='lower')\nax[0][2].text(5, 70, 'NGC PSF I-band M2a', color='w')\ncbar02 = fig.colorbar(im02, ax=ax[0][2], pad=0.02)\n\nim10 = ax[1][0].imshow(n_psficon_m2b, origin='lower')\nax[1][0].text(5, 70, 'NGC PSF I-band M2b', color='w')\ncbar10 = fig.colorbar(im10, ax=ax[1][0], pad=0.02)\n\nim11 = ax[1][1].imshow(n_psficon_m2b, origin='lower')\nax[1][1].text(5, 70, 'NGC PSF I-band M2b\\nnoamp', color='w')\ncbar11 = fig.colorbar(im11, ax=ax[1][1], pad=0.02)\n\nim12 = ax[1][2].imshow(dat_psfH, origin='lower')\nax[1][2].text(5, 70, 'PSF H-band', color='w')\ncbar12 = fig.colorbar(im12, ax=ax[1][2], pad=0.02)\nplt.show()\nprint(oop)\n# ''' #\n\nfig, ax = plt.subplots(2, 4, figsize=(20,8))\nfig.subplots_adjust(wspace=0.1, hspace=0.1)\nim0 = ax[0][0].imshow((n_psficon_m1 - n_psficon_m2a)/n_psficon_m2a, origin='lower')#, vmin=-1., vmax=1.)\nax[0][0].text(5, 70, 'NGC (1 - 2a)/2a', color='m')\ncbar0 = fig.colorbar(im0, ax=ax[0][0], pad=0.02)\nim01 = ax[0][1].imshow((p_psficon_m1 - p_psficon_m2a)/p_psficon_m2a, origin='lower')#, vmin=-1., vmax=1.)\nax[0][1].text(5, 70, 'PGC (1 - 2a)/2a', color='m')\ncbar01 = fig.colorbar(im01, ax=ax[0][1], pad=0.02)\nim02 = ax[0][2].imshow((n_psficon_m1 - n_psficon_m2b)/n_psficon_m2b, origin='lower')#, vmin=-1., vmax=1.)\nax[0][2].text(5, 70, 'NGC (1 - 2b)/2b', color='m')\ncbar02 = fig.colorbar(im02, ax=ax[0][2], pad=0.02)\nim03 = ax[0][3].imshow((p_psficon_m1 - p_psficon_m2b)/p_psficon_m2b, origin='lower')#, vmin=-1., vmax=1.)\nax[0][3].text(5, 70, 'PGC (1 - 2b)/2b', color='m')\ncbar03 = fig.colorbar(im03, ax=ax[0][3], pad=0.02)\n\nim1 = ax[1][0].imshow((n_psficon_m2a - n_psficon_m2b)/n_psficon_m2b, origin='lower')#, vmin=-1., vmax=1.)\nax[1][0].text(5, 70, 'NGC (2a - 2b)/2b', color='m')\ncbar1 = fig.colorbar(im1, ax=ax[1][0], pad=0.02)\nim11 = ax[1][1].imshow((p_psficon_m2a - p_psficon_m2b)/p_psficon_m2b, origin='lower')#, vmin=-1., vmax=1.)\nax[1][1].text(5, 70, 'PGC (2a - 2b)/2b', color='m')\ncbar11 = fig.colorbar(im11, ax=ax[1][1], pad=0.02)\nim12 = ax[1][2].imshow((n_psficon_m2a - n_psficon_m2bnoamp)/n_psficon_m2bnoamp, origin='lower')#, vmin=-1., vmax=1.)\nax[1][2].text(5, 70, 'NGC (2a - 2b_noamp)/2b_noamp', color='m')\ncbar12 = fig.colorbar(im12, ax=ax[1][2], pad=0.02)\nim13 = ax[1][3].imshow((p_psficon_m2a - p_psficon_m2bnoamp)/p_psficon_m2bnoamp, origin='lower')#, vmin=-1., vmax=1.)\nax[1][3].text(5, 70, 'PGC (2a - 2b_noamp)/2b_noamp', color='m')\ncbar13 = fig.colorbar(im13, ax=ax[1][3], pad=0.02)\nplt.show()\n\nfig, ax = plt.subplots(2, 4, figsize=(20,8))\nfig.subplots_adjust(wspace=0.1, hspace=0.1)\nim0 = ax[0][0].imshow((n_psficon_m1 - n_psficon_m2a)/n_psficon_m2a, origin='lower', vmin=-2., vmax=2.)\nax[0][0].text(5, 70, 'NGC (1 - 2a)/2a', color='m')\ncbar0 = fig.colorbar(im0, ax=ax[0][0], pad=0.02)\nim01 = ax[0][1].imshow((p_psficon_m1 - p_psficon_m2a)/p_psficon_m2a, origin='lower', vmin=-2., vmax=2.)\nax[0][1].text(5, 70, 'PGC (1 - 2a)/2a', color='m')\ncbar01 = fig.colorbar(im01, ax=ax[0][1], pad=0.02)\nim02 = ax[0][2].imshow((n_psficon_m1 - n_psficon_m2b)/n_psficon_m2b, origin='lower', vmin=-2., vmax=2.)\nax[0][2].text(5, 70, 'NGC (1 - 2b)/2b', color='m')\ncbar02 = fig.colorbar(im02, ax=ax[0][2], pad=0.02)\nim03 = ax[0][3].imshow((p_psficon_m1 - p_psficon_m2b)/p_psficon_m2b, origin='lower', vmin=-2., vmax=2.)\nax[0][3].text(5, 70, 'PGC (1 - 2b)/2b', color='m')\ncbar03 = fig.colorbar(im03, ax=ax[0][3], pad=0.02)\n\nim1 = ax[1][0].imshow((n_psficon_m2a - n_psficon_m2b)/n_psficon_m2b, origin='lower', vmin=-2., vmax=2.)\nax[1][0].text(5, 70, 'NGC (2a - 2b)/2b', color='m')\ncbar1 = fig.colorbar(im1, ax=ax[1][0], pad=0.02)\nim11 = ax[1][1].imshow((p_psficon_m2a - p_psficon_m2b)/p_psficon_m2b, origin='lower', vmin=-2., vmax=2.)\nax[1][1].text(5, 70, 'PGC (2a - 2b)/2b', color='m')\ncbar11 = fig.colorbar(im11, ax=ax[1][1], pad=0.02)\nim12 = ax[1][2].imshow((n_psficon_m2a - n_psficon_m2bnoamp)/n_psficon_m2bnoamp, origin='lower', vmin=-2., vmax=2.)\nax[1][2].text(5, 70, 'NGC (2a - 2b_noamp)/2b_noamp', color='m')\ncbar12 = fig.colorbar(im12, ax=ax[1][2], pad=0.02)\nim13 = ax[1][3].imshow((p_psficon_m2a - p_psficon_m2bnoamp)/p_psficon_m2bnoamp, origin='lower', vmin=-2., vmax=2.)\nax[1][3].text(5, 70, 'PGC (2a - 2b_noamp)/2b_noamp', color='m')\ncbar13 = fig.colorbar(im13, ax=ax[1][3], pad=0.02)\nplt.show()\nprint(oops)\n\ng2di = do_2dgaussfit(dat_npsfi) # [1.10704459e-03 4.01447195e+01 4.01799546e+01 8.18216509e-01 8.47028033e-01] # n384\ng2dh = do_2dgaussfit(dat_psfH) # [ 0.04847133 40.03064685 39.91339118 1.45843277 1.49161195] # PSF H\n#print(oops)\n\n#diff_g2d = np.sqrt(g2dh**2 - g2di**2)\n#print(diff_g2d)\nuse_guess = (2., 40., 40., 1.2, 1.2)\n# guess_g2d_offset = (160., 40., 40., 1.2, 1.2)\n#guess_g2d_offset = (160., 1.2, 1.2)\n# guess_g2d_best = (159., 40., 40., diff_g2d[3], diff_g2d[4])\n#z = zero_conv(pars=guess_g2d_best, dataH=dat_psfH, dataI=dat_psfi)\n#print(z, 'check')\n#z = zero_conv(pars=guess_g2d_offset, dataH=dat_psfH, dataI=dat_psfi)\n#print(z, 'check')\nn_sol = optimize.fmin(zero_conv, x0=use_guess, args=(dat_psfH, dat_npsfi))\nn_sol[0] = 1.\nicon = conv(n_sol, dat_npsfi)\nplt.imshow((icon - dat_psfH)/dat_psfH, origin='lower')\nplt.colorbar()\nplt.show()\nprint(oops)\n# [ 2.48427812 40.21211581 40.35469594 1.09370082 1.06636333]\n# n_sol = optimize.minimize(zero_conv, x0=use_guess, args=(dat_psfH, dat_npsfi)) # same error without height as fmin!\n# [ 2.0272873 40.12498261 40.02682619 1.09610137 1.05941339]\nprint(n_sol)\np_sol = optimize.fmin(zero_conv, x0=use_guess, args=(dat_psfH, dat_ppsfi))\nprint(p_sol)\n#v print(oop)\nsol_plot = n_sol\n#print(sol, 'fmin solution')\n#print(diff_g2d)\n# NGC 384:\n# [120.0546269 40.21214241 40.35472934 1.09384867 1.06637347] fmin solution (including centerx,y) 0.0004500262\n# [121.55822138 1.13873817 1.15121924] fmin solution (NOT including centerx,y) 0.0010782303\n# PGC 11179:\n# [121.84288026 40.1249686 40.02693034 1.09615983 1.05934121] fmin solution (including centerx,y) 0.00045021565\n# [121.82100697 1.10433544 1.05780877] fmin solution (NOT including centerx,y) 0.0005105181\n\n# MAKE GALAXY PLOTS\nsol_plot[0] = 1. # comment out for withamp; else, noamp!\nsol_plot[1] = sol_plot[1]+60. # 200 vs 80 -> midpoint 100 instead of 40, so add 60!\nsol_plot[2] = sol_plot[2]+60. # 200 vs 80 -> midpoint 100 instead of 40, so add 60!\n# icon = conv(n_sol, dataI=dat_nI[1820:2021, 1830:2031]) # NGC 384\nicon = conv(sol_plot, dataI=dat_pI[1550:1751, 1500:1701]) # PGC 11179\n\n# ''' # MAKE AND SAVE NEW CONVOLVED GALAXY FILES\nn_sol = (120.0546, 1922.2121, 1927.3547, 1.0938, 1.0664)\n# n_sol = (1., 1922.2121, 1927.3547, 1.0938, 1.0664)\nsol = optimize.fmin(zero_conv, x0=guess_g2d_offset, args=(dat_psfH, dat_psfi))\n\nni_con = conv(n_sol, dataI=dat_nI) # Centers that used 40, 40: [1882:1882+81, 1887:1887+81]) # NGC 384\n\nplt.imshow(ni_con, origin='lower')\nplt.colorbar()\nplt.show()\n\np_sol = (121.8429, 1646.1250, 1582.0269, 1.0962, 1.0593)\n# p_sol = (1., 1646.1250, 1582.0269, 1.0962, 1.0593)\npi_con = conv(p_sol, dataI=dat_pI) # Centers that used 40, 40: [1606:1606+81, 1542:1542+81]) # PGC 11179\nplt.imshow(pi_con, origin='lower')\nplt.colorbar()\nplt.show()\n\nprint(oops)\n# ''' # FINISH SAVING NEW CONVOLVED GALAXY FILES\n\nfig, ax = plt.subplots(1, 2, figsize=(12,5))\nplt.subplots_adjust(wspace=0.05)\n#im0 = ax[0].imshow(dat_nI[1820:2021, 1830:2031], origin='lower', vmax=150.) # NGC 384\nim0 = ax[0].imshow(dat_pI[1550:1751, 1500:1701], origin='lower', vmax=90.) # PGC 11179\ncb0 = fig.colorbar(im0, ax=ax[0], pad=0.02)\nax[0].text(5, 170, 'I-band (original)', color='w')\n# im0 = ax[1].imshow(icon, origin='lower', vmax=150.) # NGC 384 (noamp)\n# im0 = ax[1].imshow(icon, origin='lower', vmax=12000.) # NGC 384 (withamp)\nim0 = ax[1].imshow(icon, origin='lower', vmax=90.) # PGC 11179 (noamp)\n# im0 = ax[1].imshow(icon, origin='lower', vmax=6800.) # PGC 11179 (withamp)\ncb0 = fig.colorbar(im0, ax=ax[1], pad=0.02)\nax[1].text(5, 170, 'I-band (convolved)', color='w')\nplt.show()\nprint(oops)\n# n384_psfhomog_2dgauss_5pars_iband_noamp.png # p11179_psfhomog_2dgauss_5pars_iband_noamp\n#\n\n# MAKE PSF PLOTS\nicon = conv(sol, dataI=dat_psfi)\nprint(zero_conv(pars=sol, dataH=dat_psfH, dataI=dat_psfi), 'test the solution!')\n\nfig, ax = plt.subplots(2, 2, figsize=(8,8))\nfig.subplots_adjust(wspace=0.1, hspace=0.1)\nim0 = ax[0][0].imshow(dat_psfi, origin='lower')\nax[0][0].text(5, 70, 'I-band PSF', color='w')\ncbar0 = fig.colorbar(im0, ax=ax[0][0], pad=0.02)\nim01 = ax[0][1].imshow(dat_psfH, origin='lower')\nax[0][1].text(5, 70, 'H-band PSF', color='w')\ncbar01 = fig.colorbar(im01, ax=ax[0][1], pad=0.02)\nim1 = ax[1][0].imshow(icon, origin='lower')\nax[1][0].text(5, 70, 'convolved I-band', color='w')\ncbar1 = fig.colorbar(im1, ax=ax[1][0], pad=0.02)\nim2 = ax[1][1].imshow((dat_psfH - icon), origin='lower')\nax[1][1].text(5, 70, r'H-band $-$ convolved I-band', color='w')\ncbar2 = fig.colorbar(im2, ax=ax[1][1], pad=0.02)\nplt.show()\nprint(oop)\n#xx = optimize.fsolve(vfit, args=(dat_psfi, dat_psfH), x0=[143.4, 2])\n#print(xx, vfit(xx, dat_psfi, dat_psfH))\n\n# print(oop)\nprint(np.nanmax(dat_psfi), np.nanmax(dat_psfH)) # 0.001129155 0.05456335\nssp_n = ndimage.gaussian_filter(dat_psfi, [1.2, 1.2]) # convolve with kernel!\nplt.imshow(ssp_n - dat_psfi, origin='lower')\nplt.colorbar()\nplt.show()\nprint(np.nansum(dat_psfi - dat_psfH)) # -0.980911\nprint(np.nansum(ssp_n - dat_psfi)) # 1.1641532e-10\nprint(np.nansum(ssp_n - dat_psfH)) # -0.9809109\nprint(oops)\n\n\nprint(oops)\n\nsolveit = optimize.fsolve(fitconvolve, args=(dat_psfi, dat_psfH), x0=[1.2, 1.2])\nprint(solveit, [diff_sigma_nx, diff_sigma_ny], 'solution, initial guess')\nprint(time.time()-t0, 'time!')\nprint(fitconvolve(solveit, dat_psfi, dat_psfH), 'should be 0 -- did solution work?')\nprint(oops)\n\n\n# METHOD 1\n# calculate sigmas from 2D gaussians\ngp = do_2dgaussfit(dat_pgc_psfcen_f814w[1500:1700, 1500:1700]) # [1.04957099e-03 1.64647665e+03 1.58224407e+03 8.65402658e-01 8.51768218e-01]\ngn = do_2dgaussfit(dat_ngc_psfcen_f814w[1820:2020, 1800:2020]) # [1.10704459e-03 1.92214472e+03 1.92717995e+03 8.18216509e-01 8.47028032e-01]\ngH = do_2dgaussfit(dat_psfH) # [ 0.04847133 40.03064685 39.91339118 1.45843277 1.49161195]\n\n#p_fwhm = np.mean([p_fwhm_x, p_fwhm_y])\n#n_fwhm = np.mean([n_fwhm_x, n_fwhm_y])\n#H_fwhm = np.mean([H_fwhm_x, H_fwhm_y])\n\ndiff_sigma_px = np.sqrt(gH[3]**2 - gp[3]**2) # diff in quadrature! # 1.2072894820619162\ndiff_sigma_py = np.sqrt(gH[4]**2 - gp[4]**2) # diff in quadrature! # 1.2277824434215172\ndiff_sigma_nx = np.sqrt(gH[3]**2 - gn[3]**2) # diff in quadrature! # 1.1739269102067171\ndiff_sigma_ny = np.sqrt(gH[4]**2 - gn[4]**2) # diff in quadrature! # 1.2244987215858145\nprint(diff_sigma_nx)\nprint(diff_sigma_ny)\nprint(diff_sigma_px)\nprint(diff_sigma_py)\n\ntn = time.time()\nssp_n = ndimage.gaussian_filter(dat_ngc_psfcen_f814w, [diff_sigma_nx, diff_sigma_ny]) # convolve with kernel!\ngal_n = ndimage.gaussian_filter(dat_nI, [diff_sigma_nx, diff_sigma_ny]) # convolve with kernel!\nt1 = time.time()\nprint('time in gaussian filter', t1 - tn)\nssp_p = ndimage.gaussian_filter(dat_pgc_psfcen_f814w, [diff_sigma_px, diff_sigma_py]) # convolve with kernel!\ngal_p = ndimage.gaussian_filter(dat_pI, [diff_sigma_px, diff_sigma_py]) # convolve with kernel!\nprint('time in gaussian filter', time.time() - t1)\ngn2 = do_2dgaussfit(ssp_n[1820:2020, 1800:2020]) # [1.04957099e-03 1.64647665e+03 1.58224407e+03 8.65402658e-01 8.51768218e-01]\ngp2 = do_2dgaussfit(ssp_p[1500:1700, 1500:1700]) # [1.04957099e-03 1.64647665e+03 1.58224407e+03 8.65402658e-01 8.51768218e-01]\ngn = do_2dgaussfit(dat_ngc_psfcen_f814w[1820:2020, 1800:2020]) # [1.04957099e-03 1.64647665e+03 1.58224407e+03 8.65402658e-01 8.51768218e-01]\ngp = do_2dgaussfit(dat_pgc_psfcen_f814w[1500:1700, 1500:1700])\n# print(gn2)\n# print(gp2)\n# print(gn)\n# print(gp)\nprint(gH)\nplt.imshow(gal_n[1820:2020, 1830:2030], origin='lower', vmax=150.)\nplt.colorbar()\nplt.show()\nplt.imshow(dat_nI[1820:2020, 1830:2030], origin='lower', vmax=150.)\nplt.colorbar()\nplt.show()\nplt.imshow(gal_p[1550:1750, 1500:1700], origin='lower', vmax=90.)\nplt.colorbar()\nplt.show()\nplt.imshow(dat_pI[1550:1750, 1500:1700], origin='lower', vmax=90.)\nplt.colorbar()\nplt.show()\nprint(oops)\n\n\n''' # NGC 384 FIND CENTERS\nplt.imshow(dat_n5, origin='lower', vmax=6700, vmin=0.)\nplt.colorbar()\nplt.plot(1994, 154, 'm*') # max\nplt.plot(1994.5, 153.8, 'w*') # 2D gauss\nplt.plot(1994.4, 153.2, 'c*') # centroid\nplt.show()\nplt.imshow(dat_nl, origin='lower', vmax=14000, vmin=0.)\nplt.colorbar()\nplt.plot(2039, 199, 'm*')\nplt.plot(2039.9, 198.9, 'w*')\nplt.plot(2039.5, 198.4, 'c*')\nplt.show()\nplt.imshow(dat_no, origin='lower', vmax=9900, vmin=0.)\nplt.colorbar()\nplt.plot(2084, 244, 'm*')\nplt.plot(2110.6, 253.9, 'w*')\nplt.plot(2084.8, 243.8, 'c*')\nplt.show()\nprint(oop)\n\nfind_center(dat_n5, 1950, 100, 7000.)\n# maxloc: [54, 44] # this is [y x]! -> [1994 154] n5\n# 2D gauss: 4.44897434e+01 5.37789283e+01 [1994.5, 153.8] n5\n# cen: 44.041795233578284 53.24022886329969 [1994.4, 153.2] n5\n\nfind_center(dat_nl, 2000, 150, 14000.)\n# maxloc: [49, 39] -> [2039 199] nl\n# 2D gauss: 3.98992626e+01 4.89351953e+01 [2039.9, 198.9] nl\n# cen: 39.50042823306298 48.44560475888629 [2039.5, 198.4] nl\n#print(oop)\n\nfind_center(dat_no, 2050, 200, 9900.)\n# maxloc [44, 34] no -> [2084 244]\n# 2D gauss: 6.05688644e+01 5.38515316e+01 [2110.6, 253.9] no\n# cen: 34.777073215971605 43.77436076055096 [2084.8, 243.8] no\nprint(oop)\n# ''' #\n\n# FROM HERE NGC 384 I-BAND PSFs\n# 2005.8, 199.7 (for rmq?) atv aperture photometry!\npsf_5 = np.zeros(shape=dat_n5.shape) # rmq -> pattstep = 0, no pattern, no dither. Just center it over galaxy!\npsf_l = np.zeros(shape=dat_nl.shape) # rxq -> pattstep = 1, pattern1=LINE (0,0) [must be 0,0, since step=2 exists]\npsf_o = np.zeros(shape=dat_no.shape) # rzq -> pattstep = 2, pattern1=LINE (2.5, 2.5)\n\n\n# BEGIN JONELLE STYLE\n# BASED ON MAX PIXELS\nnxctr_5,nyctr_5 = 1994,154\nnxctr_l,nyctr_l = 2039,199\nnxctr_o,nyctr_o = 2084,244\n\n# dat_psfm, *psfx, *psfz all centered at 44,44\n# PUT 44,44 at galaxy center!!\npsf_5[nyctr_5-44:nyctr_5+45, nxctr_5-44:nxctr_5+45] = dat_psf5 # correct!!!!!!\npsf_l[nyctr_l-44:nyctr_l+45, nxctr_l-44:nxctr_l+45] = dat_psfl # correct!!!!!!\npsf_o[nyctr_o-44:nyctr_o+45, nxctr_o-44:nxctr_o+45] = dat_psfo # correct!!!!!!\n\n\n# BEGIN HYBRID & BEN STYLE!!!!\n# cen: 44.041795233578284 53.24022886329969 [1994.4, 153.2] n5\n# cen: 39.50042823306298 48.44560475888629 [2039.5, 198.4] nl\n# cen: 34.777073215971605 43.77436076055096 [2084.8, 243.8] no\n# BASED ON CENTROIDS (USE FOR BOTH CENTROID/HYBRID STYLE AND BEN STYLE)\nnxctr_5,nyctr_5 = 1994.041795233578284,153.24022886329969\nnxctr_l,nyctr_l = 2039.50042823306298,198.44560475888629\nnxctr_o,nyctr_o = 2084.777073215971605,243.77436076055096\n","sub_path":"psfhomog.py","file_name":"psfhomog.py","file_ext":"py","file_size_in_byte":33199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"564587735","text":"\"\"\"Common functions used in scripts.\"\"\"\n\n\ndef extract_label(line):\n \"\"\"Return the \\\\label on the given line\"\"\"\n start = line.find('\\\\label{')\n for i in range(start, len(line)):\n if line[i] == '}':\n label = line[start + 7 : i]\n break\n return label\n\ndef extract_ref(line, refType):\n \"\"\"Return the \\\\ref or \\\\eqref or \\\\eref on the given line\"\"\"\n target = '\\\\' + refType + '{'\n\n start = line.find(target)\n for i in range(start, len(line)):\n if line[i] == '}':\n ref = line[start + len(target) : i]\n break\n return ref\n\ndef get_chapters():\n \"\"\"Retrieves all chapter names and their corresponding .tex files.\"\"\"\n chapsfile = open('chapters', 'r')\n chapters = [name.rstrip() for name in chapsfile.readlines()]\n chapters_noext = [chapter.split('.')[0] for chapter in chapters]\n chapsfile.close()\n\n return chapters_noext, chapters\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"484255331","text":"'''\r\npy4e, Chapter 5, Exercise 2: Write another program that prompts for a list of\r\nnumbers as above and at the end prints out both the maximum and minimum of the\r\nnumbers instead of the average.\r\n\r\nWilliam Kerley, 21.02.20\r\n'''\r\n\r\n\r\nn = 0 #intialize variables\r\nsum = 0\r\ncount = 0\r\nmax = 0\r\nmin = 0\r\n\r\nwhile True:\r\n n = input(\"Enter a number: \")\r\n if n == 'done':\r\n break #exists loop if done\r\n\r\n try:\r\n n = float(n) #checks for numeric input\r\n if count == 0: #defines min and max for first entry\r\n max = n\r\n min = n\r\n count = count + 1 #counter\r\n sum = sum + n #sum\r\n if n > max:\r\n max = n #check for maximum\r\n if n < min:\r\n min = n #check for minimum\r\n except:\r\n print(\"Invalid input\")\r\n\r\nprint(sum, count, max, min)\r\n","sub_path":"ex5_2.py","file_name":"ex5_2.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"403725590","text":"#!/usr/bin/env python36\n# -*- coding: utf-8 -*-\n\n######################################################\n# Adapted from CRIPAC-DIG/SR-GNN for fair comparison #\n######################################################\n\nimport datetime\nimport math\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.nn import Module, Parameter\nimport torch.nn.functional as F\n# from torch.nn import TransformerEncoder\n# from torch.nn import TransformerEncoderLayer\nfrom nfnets.agc import AGC\nfrom conformer import ConformerEncoder\n\n\n# class Conformer(nn.Module):\n# def __init__(self, dim, depth,\n# heads, dim_head,\n# dropout, kernel_size=31,\n# causal=False):\n# self.layers = nn.ModuleList([])\n\n# for _ in range(depth):\n# self.layers.append(ConformerBlock())\n \n# def forward(self, x):\n# for layer in self.layers:\n# x = layer(x) + x\n\n# return x\n\n\n# class ConformerEncoder(nn.Module):\n# def __init__(self, *, num_tokens, num_classes, dim, depth, heads, dim_head=64, dropout=0., emb_dropout=0., kernel_size=31, causal=False):\n# super().__init__()\n\n# self.item_embed = nn.Embedding(num_tokens, dim)\n# self.pos_emb = FixedPositionalEmbedding(dim)\n# self.cls_token = nn.Parameter(torch.randn(1, 1, dim))\n# self.dropout = nn.Dropout(emb_dropout)\n\n# self.transformer = Conformer(\n# dim, depth, heads, dim_head, dropout, kernel_size, causal)\n\n# self.mlp = nn.Sequential(\n# nn.LayerNorm(dim),\n# nn.Linear(dim, dim // 2),\n# nn.ELU(inplace=True),\n# nn.Linear(dim // 2, dim),\n# )\n\n# def forward(self, x, mask=None):\n\n# b, n = x.shape\n# pos_emb = self.pos_emb(x)\n# x = pos_emb + self.item_embed(x)\n \n\n# cls_tokens = repeat(self.cls_token, '() n d -> b n d', b=b)\n# x = torch.cat((cls_tokens, x), dim=1)\n# x = self.dropout(x)\n\n# x = self.transformer(x, mask)\n# x = x.mean(dim=1)\n# decoder_out = self.mlp(x)\n# return decoder_out\n\n\n\nclass SelfAttentionNetwork(Module):\n def __init__(self, opt, n_node):\n super(SelfAttentionNetwork, self).__init__()\n self.hidden_size = opt.hiddenSize\n self.n_node = n_node\n self.batch_size = opt.batchSize\n # self.embedding = nn.Embedding(self.n_node, self.hidden_size)\n # self.transformerEncoderLayer = TransformerEncoderLayer(d_model=self.hidden_size, nhead=opt.nhead,dim_feedforward=self.hidden_size * opt.feedforward)\n # self.transformerEncoder = TransformerEncoder(self.transformerEncoderLayer, opt.layer)\n # print(self.n_node)\n self.transformerEncoder = ConformerEncoder(\n input_dim = self.n_node,\n encoder_dim = 128,\n num_layers = opt.layer, \n num_attention_heads = opt.nhead,\n input_dropout_p = 0.1,\n feed_forward_dropout_p = 0.1,\n attention_dropout_p = 0.1,\n conv_dropout_p = 0.1,\n\n )\n # self.final_linear = nn.Linear(64, 1)\n self.loss_function = nn.CrossEntropyLoss()\n self.optimizer = torch.optim.Adam(self.parameters(), lr=opt.lr, weight_decay=opt.l2)\n self.AGC_optim = AGC(self.parameters(), self.optimizer)\n self.scheduler = torch.optim.lr_scheduler.StepLR(self.optimizer, step_size=opt.lr_dc_step, gamma=opt.lr_dc)\n self.reset_parameters()\n\n def reset_parameters(self):\n stdv = 1.0 / math.sqrt(self.hidden_size)\n for weight in self.parameters():\n weight.data.uniform_(-stdv, stdv)\n\n # def compute_scores(self, hidden, mask):\n # ht = hidden[torch.arange(mask.shape[0]).long(), torch.sum(mask, 1) - 1] # batch_size x latent_size\n # b = self.embedding.weight[1:] # n_nodes x latent_size\n # scores = torch.matmul(ht, b.transpose(1, 0))\n # return scores\n\n # def forward(self, inputs, A):\n # hidden = self.embedding(inputs)\n # hidden = hidden.transpose(0,1).contiguous()\n # hidden = self.transformerEncoder(hidden)\n # hidden = hidden.transpose(0,1).contiguous()\n # return hidden\n\n def forward(self, inputs):\n # print(inputs.size())\n hidden = self.transformerEncoder(inputs)\n # hidden = hidden.transpose(0,1).contiguous()\n # print(hidden.size())\n hidden = torch.matmul(hidden, self.transformerEncoder.item_embed.weight[1:].transpose(1, 0)) # weight tying\n # hidden = self.final_linear(hidden)\n # hidden = torch.squeeze(hidden, -1)\n # print(hidden.size())\n\n return hidden\n\n\ndef trans_to_cuda(variable):\n if torch.cuda.is_available():\n return variable.cuda()\n else:\n return variable\n\n\ndef trans_to_cpu(variable):\n if torch.cuda.is_available():\n return variable.cpu()\n else:\n return variable\n\n\ndef forward(model, i, data):\n alias_inputs, A, items, mask, targets = data.get_slice(i)\n # alias_inputs = trans_to_cuda(torch.Tensor(alias_inputs).long())\n # print(len(targets))\n items = trans_to_cuda(torch.Tensor(items).long())\n # A = trans_to_cuda(torch.Tensor(A).float())\n mask = trans_to_cuda(torch.Tensor(mask).long())\n hidden = model(items)\n hidden = hidden.mean(dim=1)\n # get = lambda i: hidden[i][alias_inputs[i]]\n # seq_hidden = torch.stack([get(i) for i in torch.arange(len(alias_inputs)).long()])\n return targets, hidden # model.compute_scores(seq_hidden, mask)\n\n\ndef train_test(model, train_data, test_data): \n print('start training: ', datetime.datetime.now())\n model.train()\n total_loss = 0.0\n slices = train_data.generate_batch(model.batch_size)\n for i, j in zip(slices, np.arange(len(slices))):\n model.optimizer.zero_grad()\n targets, scores = forward(model, i, train_data)\n targets = trans_to_cuda(torch.Tensor(targets).long())\n loss = model.loss_function(scores, targets - 1)\n loss.backward()\n model.AGC_optim.step()\n total_loss += loss\n if j % int(len(slices) / 5 + 1) == 0:\n print('[%d/%d] Loss: %.4f' % (j, len(slices), loss.item()))\n print('\\tLoss:\\t%.3f' % total_loss)\n\n print('start predicting: ', datetime.datetime.now())\n model.eval()\n hit, mrr = [], []\n slices = test_data.generate_batch(model.batch_size)\n for i in slices:\n targets, scores = forward(model, i, test_data)\n sub_scores = scores.topk(20)[1]\n sub_scores = trans_to_cpu(sub_scores).detach().numpy()\n for score, target, mask in zip(sub_scores, targets, test_data.mask):\n hit.append(np.isin(target - 1, score))\n if len(np.where(score == target - 1)[0]) == 0:\n mrr.append(0)\n else:\n mrr.append(1 / (np.where(score == target - 1)[0][0] + 1))\n hit = np.mean(hit) * 100\n mrr = np.mean(mrr) * 100\n model.scheduler.step()\n return hit, mrr","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"107741123","text":"# iotest1.py Test PR #3836. User class write() performs unbuffered writing.\n\nimport io, pyb\nimport uasyncio as asyncio\nimport micropython\nmicropython.alloc_emergency_exception_buf(100)\n\nMP_STREAM_POLL_RD = const(1)\nMP_STREAM_POLL_WR = const(4)\nMP_STREAM_POLL = const(3)\nMP_STREAM_ERROR = const(-1)\n\ndef printbuf(this_io):\n print(bytes(this_io.wbuf[:this_io.wprint_len]).decode(), end='')\n\nclass MyIO(io.IOBase):\n def __init__(self):\n self.ready_rd = False\n self.ready_wr = False\n self.wbuf = bytearray(100) # Write buffer\n self.wprint_len = 0\n self.widx = 0\n self.wch = b''\n self.rbuf = b'ready\\n' # Read buffer\n pyb.Timer(4, freq = 1, callback = self.do_input)\n pyb.Timer(5, freq = 10, callback = self.do_output)\n\n # Read callback: emulate asynchronous input from hardware.\n # Typically would put bytes into a ring buffer and set .ready_rd.\n def do_input(self, t):\n self.ready_rd = True # Data is ready to read\n\n # Write timer callback. Emulate hardware: if there's data in the buffer\n # write some or all of it\n def do_output(self, t):\n if self.wch:\n self.wbuf[self.widx] = self.wch\n self.widx += 1\n if self.wch == ord('\\n'):\n self.wprint_len = self.widx # Save for schedule\n micropython.schedule(printbuf, self)\n self.widx = 0\n self.wch = b''\n\n\n def ioctl(self, req, arg): # see ports/stm32/uart.c\n ret = MP_STREAM_ERROR\n if req == MP_STREAM_POLL:\n ret = 0\n if arg & MP_STREAM_POLL_RD:\n if self.ready_rd:\n ret |= MP_STREAM_POLL_RD\n if arg & MP_STREAM_POLL_WR:\n if not self.wch:\n ret |= MP_STREAM_POLL_WR # Ready if no char pending\n return ret\n\n def readline(self):\n self.ready_rd = False\n return self.rbuf\n\n def write(self, buf, off, sz):\n self.wch = buf[off] # A real driver would trigger hardware to write a char\n return 1 # No. of bytes written. uasyncio waits on ioctl write ready\n\nmyio = MyIO()\n\nasync def receiver():\n sreader = asyncio.StreamReader(myio)\n while True:\n res = await sreader.readline()\n print('Received', res)\n\nasync def sender():\n swriter = asyncio.StreamWriter(myio, {})\n await asyncio.sleep(5)\n count = 0\n while True:\n count += 1\n tosend = 'Wrote Hello MyIO {}\\n'.format(count)\n await swriter.awrite(tosend.encode('UTF8'))\n # Once this has occurred reading stops. ioctl keeps being called with arg == 0\n # which normally occurs once only after a read\n # IOWriteDone is never yielded: is this right?\n await asyncio.sleep(2)\n\n\nloop = asyncio.get_event_loop()\nloop.create_task(receiver())\nloop.create_task(sender())\nloop.run_forever()\n\n","sub_path":"uasyncio_iostream/tests/iotest1.py","file_name":"iotest1.py","file_ext":"py","file_size_in_byte":2893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"52048873","text":"from tkinter import Frame, Tk, Menu\n\n\ndef color_r():\n frame.config(bg=\"Red\")\n\n\ndef color_g():\n frame.config(bg=\"Green\")\n\n\ndef color_b():\n frame.config(bg=\"Blue\")\n\n\ndef square():\n frame.config(width=500)\n frame.config(height=500)\n\n\ndef rectangle():\n frame.config(width=700)\n frame.config(height=400)\n\n\nif __name__ == '__main__':\n root = Tk()\n\n frame = Frame(root, width=300, height=100, bg=\"Black\")\n frame.pack()\n\n root_menu = Menu(root)\n root.config(menu=root_menu)\n\n menu1 = Menu(root_menu)\n root_menu.add_cascade(label=\"Color\", menu=menu1)\n menu1.add_command(label=\"Red\", command=color_r)\n menu1.add_command(label=\"Green\", command=color_g)\n menu1.add_command(label=\"Blue\", command=color_b)\n\n menu2 = Menu(root_menu)\n root_menu.add_cascade(label=\"Size\", menu=menu2)\n menu2.add_command(label=\"500x500\", command=square)\n menu2.add_command(label=\"700x400\", command=rectangle)\n\n root.mainloop()\n","sub_path":"tkinter/pracrical_work/practical_work_6.py","file_name":"practical_work_6.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"588358165","text":"from time import sleep; from sys import stdout; import random; import pickle; import datetime; import os\r\n\r\nsz = os.get_terminal_size()\r\ndef clear():\r\n\tos.system('cls' if os.name=='nt' else 'clear')\r\n\ttitle = \"Welcome To Blood Rising\"\r\n\tprint(title)\r\nplayer = {}\r\nsaves = [player]\r\nMenu_list = [{\"Saves\":[{\"Test\":\"Test\"}]},{\"New Game\":\"\"},{\"Settings\":[]}]\r\n\r\ndef SlowPrint(text,speed=.03):\r\n\tfor letter in text:\r\n\t\tstdout.write(letter)\r\n\t\tstdout.flush()\r\n\t\tsleep(speed)\r\n\tstdout.write(\"\\n\")\r\n\t\t\r\nclass Menu():\r\n\tdef __init__(self, saves):\r\n\t\tself.saves = saves\r\n\t\r\n\tdef menu(self, menu_list):\r\n\t\tclear()\r\n\t\tfor i in menu_list:\r\n\t\t\tprint(('('+str(menu_list.index(i)+1)+')-'+str(list(i.keys())[0])))\r\n\t\t\tsleep(.1)\r\n\t\tinput_str = input(\">>> \")\r\n\t\tprint([list(menu_list[i-1].keys())[0].lower() for i in len(menu_list)])\r\n\t\tif input_str.isdigit() and 0 < int(input_str) <= len(menu_list):\r\n\t\t\tmenu_index = int(input_str)-1\r\n\t\telif input_str.lower() in [list(menu_list[i].keys())[0].lower() for i in menu_list]:\r\n\t\t\t#menu_index = [list(menu_list[i].keys())[0].lower() for i in menu_list].index(input_str.lower())\r\n\t\t\tprint(\"Test\")\r\n\t\telse:\r\n\t\t\tmain_menu.menu(menu_list)\r\n\t\tif menu_index and type(list(menu_list[menu_index].values())[0]) is list:\r\n\t\t\tmain_menu.menu(list(menu_list[int(input_str)-1].values())[0])\r\n\r\nmain_menu = Menu(saves)\r\nwhile True:\r\n\tmain_menu.menu(Menu_list)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"490021180","text":"from flask import Flask, request\nfrom flask_cors import CORS\nimport tensorflow as tf\nimport numpy as np\nimport cv2\nimport pickle\nimport requests\n\napp = Flask(__name__)\nCORS(app)\n\nROBOT_URL = 'http://192.168.1.197:5010'\nmodel = tf.keras.models.load_model('models/model_esquerda.h5')\n\n@app.route('/get_direction', methods=['POST'])\ndef get_direction():\n data = request.json\n\n frame = np.array(data['frame'],dtype=np.uint8)\n print(frame.shape)\n frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n frame = frame[tf.newaxis,...,tf.newaxis] / 255.0\n \n direction = model.predict(frame)\n print(direction)\n direction = np.argmax(direction)\n if direction == 0:\n requests.get(ROBOT_URL + '/left_side')\n elif direction == 1:\n requests.get(ROBOT_URL + '/up_side')\n \n return 'OK'\n\n\nif __name__ == \"__main__\":\n print (\"Start\")\n app.run(host='0.0.0.0',port=5010)","sub_path":"app_model.py","file_name":"app_model.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"281559056","text":"from selenium import webdriver\nimport pandas as pd\n\ntest = []\n\n\n# driver = webdriver.PhantomJS(\"E:\\\\projects\\\\comparator\\comparator\\\\phantomjs.exe\")\n\ndef process(row):\n #driver = webdriver.PhantomJS(\"E:\\\\projects\\\\others\\\\comparator\\\\comparator\\\\phantomjs.exe\")\n driver = webdriver.Chrome(\"D:\\\\softwares\\\\chromedriver_win32\\\\chromedriver.exe\")\n matches = str(row['url'])\n # print(matches)\n driver.get(matches)\n df = driver.find_element_by_class_name(\"breadcrumbs\").text\n test.append(df)\n print(df)\n driver.close()\n\n\n# print(df)\n# driver.find_element_by_link_text(\"Clear cache\").click()\n\n\nif __name__ == '__main__':\n\n\n b = pd.read_csv(\"E:\\\\projects\\\\QA\\Migration\\\\Uro Turing\\\\select_your_car\\\\scraping.csv\")\n b.apply(process, 1)\n pd.DataFrame(data=test, columns=['title']).to_csv(\"E:\\\\projects\\\\QA\\Migration\\\\Uro Turing\\\\select_your_car\\\\scraped_data.csv\")\n","sub_path":"seliniumsamplenew.py","file_name":"seliniumsamplenew.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"239755318","text":"import multiprocessing\nimport pickle\nimport numpy as np\nimport time\n\nfrom context import temp_files_path\n\nfrom functions import n_grams_counters_list\n\nexecution_params = pickle.load(open(temp_files_path+\"execution_params.p\", \"rb\" ))\nN_PROCS = execution_params['N_PROCS']\nN_GRAM = execution_params['N_GRAM']\ntokenized_text = execution_params['tokenized_text']\n\nif __name__ == '__main__':\n print(\"Multiprocessing\")\n #We are going to execute a multiprocessing and split the list in as many parts than processors used :\n #DataFrame splitting :\n L_sub_lists = np.array_split(tokenized_text, N_PROCS)\n final_List = []\n start_time = time.time()\n\n print('Creating pool with %d processes\\n' % N_PROCS)\n with multiprocessing.Pool(N_PROCS) as pool:\n # We initialize a list of tasks which each call the same function, but\n #with a diffrent list\n TASKS = [(sub_list, N_GRAM) for sub_list in L_sub_lists]\n print(\"TASK ready\")\n results = [pool.apply_async(n_grams_counters_list, t) for t in TASKS]\n print(\"results ready\")\n final_results = [r.get() for r in results]\n print(\"final_results ready\")\n print(\"appending sub lists :\")\n\n for sub_list_res in final_results:\n if len(sub_list_res)>0:\n final_List+=list(sub_list_res)\n print(\"success\")\n\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n print('the result file is available at : \\n temp_files_path+\"tokenized_text_without_stopwords.p\"')\n pickle.dump(final_List,open(temp_files_path+\"L_n_grams_counters.p\", \"wb\"))\n","sub_path":"multiprocessing_n_grams_counters_list.py","file_name":"multiprocessing_n_grams_counters_list.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"31659657","text":"# 数据处理\r\nimport os\r\nimport sys\r\nimport time\r\n\r\n'''\r\n制作index字典\r\n'''\r\ndef read_index_file(file_path):\r\n type_dict = {\"spam\":\"1\", \"ham\":\"0\"}\r\n index_file = open(file_path)\r\n index_dict = {}\r\n try:\r\n # next(index_file)\r\n for line in index_file:\r\n arr = line.split(\" \")\r\n if len(arr) == 2:\r\n key, value = arr\r\n \r\n value = value.replace(\"../data\",\"\").replace(\"\\n\",\"\")\r\n index_dict[value] = type_dict[key.lower()]\r\n finally:\r\n index_file.close()\r\n\r\n return index_dict\r\n\r\n'''\r\n读取邮件内容\r\n'''\r\ndef read_file(file_path):\r\n # 读操作,邮件数据编码为\"gb2312\",数据读取有异常就ignore忽略\r\n\r\n file = open(file_path,\"r\",encoding=\"gb2312\",errors=\"ignore\")\r\n\r\n content_dict = {}\r\n\r\n try:\r\n is_content = False\r\n \r\n for line in file: # 按行读取\r\n line = line.strip() # 每行的空格去掉用strip()\r\n if line.startswith(\"From:\"):\r\n content_dict[\"from\"] = line[5:]\r\n elif line.startswith(\"To:\"):\r\n content_dict[\"to\"] = line[3:]\r\n elif line.startswith(\"Date:\"):\r\n content_dict[\"data\"] = line[5:]\r\n elif not line:\r\n # 邮件内容与上面信息存在着第一个空行,遇到空行时,\r\n # 这里标记为True以便进行下面的邮件内容处理\r\n # line文件的行为空时是False,不为空时是True\r\n is_content = True\r\n \r\n # 处理邮件内容(处理到为空的行时接着处理邮件的内容)\r\n if is_content:\r\n if \"content\" in content_dict:\r\n content_dict[\"content\"] += line\r\n else:\r\n content_dict[\"content\"] = line\r\n finally:\r\n file.close()\r\n \r\n return content_dict\r\n\r\n'''\r\n邮件数据处理(内容的拼接、并用后台进行分割)\r\n'''\r\ndef process_file(file_path):\r\n content_dict = read_file(file_path)\r\n\r\n #进行处理(拼接),get()函数返回指定键的值,指定键的值不存在用指定的默认值unkown代替\r\n result_str = content_dict.get(\"from\",\"unkown\").replace(\",\",\"\").strip()+\",\"\r\n result_str += content_dict.get(\"to\",\"unkown\").replace(\",\",\"\").strip()+\",\"\r\n result_str += content_dict.get(\"data\",\"unkown\").replace(\",\",\"\").strip()+\",\"\r\n result_str += content_dict.get(\"content\",\"unkown\").replace(\",\",\"\").strip()\r\n\r\n return result_str\r\n\r\n# 开始进行数据处理 函数调用\r\nstart_time = time.time()\r\nindex_dict = read_index_file(r'../../trec06p/full/index') #制作标签字典\r\nlist0 = os.listdir(r'D:\\python\\trec06c\\data') #文件夹的名称\r\n\r\nfor l1 in list0:\r\n l1_path = os.path.join(r'D:\\python\\trec06c\\data',l1)\r\n print(\"开始处理文件夹\"+l1_path)\r\n list1 = os.listdir(l1_path)\r\n\r\n write_file_path = r'D:\\python\\trec06c\\process01_'+l1\r\n \r\n with open(write_file_path, \"w\", encoding=\"utf-8\") as writer:\r\n for l2 in list1:\r\n l2_path = l1_path + \"/\" + l2 # l2_path ../data/data/215/000\r\n # 得到具体的文件内容后,进行文件数据的读取\r\n index_key = \"/\" + l1 + \"/\" + l2 # index_key: /215/000\r\n if index_key in index_dict:\r\n # 读取数据\r\n content_str = process_file(l2_path)\r\n # 添加分类标签(0、1)也用逗号隔开\r\n content_str += \",\" + index_dict[index_key] + \"\\n\"\r\n # 进行数据输出\r\n writer.writelines(content_str)\r\n\r\n\r\n# 在合并所有第一次构建好的内容\r\nwith open(r'D:\\python\\trec06c\\result_process01', 'w', encoding='utf-8') as writer:\r\n for l1 in list0:\r\n file_path = r'D:\\python\\trec06c\\process01_' + l1 \r\n print(\"开始合并文件\" + file_path)\r\n\r\n with open(file_path, encoding='utf-8') as file:\r\n for line in file:\r\n writer.writelines(line)\r\n\r\nend_time = time.time() \r\nprint('time:{:.2f}'.format(end_time-start_time))\r\n\r\n\r\n\r\n\r\n\r\n \r\n\r\n# 中间测试代码\r\n# index_dict = read_index_file(\"../../trec06p/full/index\")\r\n# content_dict = read_file(r'D:\\python\\trec06c\\data\\001\\000')\r\n# print(content_dict)\r\n# print(index_dict)\r\n# sys.exit(\"第25行\")\r\n# file_dir = r'D:\\python\\email\\train\\Data'\r\n# for i in os.listdir(file_dir):\r\n# print(len(os.listdir(os.path.join(file_dir, i))))","sub_path":"spamtrack/code/dataProcess.py","file_name":"dataProcess.py","file_ext":"py","file_size_in_byte":4488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"608538126","text":"class Interval(object):\n def __init__(self, start, end):\n self.start = start\n self.end = end\n\nclass Solution:\n \"\"\"\n @param intervals: interval list.\n @return: A new interval list.\n \"\"\"\n def merge(self, intervals):\n if not intervals:\n return []\n\n intervals = sorted(intervals, key=lambda x: x.start)\n results = []\n left, right = intervals[0].start, intervals[0].end\n for interval in intervals:\n if right < interval.start:\n results.append(Interval(left, right))\n left, right = interval.start, interval.end\n continue\n\n right = max(right, interval.end)\n results.append(Interval(left, right))\n return results\n","sub_path":"Databricks/doc16. Merge Interval.py","file_name":"doc16. Merge Interval.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"417781526","text":"from io import BytesIO\n\nfrom django.core.files.uploadedfile import InMemoryUploadedFile\nfrom PIL import Image as PILImage\nfrom rest_framework import serializers\n\n\nfrom image.models import Image\n\n\nclass ImageSerializer(serializers.ModelSerializer):\n create_time = serializers.ReadOnlyField()\n width = serializers.IntegerField(read_only=True)\n height = serializers.IntegerField(read_only=True)\n\n class Meta:\n model = Image\n fields = ('id', 'create_time', 'image', 'width', 'height')\n\n def create(self, validated_data):\n if validated_data['image'].name.endswith('.tif') or validated_data['image'].name.endswith('.tiff'):\n image = PILImage.open(validated_data['image'])\n out = image.convert(\"RGB\")\n bytes = BytesIO()\n out.save(bytes, format=\"jpeg\")\n validated_data['image'] = InMemoryUploadedFile(bytes, None, 'test.jpeg', 'image/jpeg', None, None)\n\n return super(ImageSerializer, self).create(validated_data)\n","sub_path":"api/image/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"46170346","text":"# -*- coding:utf-8 -*-\n# create_time: 2018/11/28 22:16\n# __author__ = 'brad'\n\nimport gevent\nfrom gevent.queue import Queue\n\ntasks = Queue(maxsize=24)\n\n\ndef worker(n):\n while not tasks.empty():\n task = tasks.get()\n print('Worker %s got task %s' % (n, task))\n gevent.sleep(0)\n\n print('Quitting time!')\n\n\ndef boss():\n for i in range(1, 25):\n tasks.put_nowait(i)\n # tasks.put(i)\n gevent.sleep(0)\n print('put', i)\n\n\ngevent.spawn(boss).join()\n\ngevent.joinall([\n gevent.spawn(boss),\n gevent.spawn(worker, 'steve'),\n gevent.spawn(worker, 'john'),\n gevent.spawn(worker, 'nancy'),\n])\n","sub_path":"coroutine-GeneratorFunc-asynchronusGeneratorFunc/corroutine-gevent/queue_nowait.py","file_name":"queue_nowait.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"25706020","text":"# coding=utf-8\nimport xlrd\nimport xlwt\nfrom xlutils import copy\n'''\nkwb=xlrd.open_workbook(\"E:/123.xls\")\nsheet=kwb.sheets()[0]\nprint (kwb.sheet_names())\nprint (sheet.nrows)\nprint (sheet.ncols)\nprint (sheet.row_values(0))\nprint (sheet.col_values(0))\nprint (sheet.cell_value(one,one))\n\nkwb=xlwt.Workbook()\nsheet=kwb.add_sheet(\"Sheet one\",cell_overwrite_ok=True)\nsheet.write(2,0,'zyw1')\nsheet.write(2,one,19980706)\nkwb.save('E:/123.xls')\n\nkwb=xlrd.open_workbook('E:/123.xls')\nkwb1=copy.copy(kwb)\nsheet=kwb1.get_sheet(0)\nsheet.write(one,0,'bbb')\nsheet.write(one,one,456)\nsheet.write(2,0,'ccc')\nsheet.write(2,one,789)\nkwb1.save('E:/123.xls')\n'''\n\nlist=['tom','p','uu']\nrelist=['Caronline','one','p']\npath='C:/Python3.6/123.xls'\n\nkwb=xlrd.open_workbook(path)\nr_sheet=kwb.sheets()[0] #读sheet\nkwb1=copy.copy(kwb)\nw_sheet=kwb1.get_sheet(0) #写sheet\nfor i in range(r_sheet.nrows):\n n = 0\n L=r_sheet.row_values(i)\n for j in L:\n j=str(j)\n for k in range(len(list)):\n if list[k] in j:\n s=j.replace(list[k],relist[k])\n w_sheet.write(i,n,s)\n n+=1\nkwb1.save(path)\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","sub_path":"wenjian/practice/one/excle.py","file_name":"excle.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"412478419","text":"import matplotlib.pyplot as plt\n\n\n# Fonctions\ndef indiceMin(liste):\n min = liste[0]\n iMin = 0\n comp = 0\n for elem in liste:\n if elem < min:\n min = elem\n iMin = comp\n comp += 1\n return iMin\n\n\ndef totalAcc(liste):\n sum = 0\n for elem in liste:\n sum += elem\n return sum\n\n\n# Main\nco = [] # Cours d'ouverture du jour\ncc = [] # Cours à la clôture\ncma = [] # Cours maximal du jour\ncmi = [] # Cours minimal du jour\ndt = [] # Date du jour\nacc = [] # Accroissements journaliers\naccpos = 0 # Accroissements journaliers positifs\naccneg = 0 # Accroissements journaliers négatifs\naccroi = 0\n\n# Ouverture et lecture\nwith open(\"cac40.csv\", encoding=\"utf-8\") as fichier:\n for ligne in fichier:\n # print(ligne)\n ligneCour = ligne.split(\";\")\n co.append(float(ligneCour[2]))\n cc.append(float(ligneCour[5]))\n cma.append(float(ligneCour[3]))\n cmi.append(float(ligneCour[4]))\n dt.append(ligneCour[1])\n accroi = float(ligneCour[2]) - float(ligneCour[5])\n acc.append(accroi)\n if accroi >= 0:\n accpos += accroi\n else:\n accneg -= accroi\n\n# Nombre de jours\nprint(len(dt), \"jours sont répertoriés dans le fichier.\")\n\n# Cours le plus bas\niCmaPlusBas = indiceMin(cma)\nprint(\"Le cours le plus bas dans la période est\",\n cma[iCmaPlusBas], \"le\", dt[iCmaPlusBas])\n\n# Accroissements journaliers\nprint(\"Total accroissements journaliers :\", totalAcc(acc))\n\n# plt.plot(acc)\nplt.bar(0.5, accpos, 1, color='r', label='Accroissement positif', alpha=0.5)\nplt.bar(2.5, accneg, 1, color='b', label='Accroissement négatif', alpha=0.5)\nplt.title('Accroissement total')\nplt.legend(loc=0)\nplt.show()\n","sub_path":"tp6/tp6ex1.py","file_name":"tp6ex1.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"398194277","text":"from .map_generator import Generator\nfrom .player import Player, Baby\nfrom .monsters import Monster\nimport random as rd\n\n\nclass Game:\n def __init__(self, width=53, height=32):\n self._generator = Generator(width=width, height=height)\n self._generator.gen_level()\n self._generator.gen_coins()\n self._generator.gen_potions()\n self._generator.gen_tiles_level()\n self._map = self._generator.tiles_level\n self.height = self._generator.height\n self.width = self._generator.width\n self._players = [Player(chr(0x1F471)), Player(chr(0x1F990))]\n self._initPos_P1 = self._players[0].initPos(self._map)\n self._initPos_P2 = self._players[1].initPos(self._map)\n self.baby = self._generator.gen_baby(self)\n self._Monster = self._generator.gen_monster(self)\n\n def getMap(self):\n return self._map\n\n def move(self, dx, dy, i):\n return self._players[i].move(dx, dy, self._map), self._Monster.moveM(self._map, self._players)\n\n #def moveM(self):\n # return self._Monster.moveM(self._map, self._player)","sub_path":"game_backend/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"177505556","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pdb\n\n\nclass QContainer:\n def __init__(self, nb_states):\n assert nb_states in [11, 101, 1001]\n\n divisors = {1001: 1, 101: 10, 11: 100}\n self._divisor = divisors[nb_states]\n\n # 1001 explicit states (-500..500)\n data_dims = [nb_states]\n action_count = 2 # move left, move right\n self.data = np.zeros(data_dims + [action_count])\n\n \n def __getitem__(self, key):\n \"\"\"Retrieve action-state value\n\n key should have following format:\n (state, action)\n [0,1001] [0,1]\n \"\"\"\n\n assert isinstance(key, tuple)\n assert len(key) == 2\n if key[0] == 'TERMINAL':\n return 0\n assert isinstance(key[0], int)\n assert isinstance(key[1], int) or isinstance(key[1], np.int64)\n\n state = key[0]\n action = key[1]\n\n return self.data[round(state/self._divisor), action]\n\n\n def __setitem__(self, key, value):\n \"\"\"Retrieve action-state value\n\n key should have following format:\n (state, action)\n [0,1001] [0,1]\n \"\"\"\n\n assert isinstance(key, tuple)\n assert len(key) == 2\n assert isinstance(key[0], int)\n assert isinstance(key[1], int) or isinstance(key[1], np.int64)\n\n state = key[0]\n action = key[1]\n\n self.data[round(state/self._divisor), action] = value\n\n def clear(self):\n self.data.fill(0)\n\n def is_zeros(self):\n return np.count_nonzero(self.data) == 0\n\nclass HistoryData:\n \"\"\"One piece of agent trajectory\"\"\"\n def __init__(self, t_step, observation, reward, done):\n self.t_step = t_step\n self.observation = observation\n self.reward = reward\n self.action = None\n self.done = done\n\n def __str__(self):\n return '{0}: {1}, {2} {3} {4}'.format(\n self.t_step, self.observation, self.reward, self.done, self.action)\n\n\nclass AgentAggregate:\n def __init__(self, state_space, action_space, nb_states,\n step_size=0.1, lmbda=None, e_rand=0.0):\n\n self.V = {}\n self.Q = QContainer(nb_states)\n\n self.Q_sum = QContainer(nb_states) # sum of all visits\n self.Q_num = QContainer(nb_states) # number of times state-action visited\n\n for state in state_space:\n self.V[state] = 0\n # for action in action_space:\n # self.Q[state, action] = 0\n # self.Q_sum[state, action] = 0\n # self.Q_num[state, action] = 0\n \n self._action_space = action_space\n self._step_size = step_size # usually noted as alpha in literature\n self._discount = 1.0 # usually noted as gamma in literature\n\n self._lmbda = lmbda # param for lambda functions\n\n self._epsilon_random = e_rand # policy parameter, 0 => always greedy\n\n self._episode = 0\n self._trajectory = [] # Agent saves history on it's way\n self._eligibility_traces_V = {} # for lambda funtions\n self._eligibility_traces_Q = QContainer(nb_states) # for lambda funtions\n self._force_random_action = False # for exploring starts\n\n def reset(self):\n self._episode += 1\n self._trajectory = [] # Agent saves history on it's way\n self._eligibility_traces_V = {}\n self._eligibility_traces_Q.clear() # for lambda funtions\n self._force_random_action = False\n\n def reset_exploring_starts(self):\n self._episode += 1\n self._trajectory = [] # Agent saves history on it's way\n self._eligibility_traces_V = {}\n self._eligibility_traces_Q.clear() # for lambda funtions\n self._force_random_action = True\n\n def pick_action(self, obs):\n\n # player_points = obs[1]\n # if player_points < 18:\n # return 1 # draw\n # else:\n # return 0 # stick\n\n if self._force_random_action:\n self._force_random_action = False\n return np.random.choice(self._action_space)\n \n\n\n if np.random.rand() < self._epsilon_random:\n # pick random action\n return np.random.choice(self._action_space)\n\n else:\n # act greedy\n max_Q = float('-inf')\n max_action = None\n\n possible_actions = []\n for action in self._action_space:\n q = self.Q[obs, action]\n if q > max_Q:\n possible_actions.clear()\n possible_actions.append(action)\n max_Q = q\n elif q == max_Q:\n possible_actions.append(action)\n return np.random.choice(possible_actions)\n\n\n\n def append_trajectory(self, t_step, prev_action, observation, reward, done):\n if len(self._trajectory) != 0:\n self._trajectory[-1].action = prev_action\n self.Q_num[self._trajectory[-1].observation, prev_action] += 1\n\n self._trajectory.append(\n HistoryData(t_step, observation, reward, done))\n\n def print_trajectory(self):\n print('Trajectory:')\n for element in self._trajectory:\n print(element)\n print('Total trajectory steps: {0}'.format(len(self._trajectory)))\n\n def check_trajectory_terminated_ok(self):\n last_entry = self._trajectory[-1]\n if not last_entry.done:\n raise ValueError('Cant do offline on non-terminated episode')\n if self.V[last_entry.observation] != 0:\n raise ValueError('Last state in trajectory has non-zero value')\n for act in self.action_space:\n if self.Q[last_entry.observation, act] != 0:\n raise ValueError('Action from last state has non-zero val.')\n\n\n\n def eval_td_t(self, t):\n \"\"\"TD update state-value for single state in trajectory\n\n This assumesss time step t+1 is availalbe in the trajectory\n\n For online updates:\n Call with t equal to previous time step\n\n For offline updates:\n Iterate trajectory from t=0 to t=T-1 and call for every t\n\n Params:\n t (int [t, T-1]) - time step in trajectory,\n 0 is initial state; T-1 is last non-terminal state\n\n V (float arr) - optional,\n if passed, funciton will operate on this array\n if None, then function will operate on self.V\n \"\"\"\n\n\n V = self.V # State values array, shape: [world_size]\n Q = self.Q # Action value array, shape: [world_size, action_space]\n\n # Shortcuts for more compact notation:\n\n St = self._trajectory[t].observation # evaluated state tuple (x, y)\n St_1 = self._trajectory[t+1].observation # next state tuple (x, y)\n Rt_1 = self._trajectory[t+1].reward # next step reward\n step = self._step_size\n disc = self._discount\n\n V[St] = V[St] + step * (Rt_1 + disc*V[St_1] - V[St])\n\n At = self._trajectory[t].action\n At_1 = self._trajectory[t+1].action\n if At_1 is None:\n At_1 = self.pick_action(St)\n\n Q[St, At] = Q[St, At] + step * (Rt_1 + disc * Q[St_1, At_1] - Q[St, At])\n\n def eval_td_online(self):\n self.eval_td_t(len(self._trajectory) - 2) # Eval next-to last state\n\n def eval_td_offline(self):\n \"\"\" Do TD update for all states in trajectory\n\n Note:\n This updates V and Q arrays \"in place\". True offline update should\n update copy of V (or Q), then replace V with a copy at the end.\n This function will yeild slightly different result.\n\n \"\"\"\n self.check_trajectory_terminated_ok()\n\n # Iterate all states in trajectory\n for t in range(0, len(self._trajectory)-1):\n # Update state-value at time t\n self.eval_td_t(t)\n\n\n\n\n\n\n\n def eval_td_lambda_t(self, t):\n \"\"\"TD(lambda) update for particular state.0\n\n Note:\n Becouse this function builds eligibility trace dictionary in order,\n it MUST be called in correct sequence, from t=0 to T=T-1.\n It can be called only once per t-step\n\n For online updates:\n Call with t equal to previous time step\n\n For offline updates:\n Iterate trajectory from t=0 to t=T-1 and call for every t\n\n Params:\n t (int [t, T-1]) - time step in trajectory,\n 0 is initial state; T-1 is last non-terminal state\n\n \"\"\"\n\n V = self.V # State values array, shape: [world_size]\n Q = self.Q # Action value array, shape: [world_size, action_space]\n\n EV = self._eligibility_traces_V # eligibility trace dictionary\n EQ = self._eligibility_traces_Q\n\n St = self._trajectory[t].observation # current state xy\n St_1 = self._trajectory[t+1].observation\n Rt_1 = self._trajectory[t+1].reward\n\n #\n # Handle V\n #\n\n if St not in EV:\n EV[St] = 0\n\n # Update eligibility traces for V\n for s in EV:\n EV[s] *= self._lmbda\n EV[St] += 1\n\n ro_t = Rt_1 + self._discount * V[St_1] - V[St]\n for s in EV:\n V[s] = V[s] + self._step_size * ro_t * EV[s]\n\n #\n # Handle Q\n #\n\n At = self._trajectory[t].action\n At_1 = self._trajectory[t+1].action\n\n if At_1 is None:\n At_1 = self.pick_action(St)\n\n\n # Update eligibility traces for Q\n EQ.data *= self._lmbda\n EQ[St, At] += 1\n\n ro_t = Rt_1 + self._discount * Q[St_1, At_1] - Q[St, At]\n Q.data += self._step_size * ro_t * EQ.data\n\n def eval_td_lambda_offline(self):\n \"\"\"TD(lambda) update for all states\n\n Class Params:\n self._lmbda (float, [0, 1]) - param. for weighted average of returns\n \"\"\"\n\n if len(self._eligibility_traces_V) != 0:\n raise ValueError('TD-lambda offline: eligiblity traces not empty?')\n if not self._eligibility_traces_Q.is_zeros():\n raise ValueError('TD-lambda offline: eligiblity traces not zeros?')\n\n self.check_trajectory_terminated_ok()\n\n # Iterate all states apart from terminal state\n max_t = len(self._trajectory)-2 # inclusive\n for t in range(0, max_t+1):\n self.eval_td_lambda_t(t)\n\n def eval_td_lambda_online(self, V=None):\n t = len(self._trajectory) - 2 # Previous time step\n self.eval_td_lambda_t(t)\n\n\n\n\n\n\n\n\n\n\n def calc_Gt(self, t):\n \"\"\"Calculates return for state t\n\n Params:\n t (int [t, T-1]) - time step in trajectory,\n 0 is initial state; T-1 is last non-terminal state\n\n \"\"\"\n\n T = len(self._trajectory)-1 # terminal state\n discount = 1.0\n\n Gt = 0\n\n # Iterate from t+1 to T (inclusive on both start and finish)\n for j in range(t+1, T+1):\n Rj = self._trajectory[j].reward\n Gt += discount * Rj\n discount *= self._discount\n\n return Gt\n\n def eval_mc_t(self, t):\n \"\"\"MC update for state-values for single state in trajectory\n\n Note:\n This assumes episode is completed and trajectory is present\n from start to termination.\n\n For online updates:\n N/A\n\n For offline updates:\n Iterate trajectory from t=0 to t=T-1 and call for every t\n\n Params:\n t (int [t, T-1]) - time step in trajectory,\n 0 is initial state; T-1 is last non-terminal state\n\n \"\"\"\n\n V = self.V # State values array, shape: [world_size]\n Q = self.Q # Action value array, shape: [world_size, action_space]\n\n # Shortcuts for more compact notation:\n St = self._trajectory[t].observation # current state (x, y)\n Gt = self.calc_Gt(t) # return for current state\n\n V[St] = V[St] + self._step_size * (Gt - V[St])\n\n At = self._trajectory[t].action\n Q[St, At] = Q[St, At] + self._step_size * (Gt - Q[St, At])\n\n def eval_mc_offline(self):\n \"\"\"MC update for all statates. Call after episode terminates\n\n Note:\n This updates V array \"in place\". True offline update should\n update copy of V, then replace V with a copy at the end.\n This function will yeild slightly different result.\n \"\"\"\n\n self.check_trajectory_terminated_ok()\n\n # Iterate all states in trajectory, apart from terminal state\n T = len(self._trajectory) - 1\n for t in range(0, T):\n # Update state-value at time t\n self.eval_mc_t(t)\n\n\n\n\n\n def eval_mc_full_t(self, t):\n \"\"\"MC update for state-values for single state in trajectory\n\n Note:\n This assumes episode is completed and trajectory is present\n from start to termination.\n\n For online updates:\n N/A\n\n For offline updates:\n Iterate trajectory from t=0 to t=T-1 and call for every t\n\n Params:\n t (int [t, T-1]) - time step in trajectory,\n 0 is initial state; T-1 is last non-terminal state\n\n \"\"\"\n\n V = self.V # State values array, shape: [world_size]\n Q = self.Q # Action value array, shape: [world_size, action_space]\n\n # Shortcuts for more compact notation:\n St = self._trajectory[t].observation # current state (x, y)\n Gt = self.calc_Gt(t) # return for current state\n\n\n V[St] = 0 # not updated\n\n\n At = self._trajectory[t].action\n self.Q_sum[St, At] += Gt\n Q[St, At] = self.Q_sum[St, At] / self.Q_num[St, At]\n\n def eval_mc_full(self):\n \"\"\"MC update for all statates. Call after episode terminates\n\n \"\"\"\n self.check_trajectory_terminated_ok()\n\n # Iterate all states in trajectory, apart from terminal state\n T = len(self._trajectory) - 1\n for t in range(0, T):\n # Update state-value at time t\n self.eval_mc_full_t(t)\n\n","sub_path":"marcin/rl_basic/06a_linear_approx/agent_aggregate.py","file_name":"agent_aggregate.py","file_ext":"py","file_size_in_byte":14157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"275007707","text":"import turtle\n\nwindow = turtle.Screen()\nwindow.bgcolor(\"black\")\n\nmichael = turtle.Turtle()\nmichael.color(\"cyan\")\nmichael.pensize(5)\n\nbailey = turtle.Turtle()\nbailey.color(\"pink\")\nbailey.pensize(10)\nbailey.shape(\"turtle\")\nbailey.speed(1)\n\nfor my_color in [\"red\", \"blue\", \"green\", \"yellow\"]:\n michael.color(my_color)\n michael.forward(100)\n michael.left(90)\n\n\nbailey.right(45)\nbailey.forward(150)\nbailey.right(45)\nbailey.forward(100)","sub_path":"multiple_turtles.py","file_name":"multiple_turtles.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"470913440","text":"####################################################################################\n# PersonValidate.py\n# @Author: Septiviana Savitri\n# @Last update: 28 Februari 2017\n# Fasilkom Universitas Indonesia\n#\n# Objective: To validate all the expanded data of Person in DBPedia \n# input: \n# - File contain each type of expanded data\n\n# output: validated version of data , remove all :\n # - word in KBBI or NLTK\n # - word in roman number\n # - word contain period\n # - word length 1\n # - word with all uppercase letter\n\n \n####################################################################################\n\n\nfrom function import writeDictToFile, writeListofStringToFile, writeListofListToFile, diKamus, buatKamus, hitungKapital, lemmaDiCorpus, writeDictWithValueToFile\nfrom nltk.stem.wordnet import WordNetLemmatizer\n\n\n\n##########################################################################\n# M A I N\n##########################################################################\n\n#set the input and output file\ninput = \"dbpedia-new/expanded/person.txt\"\n#input = \"cekPerson/validation/x-expand/resultPERBedaXDikurangiExpand.txt\"\nfolder = \"dbpedia-new/validate/\"\n#folder = \"cekPerson/validation/x-expand/\"\noutput = folder + \"person.txt\"\noutputtmp = folder + \"tmpperson.txt\"\noutputtmpEn = folder + \"tmppersonEn.txt\"\nnltk_data = \"dbpedia-new/en\"\nkebi_data = \"dbpedia-new/kebi.txt\"\nenglish_dict = \"dbpedia-new/english_corpus.txt\"\ndictKebi = {}\ndictNLTK = {}\ndictEnglish = {}\n######################### begin ################################\n\ninputFile = open(input, 'r', errors='ignore')\nflines = inputFile.readlines()\ndictPerson = {}\ndictTmp = {}\n\ndictNLTK = buatKamus(dictNLTK, nltk_data)\ndictEnglish = buatKamus(dictEnglish, english_dict)\ndictKebi = buatKamus(dictKebi, kebi_data)\nROMAWI = [\"I\", \"II\", \"III\", \"IV\", \"V\", \"VI\", \"VII\", \"VIII\", \"IX\", \"X\",\n \"XI\", \"XII\", \"XIII\", \"XIV\",\n \"XX\", \"XXX\"]\nBULAN = [\"April\", \"Juni\", \"Juli\"]\nAGAMA = [\"Buddha\",\"Hindu\",\"Islam\",\"Katolik\",\"Khonghucu\",\"Kristen\",\"Protestan\"]\ncount = 1\ncountLema = 0\n\nfor k in flines:\n k= k.replace(\"\\n\",\"\")\n splitK = k.split(\" \")\n \n \n \n \n #Jika nama ada di kebi\n if(diKamus(k, dictKebi)):\n dictTmp[k] = \"Kebi\"\n #jika nama ada di nltk\n elif(diKamus(k, dictNLTK)):\n dictTmp[k] = \"NLTK\"\n elif(len(k) <2):\n dictTmp[k] = \"Panjang 1\"\n elif(k in ROMAWI):\n dictTmp[k] = \"Romawi\"\n #V6\n elif(k in BULAN):\n dictTmp[k] = \"Nama Bulan\"\n #V7\n elif(k in AGAMA):\n dictTmp[k] = \"Nama agama\"\n print(k)\n #untuk entity yang berisi 1 kata\n elif len(splitK) == 1 and \".\" in k:\n dictTmp[k] = \"Satu kata bertitik\"\n \n elif len(splitK) == 1 and k.isnumeric():\n dictTmp[k] = \"Angka\"\n # elif len(k) == 2 and k[1].isupper():\n # dictTmp[k] = k\n elif len(splitK) == 1 and hitungKapital(k) == len(k):\n dictTmp[k]=\"Huruf Besar Semua\" \n elif len(splitK) == 1 and lemmaDiCorpus(k,dictNLTK):\n dictTmp[k] = \"Lemmatization di nltk\" \n else: \n dictPerson[k] = k\ninputFile.close()\n\nwriteDictToFile(dictPerson, output)\n\nwriteDictWithValueToFile(dictTmp, outputtmp)\n#writeListofStringToFile(newListTmp, outputtmp)\n\n\n\n############################################################################\n# End of file\n############################################################################\n","sub_path":"NER_Ika_Lib/PersonValidate.py","file_name":"PersonValidate.py","file_ext":"py","file_size_in_byte":3414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"306180959","text":"from time import sleep\n\ndados = {}\n\n\n\nfor informacoes in range(1):\n nome = input(\"qual o seu nome? : \")\n dados.update({\"nome\":nome}) \n nascimento = int(input(\"Qual o seu ano de nascimento? : \"))\n idade = (2021 - nascimento)\n dados.update({\"idade\":idade})\n ctps = int(input(\"qual a sua carteira de trabalho? (0 não tem): \"))\n if ctps == 0:\n dados.update({\"Carteira de trabalho Nº\":\"não tem!\"})\n else:\n dados.update({\"carteira de trabalho Nº\":ctps})\n contratacao = int(input(\"Digite o ano em que foi contratado: \"))\n dados.update({\"Ano de contratação\":contratacao})\n salario = float(input(\"Digite o valor do salário: \"))\n dados.update({\"Salário em R$\":salario})\n aposentadoria = (35 - (2021-contratacao))\n dados.update({\"Quantos anos de trabalho faltam para se aposentar \":aposentadoria})\n a_receber = ((aposentadoria*12)*salario)\n dados.update({\"Você vai receber até se aposentar: \":a_receber})\n print()\n\nprint(dados)\nprint()\nfor informacoes in dados:\n print(f'{informacoes}: {dados[informacoes]}')\n sleep(1)","sub_path":"aula 14 20.05/verificação de aprendizagem8.py","file_name":"verificação de aprendizagem8.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"213610312","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# rce-core/rce/util/container.py\n#\n# This file is part of the RoboEarth Cloud Engine framework.\n#\n# This file was originally created for RoboEearth\n# http://www.roboearth.org/\n#\n# The research leading to these results has received funding from\n# the European Union Seventh Framework Programme FP7/2007-2013 under\n# grant agreement no248942 RoboEarth.\n#\n# Copyright 2012 RoboEarth\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# \\author/s: Dominique Hunziker\n#\n#\n\n# Python specific imports\nimport os\n\npjoin = os.path.join\n\n# twisted specific imports\nfrom twisted.python import log\nfrom twisted.python.failure import Failure\nfrom twisted.internet.defer import Deferred\nfrom twisted.internet.utils import getProcessValue\n\n\n_CONFIG = \"\"\"\nlxc.utsname = {hostname}\n\nlxc.tty = 4\nlxc.pts = 1024\nlxc.rootfs = {fs}\nlxc.mount = {fstab}\n\nlxc.network.type = veth\nlxc.network.flags = up\nlxc.network.name = eth0\nlxc.network.link = lxcbr0\nlxc.network.ipv4 = {ip}\n\nlxc.cgroup.devices.deny = a\n# /dev/null and zero\nlxc.cgroup.devices.allow = c 1:3 rwm\nlxc.cgroup.devices.allow = c 1:5 rwm\n# consoles\nlxc.cgroup.devices.allow = c 5:1 rwm\nlxc.cgroup.devices.allow = c 5:0 rwm\nlxc.cgroup.devices.allow = c 4:0 rwm\nlxc.cgroup.devices.allow = c 4:1 rwm\n# /dev/{{,u}}random\nlxc.cgroup.devices.allow = c 1:9 rwm\nlxc.cgroup.devices.allow = c 1:8 rwm\nlxc.cgroup.devices.allow = c 136:* rwm\nlxc.cgroup.devices.allow = c 5:2 rwm\n# rtc\nlxc.cgroup.devices.allow = c 254:0 rwm\n\n# restrict capabilities\n# can't use: lxc.cap.drop = sys_admin\n# see: man capabilities for more information\n#lxc.cap.drop = audit_control\n#lxc.cap.drop = audit_write\n#lxc.cap.drop = mac_admin\n#lxc.cap.drop = mac_override\n#lxc.cap.drop = mknod\n#lxc.cap.drop = setfcap\n#lxc.cap.drop = setpcap\n#lxc.cap.drop = sys_boot\n#lxc.cap.drop = sys_chroot\n#lxc.cap.drop = sys_module\n#lxc.cap.drop = sys_rawio\n#lxc.cap.drop = sys_time\n\"\"\"\n\n\n_FSTAB_BASE = \"\"\"\nproc {proc} proc nodev,noexec,nosuid 0 0\ndevpts {devpts} devpts defaults 0 0\nsysfs {sysfs} sysfs defaults 0 0\n\"\"\"\n\n\n_FSTAB_BIND = '{srcDir} {fsDir} none bind{ro} 0 0\\n'\n\n\nclass ContainerError(Exception):\n \"\"\" Exception is raised when a LXC command fails.\n \"\"\"\n\n\nclass Container(object):\n \"\"\" Class representing a single container.\n \"\"\"\n def __init__(self, reactor, rootfs, conf, hostname, ip):\n \"\"\" Initialize the Container.\n\n @param reactor: Reference to the twisted::reactor\n @type reactor: twisted::reactor\n\n @param rootfs: Filesystem path of the root directory of the\n container filesystem.\n @type rootfs: str\n\n @param conf: Filesystem path of folder where configuration\n files for the container should be stored.\n @type conf: str\n\n @param hostname: Host name of the container.\n @type hostname: str\n\n @param ip: IP address which the container should use.\n Use '0.0.0.0' for DHCP.\n @type ip: str\n \"\"\"\n self._reactor = reactor\n self._rootfs = rootfs\n self._conf = pjoin(conf, 'config')\n self._fstab = pjoin(conf, 'fstab')\n self._hostname = hostname\n self._ip = ip\n\n if not os.path.isabs(conf):\n raise ValueError('Container configuration directory is not an '\n 'absolute path.')\n\n if not os.path.isdir(conf):\n raise ValueError('Container Configuration directory does not '\n 'exist: {0}'.format(conf))\n\n if os.path.exists(self._conf):\n raise ValueError('There is already a config file in the container '\n \"configuration directory '{0}'.\".format(conf))\n\n if os.path.exists(self._fstab):\n raise ValueError('There is already a fstab file in the container '\n \"configuration directory '{0}'.\".format(conf))\n\n self._fstabExt = []\n\n def extendFstab(self, src, fs, ro):\n \"\"\" Add a line to the fstab file using bind.\n\n @param src: Source path in host filesystem.\n @type src: str\n\n @param fs: Path in container filesystem to which the source\n should be bind.\n @type fs: str\n\n @param ro: Flag to indicate whether bind should be read-only\n or not.\n @type ro: bool\n \"\"\"\n self._fstabExt.append(_FSTAB_BIND.format(srcDir=src,\n fsDir=pjoin(self._rootfs, fs),\n ro=',ro' if ro else ''))\n\n def _setup(self):\n \"\"\" Setup necessary files.\n \"\"\"\n with open(self._conf, 'w') as f:\n f.write(_CONFIG.format(hostname=self._hostname, fs=self._rootfs,\n fstab=self._fstab, ip=self._ip))\n\n with open(self._fstab, 'w') as f:\n f.write(_FSTAB_BASE.format(\n proc=pjoin(self._rootfs, 'proc'),\n devpts=pjoin(self._rootfs, 'dev/pts'),\n sysfs=pjoin(self._rootfs, 'sys')))\n f.writelines(self._fstabExt)\n\n def start(self, name):\n \"\"\" Start the container.\n\n @param name: Name of the container which should be started.\n @type name: str\n\n @return: Deferred whose callback is triggered on success or\n whose errback is triggered on failure with an\n error message.\n @rtype: twisted.internet.defer.Deferred\n \"\"\"\n self._setup()\n\n log.msg(\"Start container '{0}'\".format(name))\n deferred = Deferred()\n\n try:\n dfrd = getProcessValue('/usr/bin/lxc-start',\n ('-n', name, '-f', self._conf, '-d'),\n env=os.environ, reactor=self._reactor)\n def cb(retVal):\n if retVal == 0:\n deferred.callback('Container successfully started.')\n else:\n e = ContainerError('Container could not be started: '\n 'Received exit code {0} from '\n 'lxc-start.'.format(retVal))\n deferred.errback(Failure(e))\n\n dfrd.addCallback(cb)\n except OSError:\n e = ContainerError('Insufficient system resources to start a new '\n 'process.')\n deferred.errback(Failure(e))\n\n return deferred\n\n def stop(self, name):\n \"\"\" Stop the container.\n\n @param name: Name of the container which should be stopped.\n @type name: str\n\n @param command: Deferred whose callback is triggered on success\n or whose errback is triggered on failure with\n an error message.\n @type command: twisted.internet.defer.Deferred\n \"\"\"\n log.msg(\"Stop container '{0}'\".format(name))\n deferred = Deferred()\n\n try:\n dfrd = getProcessValue('/usr/bin/lxc-stop', ('-n', name),\n env=os.environ, reactor=self._reactor)\n\n def cb(retVal):\n if retVal == 0:\n deferred.callback('Container successfully stopped.')\n else:\n e = ContainerError('Container could not be stopped: '\n 'Received exit code {0} from '\n 'lxc-stop.'.format(retVal))\n deferred.errback(Failure(e))\n\n dfrd.addCallback(cb)\n except OSError:\n e = ContainerError('Insufficient system resources to stop a '\n 'process.')\n deferred.errback(Failure(e))\n\n return deferred\n\n# def execute(self, name, command):\n# \"\"\" Execute a command inside the container.\n#\n# @param name: Name of the container which will execute the\n# command.\n# @type name: str\n#\n# @param command: Command which should be executed.\n# @type command: [str]\n# \"\"\"\n# def cb(_):\n# print('\\nSuccessful.')\n# self._reactor.stop()\n#\n# def eb(err):\n# print('\\n{0}'.format(err.getErrorMessage()))\n# self._reactor.stop()\n#\n# deferred = Deferred()\n# deferred.addCallbacks(cb, eb)\n#\n# self.extendFstab('/usr/lib/lxc', pjoin(self._rootfs, 'usr/lib/lxc'),\n# False)\n#\n# protocol = self._setup(deferred, sys.stdout.write, sys.stderr.write)\n#\n# try:\n# cmd = ['/usr/bin/lxc-execute', '-n', name, '-f', self._conf, '--']\n# cmd += command\n# self._reactor.spawnProcess(protocol, cmd[0], cmd, env=os.environ)\n# except Exception as e:\n# import traceback\n# print('Caught an exception when trying to execute a command in '\n# 'the container.')\n# print('\\n'.join(traceback.format_exception_only(type(e), e)))\n","sub_path":"rce-core/rce/util/container.py","file_name":"container.py","file_ext":"py","file_size_in_byte":10044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"280325386","text":"# Week Two Exercise 6\n# largest common substring\n\n# given the user enters two strings, return the largest common substring\n# example: \"I love Dr. Mario\" and \"Mario Bros. 2 is the best\" returns \"Mario\"\n\nfirst = input('Enter a string: ')\nsecond = input('Enter another string: ')\n\n# v1 keep track of largest\nlargest = ''\nfor i in range(len(first)):\n for x in range(i,len(first)+1):\n sub = first[i:x]\n if sub in second and len(sub) > len(largest):\n largest = sub\nprint(largest)\n\n# v2 thunder line\nnewList = [first[i:x] for i in range(len(first)) for x in range(i+1,len(first)+1) if first[i:x] in second]\nnewList.sort(key=len)\nprint(newList[-1])\n\n\n# v3 list comp unroll\nnewList = [first[i:x]\n for i in range(len(first))\n for x in range(i+1,len(first)+1)\n if first[i:x] in second]\n\nnewList.sort(key=len)\nprint(newList[-1])\n","sub_path":"week2/week_2_exercise_6.py","file_name":"week_2_exercise_6.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"617922331","text":"from django.contrib import admin \nfrom django.urls import reverse \nfrom django.utils.html import mark_safe\nfrom django.db import models \nfrom django.forms import NumberInput, Textarea, TextInput\nfrom django.utils.translation import gettext_lazy as _\nfrom modeltranslation.admin import TabbedTranslationAdmin, TranslationStackedInline\nfrom box.core.utils import BaseAdmin , seo \n# from adminsortable.admin import SortableAdmin\nfrom box.core.utils import BaseAdmin\nfrom .models import *\nfrom box.core.utils import (\n show_admin_link,\n AdminImageWidget, seo, \n)\n# from django_summernote.admin import SummernoteModelAdmin\n# from markdownx.admin import MarkdownxModelAdmin\n\n\n\nclass CommentInline(admin.StackedInline):\n model = PostComment\n extra = 0\n classes = ['collapse']\n\n\nclass PostInline(TranslationStackedInline):\n model = Post\n extra = 0\n classes = ['collapse']\n\n\n@admin.register(PostCategory)\nclass PostCategoryAdmin(\n BaseAdmin, \n TabbedTranslationAdmin,\n # SummernoteModelAdmin,\n ):\n # summernote_fields = ('content',)\n # changeform \n fieldsets = (\n (('ОСНОВНА ІНФОРМАЦІЯ'), {\n 'fields':(\n 'title',\n 'image',\n 'created',\n 'updated',\n 'code',\n ),\n 'classes':('collapse'),\n }),\n seo,\n )\n prepopulated_fields = {\n \"slug\": (\"title\",),\n }\n readonly_fields = [\n 'code',\n 'updated',\n 'created',\n ]\n save_on_top = True \n # changelist\n search_fields = [\n 'title',\n 'description',\n ]\n list_display = [\n 'id',\n 'title',\n 'slug',\n 'is_active',\n ]\n list_display_links = [\n 'id',\n 'title',\n 'slug',\n ]\n formfield_overrides = {\n models.CharField: {'widget': NumberInput(attrs={'size':'20'})},\n models.CharField: {'widget': TextInput(attrs={'size':'20'})},\n models.TextField: {'widget': Textarea(attrs={'rows':6, 'cols':20})},\n }\n\n\n\nfrom import_export.admin import ImportExportModelAdmin\nfrom .resources import PostResource\n\n\n\n@admin.register(Post)\nclass PostAdmin(\n BaseAdmin,\n TabbedTranslationAdmin,\n # SortableAdmin,\n ImportExportModelAdmin,\n # MarkdownxModelAdmin,\n # SummernoteModelAdmin,\n ):\n resource_class = PostResource\n def show_category(self, obj):\n return show_admin_link(obj, obj_attr='category', obj_name='title')\n\n def show_image(self, obj):\n return mark_safe(f\"\")\n # summernote_fields = ('content',)\n show_category.short_description = _(\"Категорія\")\n show_image.short_description = _(\"Зображення\")\n \n prepopulated_fields = {\n 'slug':('title',),\n }\n if 'jet' not in settings.INSTALLED_APPS:\n autocomplete_fields = [\n 'author',\n 'category',\n 'similars',\n 'markers',\n ]\n inlines = [\n CommentInline,\n ]\n fieldsets = (\n seo,\n (('ОСНОВНА ІНФОРМАЦІЯ'), {\n 'fields':(\n 'title',\n 'category',\n 'author',\n 'similars',\n 'markers',\n 'image',\n 'content',\n ),\n # 'classes':['collapse']\n }),\n # (('КОНТЕНТ'), {\n # 'fields':(\n # 'content',\n # ),\n # # 'classes':['collapse',]\n # }),\n )\n list_display = [\n 'show_image',\n 'title',\n 'show_category',\n 'is_active',\n \"show_site_link\",\n 'show_delete_link',\n ]\n list_editable = [\n 'is_active',\n ]\n list_display_links = [\n 'show_image',\n 'title',\n \"show_site_link\",\n\n ]\n prepopulated_fields = {\n \"slug\": (\"title\",),\n }\n search_fields = [\n 'title',\n 'content',\n ]\n list_filter = [\n 'category',\n 'created',\n 'updated',\n ]\n\n\n# @admin.register(Comment)\nclass CommentAdmin(admin.ModelAdmin):\n inlines = [\n CommentInline,\n ]\n\n\nclass PostCommentAdmin(BaseAdmin):\n list_display = [\n 'content',\n 'is_active',\n ]\n list_display_links = [\n 'content',\n ]\n search_fields = [\n 'content',\n ]\n\n\n","sub_path":"apps/sw_blog/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":4431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"376731467","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nN = int(input())\nN_list = list(map(int, input().split()))\nM = int(input())\nM_list = list(map(int, input().split()))\n\nN_count = {}\nfor n in N_list:\n try:\n N_count[n] += 1\n except:\n N_count[n] = 1\n\nanswer = []\nfor m in M_list:\n try: \n answer.append((N_count[m]))\n except:\n answer.append(0)\n\nfor i in answer:\n print(i, end = ' ')\n\n","sub_path":"10816_숫자카드2.py","file_name":"10816_숫자카드2.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"286929676","text":"#!/usr/bin/env python3\n\nimport sys\n\nfilenames= sys.argv[1:]\n\nfor file in filenames:\n alle_dna=\"\"\n splice_line=\"\"\n dna_regel=False\n opened = open(file)\n mRNA_regel = False\n for line in opened:\n if \"DEFINITION\" in line:\n definition =line\n if \"VERSION\" in line:\n version = line\n if \"ORIGIN\" in line:\n dna_regel= True\n if\"//\" in line:\n dna_regel=False\n if dna_regel == True:\n alle_dna= alle_dna + line.strip()\n\n if \"mRNA\" in line and \"join\" in line:\n mRNA_regel = True\n if \"/gene\" in line:\n mRNA_regel= False\n if mRNA_regel == True:\n splice_line = splice_line + line\n\nprint(alle_dna) \nprint(splice_line)\nvertaal = {\"a\":\"A\",\n \"t\":\"T\",\n \"c\":\"C\",\n \"g\":\"G\",\n \"1\":\"\",\n \"2\":\"\",\n \"3\":\"\",\n \"4\":\"\",\n \"5\":\"\",\n \"6\":\"\",\n \"7\":\"\",\n \"8\":\"\",\n \"9\":\"\",\n \"0\":\"\",\n \" \":\"\"}\nvertaaltabel = str.maketrans(vertaal)\nalle_dna = alle_dna.translate(vertaaltabel)\nsplicesites = []\n\n#tussenin = splice_line.split()[1].split(\"(\")[1].split(\",\")\ntussenin = \"\".join(splice_line.split()[1:]).split(\"(\")[1].strip(\")\").split(\",\")\nprint(tussenin)\n\nsplicesites2 = []\nprint(splicesites2)\n\nfor locatie in tussenin:\n cijfers = locatie.split(\"..\")\n if len(cijfers) == 2:\n splicesites.append(( int(cijfers[0])-1, int(cijfers[1])-1 ))\nprint(splicesites)\nmRNA_regel= False\nalle_mRNA= \"\"\n\nfor splice in splicesites:\n slice(alle_dna)\n print(alle_dna)\n \n##\n##for line in open(filenames[0]):\n## if \"mRNA\" in line:\n## mRNA_regel= True\n## if \")\" in line and mRNA_regel:\n## alle_mRNA = alle_mRNA + line.strip()\n## mRNA_regel= False\n## if mRNA_regel == True:\n## alle_mRNA = alle_mRNA + line.strip()\n## print(alle_mRNA.count(\",\"))\n","sub_path":"les5/opdracht3_les5.py","file_name":"opdracht3_les5.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"596733008","text":"# -*- coding: utf-8 -*-\n\nimport datetime\n\nimport grpc\n\nfrom simple_pb2 import MessageData\nfrom simple_pb2_grpc import SimpleServiceStub\n\n\ndef send_message(stub, name, msg):\n messages = []\n sent_at = \"{}\".format(datetime.datetime.today())\n messages.append(MessageData(sender=name, body=msg, sent_at=sent_at))\n responses = stub.SimpleServer(iter(messages))\n for response in responses:\n print('Received message : {}'.format(response.reply))\n\ndef main():\n with grpc.insecure_channel('localhost:50051') as channel:\n stub = SimpleServiceStub(channel)\n print('--Please input your name--')\n while True:\n name = input(\"What's your name? > \")\n message = input(\"message > \")\n send_message(stub, name, message)\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"py/simple/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"298899314","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport six\nfrom nose import tools\n\nimport umemcache\n\n\nclass TestBasicTests(object):\n def setUp(self):\n self.key = \"test\"\n self.client = umemcache.Client([\"127.0.0.1\"])\n\n def test_basic_commands(self):\n\n # Set and get different data types\n\n self.client.set(self.key, b\"resume\")\n value = self.client.get(self.key)\n tools.assert_equal(value, b\"resume\")\n\n self.client.set(self.key, u\"résumé\")\n value = self.client.get(self.key)\n tools.assert_equal(value, u\"résumé\")\n self.client.set(self.key, u\"резюме\")\n value = self.client.get(self.key)\n tools.assert_equal(value, u\"резюме\")\n\n self.client.set(self.key, 42)\n value = self.client.get(self.key)\n tools.assert_equal(value, 42)\n\n self.client.set(self.key, 3.1415)\n value = self.client.get(self.key)\n tools.assert_equal(value, 3.1415)\n\n my_object = {} # a simple object\n self.client.set(self.key, my_object)\n value = self.client.get(self.key)\n tools.assert_equal(value, my_object)\n\n # incr and decr\n\n self.client.set(self.key, 1)\n value = self.client.get(self.key)\n tools.assert_equal(value, 1)\n\n self.client.incr(self.key)\n value = self.client.get(self.key)\n tools.assert_equal(value, 2)\n\n self.client.incr(self.key, 3)\n value = self.client.get(self.key)\n tools.assert_equal(value, 5)\n\n self.client.decr(self.key)\n value = self.client.get(self.key)\n tools.assert_equal(value, 4)\n\n self.client.decr(self.key, 3)\n value = self.client.get(self.key)\n tools.assert_equal(value, 1)\n\n # flush\n\n self.client.flush_all()\n\n # add, replace, and delete\n\n response = self.client.add(self.key, \"my value\")\n tools.assert_true(response)\n\n response = self.client.add(self.key, \"my value\")\n tools.assert_false(response)\n\n response = self.client.replace(self.key, \"amazing\")\n tools.assert_true(response)\n\n response = self.client.delete(self.key)\n tools.assert_true(response)\n value = self.client.get(self.key)\n tools.assert_is_none(value)\n\n response = self.client.delete(self.key)\n tools.assert_false(response)\n\n response = self.client.replace(self.key, \"nope\")\n tools.assert_false(response)\n\n # append and prepend\n\n self.client.flush_all()\n\n response = self.client.append(self.key, \"nothing\")\n tools.assert_false(response)\n\n response = self.client.prepend(self.key, \"nothing\")\n tools.assert_false(response)\n\n self.client.add(self.key, \"te\")\n response = self.client.append(self.key, \"st\")\n tools.assert_true(response)\n\n response = self.client.prepend(self.key, \"successful \")\n tools.assert_true(response)\n\n value = self.client.get(self.key)\n tools.assert_equal(value, \"successful test\")\n\n def test_basic_commands_with_tuple_keys(self):\n # TODO: This tests that all commands accept tuples, but doesn't\n # confirm that the values really get placed on a single server\n self.key = (b\"test\", b\"abc\")\n self.test_basic_commands()\n\n def test_multi(self):\n data = {\n b'test_a': 222,\n b'test_b': 42.7,\n b'test_c': b'string data',\n b'test_d': u'российские данные',\n b'test_e': {}, # a simple object\n }\n keys = list(data.keys())\n\n response = self.client.set_multi(data)\n tools.assert_true(response)\n \n response = self.client.set_multi(data, cmd=b'replace')\n tools.assert_true(response)\n \n response = self.client.set_multi(data, cmd=b'add')\n tools.assert_false(response)\n\n response = self.client.get_multi(keys)\n tools.assert_equal(data, response)\n\n response = self.client.delete_multi(keys)\n tools.assert_true(response)\n response = self.client.delete_multi(keys)\n tools.assert_false(response)\n\n def test_multi_with_tuple_keys(self):\n data = {\n (b'test_a', b'test'): 222,\n (b'test_b', b'test'): 42.7,\n (b'test_c', b'test'): b'string data',\n (b'test_d', b'test'): u'российские данные',\n (b'test_e', b'test'): {}, # a simple object\n }\n keys = list(data.keys())\n\n response = self.client.set_multi(data)\n tools.assert_true(response)\n \n response = self.client.set_multi(data, cmd=b'replace')\n tools.assert_true(response)\n \n response = self.client.set_multi(data, cmd=b'add')\n tools.assert_false(response)\n\n response = self.client.get_multi(keys)\n # response keys won't be a tuple\n expected_data = dict((k[0], v) for k, v in six.iteritems(data))\n tools.assert_equal(expected_data, response)\n\n response = self.client.delete_multi(keys)\n tools.assert_true(response)\n response = self.client.delete_multi(keys)\n tools.assert_false(response)\n\nclass TestKeyChecksEnabled():\n def setUp(self):\n self.key = \"test\"\n self.client = umemcache.Client([\"127.0.0.1\"], check_key=True)\n\n # TODO: client-side checking for values\n\n def test_key_invalid_characters(self):\n key = \"my invalid key\"\n with tools.assert_raises(umemcache.exceptions.MemcacheKeyError):\n self.client.get(key)\n\n def test_key_too_long(self):\n key = 'a' * (self.client.MAX_KEY_LENGTH + 1)\n with tools.assert_raises(umemcache.exceptions.MemcacheKeyError):\n self.client.get(key)\n\n\nclass TestKeyChecksDisabled():\n def setUp(self):\n self.key = \"test\"\n self.client = umemcache.Client([\"127.0.0.1\"], check_key=False)\n\n def test_max_value_length(self):\n # Default max item size. This test may fail if you have\n # increased this limit on the server\n value = b'a' * 1048576\n\n with tools.assert_raises(umemcache.exceptions.MemcacheServerError):\n self.client.set(self.key, value)\n\n def test_key_invalid_characters(self):\n key = \"my invalid key\"\n # this will do a get on \"my\", \"invalid\" and \"key\" and will not\n # raise any exceptions\n response = self.client.get(key)\n tools.assert_false(response)\n\n def test_key_too_long(self):\n key = 'a' * (self.client.MAX_KEY_LENGTH + 1)\n with tools.assert_raises(umemcache.exceptions.MemcacheClientError):\n self.client.get(key)\n","sub_path":"tests/test_umemcache.py","file_name":"test_umemcache.py","file_ext":"py","file_size_in_byte":6689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"306370973","text":"from numpy import sum\nfrom numpy import zeros\n\nfrom gwlfe.Input.WaterBudget.Water import Water\nfrom gwlfe.Memoization import memoize\nfrom gwlfe.MultiUse_Fxns.Discharge.UrbanQTotal_1 import UrbanQTotal_1\nfrom gwlfe.MultiUse_Fxns.Discharge.UrbanQTotal_1 import UrbanQTotal_1_f\n\n\n@memoize\ndef UrbanRunoff(NYrs, DaysMonth, InitSnow_0, Temp, Prec, NRur, NUrb, Area, CNI_0, AntMoist_0, Grow_0, CNP_0, Imper,\n ISRR, ISRA):\n result = zeros((NYrs, 12))\n water = Water(NYrs, DaysMonth, InitSnow_0, Temp, Prec)\n urbanqtotal_1 = UrbanQTotal_1(NYrs, DaysMonth, Temp, InitSnow_0, Prec, NRur, NUrb, Area, CNI_0, AntMoist_0, Grow_0,\n CNP_0, Imper,\n ISRR, ISRA)\n for Y in range(NYrs):\n for i in range(12):\n for j in range(DaysMonth[Y][i]):\n if Temp[Y][i][j] > 0 and water[Y][i][j] > 0.01:\n result[Y][i] += urbanqtotal_1[Y][i][j]\n else:\n pass\n return result\n\n\ndef UrbanRunoff_f(NYrs, DaysMonth, Temp, InitSnow_0, Prec, NRur, NUrb, Area, CNI_0, AntMoist_0, Grow_0,\n CNP_0, Imper, ISRR, ISRA):\n return sum(UrbanQTotal_1_f(NYrs, DaysMonth, Temp, InitSnow_0, Prec, NRur, NUrb, Area, CNI_0, AntMoist_0, Grow_0,\n CNP_0, Imper, ISRR, ISRA), axis=2)\n","sub_path":"gwlfe/MultiUse_Fxns/Runoff/UrbanRunoff.py","file_name":"UrbanRunoff.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"57774895","text":"# -*- encoding: utf-8 -*-\nfrom abjad.tools import containertools\nfrom abjad.tools import datastructuretools\nfrom abjad.tools import durationtools\nfrom abjad.tools import mathtools\nfrom abjad.tools import rhythmmakertools\nfrom abjad.tools import selectiontools\nfrom abjad.tools import sequencetools\nfrom experimental.tools.musicexpressiontools.PayloadExpression \\\n import PayloadExpression\n\n\nclass IterablePayloadExpression(PayloadExpression):\n r'''Payload expression.\n\n ::\n\n >>> payload_expression = \\\n ... musicexpressiontools.IterablePayloadExpression(\n ... [(4, 16), (2, 16)])\n\n ::\n\n >>> payload_expression\n IterablePayloadExpression(payload=((4, 16), (2, 16)))\n\n ::\n\n >>> print payload_expression.storage_format\n musicexpressiontools.IterablePayloadExpression(\n payload=((4, 16), (2, 16))\n )\n\n Payload expressions are assumed to evaluate to a list or other iterable.\n '''\n\n ### INTIAILIZER ###\n\n def __init__(self, payload=None):\n from experimental.tools import musicexpressiontools\n assert not isinstance(payload, rhythmmakertools.RhythmMaker)\n assert not isinstance(payload, datastructuretools.StatalServerCursor)\n assert isinstance(payload, (\n str, tuple, list, \n containertools.Container,\n datastructuretools.TypedList,\n musicexpressiontools.DivisionList,\n selectiontools.SliceSelection,\n ))\n if isinstance(payload, list):\n payload = tuple(payload)\n PayloadExpression.__init__(self, payload)\n\n ### SPECIAL METHODS ###\n\n def __and__(self, timespan):\n r'''Logical AND of payload expression and `timespan`.\n\n ::\n\n >>> timespan = timespantools.Timespan((1, 16), (5, 16))\n >>> result = payload_expression & timespan\n\n ::\n\n >>> print result.storage_format\n timespantools.TimespanInventory([\n musicexpressiontools.IterablePayloadExpression(\n payload=(Division('[3, 16]', start_offset=Offset(1, 16)),\n Division('[1, 16]', start_offset=Offset(1, 4)))\n )\n ])\n\n Returns newly constructed payload expression.\n '''\n from experimental.tools import musicexpressiontools\n if not sequencetools.all_are_numbers(self.payload):\n payload = [mathtools.NonreducedFraction(x) for x in self.payload]\n else:\n payload = self.payload\n division_payload_expression = \\\n musicexpressiontools.StartPositionedDivisionPayloadExpression(\n payload=payload, start_offset=0, voice_name='dummy voice name')\n result = division_payload_expression & timespan\n assert len(result) in (0, 1)\n if result:\n divisions = result[0].payload.divisions\n expression = self.new(payload=divisions)\n result[0] = expression\n return result\n\n def __getitem__(self, expr):\n r'''Payload expression get item.\n\n ::\n\n >>> result = payload_expression[:1]\n\n ::\n\n >>> print result.storage_format\n musicexpressiontools.IterablePayloadExpression(\n payload=((4, 16),)\n )\n\n Returns newly constructed payload expression\n with referenced payload.\n '''\n payload = self.payload.__getitem__(expr)\n result = self.new(payload=payload)\n return result\n\n ### PRIVATE METHODS ###\n\n def _duration_helper(self, expression):\n if hasattr(expression, 'duration'):\n return expression.duration\n elif hasattr(expression, 'duration'):\n return expression.duration\n else:\n duration = durationtools.Duration(expression)\n return duration\n\n @staticmethod\n def _durations_to_integers(durations):\n r'''Change `durations` to integers:\n\n ::\n\n >>> durations = [Duration(2, 4), 3, (5, 16)]\n >>> for integer in payload_expression._durations_to_integers(\n ... durations):\n ... integer\n ...\n 8\n 48\n 5\n\n Returns new object of `durations` type.\n '''\n from abjad.tools import durationtools\n # change to nonreduced fractions\n nonreduced_fractions = \\\n durationtools.Duration.durations_to_nonreduced_fractions_with_common_denominator(\n durations)\n # find common denominator\n common_denominator = nonreduced_fractions[0].denominator\n # change to integers\n nonreduced_fractions = [\n common_denominator * nonreduced_fraction \n for nonreduced_fraction in nonreduced_fractions\n ]\n fractions = [\n nonreduced_fraction.reduce() \n for nonreduced_fraction in nonreduced_fractions\n ]\n assert all(fraction.denominator == 1 for fraction in fractions)\n integers = [fraction.numerator for fraction in fractions]\n # return integers\n return integers\n\n ### PUBLIC PROPERTIES ###\n\n @property\n def elements(self):\n r'''Payload expression elements.\n\n ::\n\n >>> payload_expression.elements\n ((4, 16), (2, 16))\n\n Returns tuple.\n '''\n return self.payload[:]\n\n @property\n def payload(self):\n r'''Payload expression payload:\n\n ::\n\n >>> payload_expression.payload\n ((4, 16), (2, 16))\n\n Returns tuple or string.\n '''\n return self._payload\n\n @property\n def storage_format(self):\n r'''Payload expression storage format:\n\n ::\n\n >>> print payload_expression.storage_format\n musicexpressiontools.IterablePayloadExpression(\n payload=((4, 16), (2, 16))\n )\n\n Returns string.\n '''\n return PayloadExpression.storage_format.fget(self)\n\n ### PUBLIC METHODS ###\n\n def evaluate(self):\n r'''Evaluate payload expression.\n\n >>> payload_expression.evaluate()\n IterablePayloadExpression(payload=((4, 16), (2, 16)))\n\n Returns payload expression.\n '''\n return PayloadExpression.evaluate(self)\n\n def partition_by_ratio(self, ratio):\n r'''Partition payload expression by ratio.\n\n ::\n\n >>> result = payload_expression.partition_by_ratio((1, 1))\n\n ::\n\n >>> for element in result:\n ... print element.storage_format\n musicexpressiontools.IterablePayloadExpression(\n payload=((4, 16),)\n )\n musicexpressiontools.IterablePayloadExpression(\n payload=((2, 16),)\n )\n\n Returns list of newly constructed payload expressions.\n '''\n parts = sequencetools.partition_sequence_by_ratio_of_lengths(\n self.payload, ratio)\n result = []\n for part in parts:\n part = self.new(payload=part)\n result.append(part)\n return result\n\n def partition_by_ratio_of_durations(self, ratio):\n r'''Partition payload expression by ratio of durations.\n\n ::\n\n >>> result = \\\n ... payload_expression.partition_by_ratio_of_durations((1, 1))\n\n ::\n\n >>> for element in result:\n ... print element.storage_format\n musicexpressiontools.IterablePayloadExpression(\n payload=((4, 16),)\n )\n musicexpressiontools.IterablePayloadExpression(\n payload=((2, 16),)\n )\n\n Returns newly constructed payload expression.\n '''\n element_durations = [self._duration_helper(x) for x in self.payload]\n element_tokens = self._durations_to_integers(element_durations)\n token_parts = sequencetools.partition_sequence_by_ratio_of_weights(\n element_tokens, ratio)\n part_lengths = [len(x) for x in token_parts]\n duration_parts = sequencetools.partition_sequence_by_counts(\n element_durations, part_lengths)\n element_parts = sequencetools.partition_sequence_by_counts(\n self.payload, part_lengths)\n result = []\n for part in element_parts:\n part = self.new(payload=part)\n result.append(part)\n return result\n\n def reflect(self):\n r'''Reflect payload expression.\n\n ::\n\n >>> result = payload_expression.reflect()\n\n ::\n\n >>> print result.storage_format\n musicexpressiontools.IterablePayloadExpression(\n payload=((2, 16), (4, 16))\n )\n\n Returns newly constructed payload expression.\n '''\n assert isinstance(self.payload, tuple), repr(self.payload)\n payload = type(self.payload)(reversed(self.payload))\n result = self.new(payload=payload)\n return result\n\n def repeat_to_duration(self, duration):\n r'''Repeat payload expression to duration.\n\n ::\n\n >>> result = \\\n ... payload_expression.repeat_to_duration(Duration(13, 16))\n\n ::\n\n >>> print result.storage_format\n musicexpressiontools.IterablePayloadExpression(\n payload=(NonreducedFraction(4, 16),\n NonreducedFraction(2, 16),\n NonreducedFraction(4, 16),\n NonreducedFraction(2, 16),\n NonreducedFraction(1, 16))\n )\n\n Returns newly constructed payload expression.\n '''\n if not sequencetools.all_are_numbers(self.payload):\n payload = [mathtools.NonreducedFraction(x) for x in self.payload]\n else:\n payload = self.payload\n payload = sequencetools.repeat_sequence_to_weight_exactly(\n payload, duration)\n result = self.new(payload=payload)\n return result\n\n def repeat_to_length(self, length):\n r'''Repeat payload expression to length.\n\n ::\n\n >>> result = payload_expression.repeat_to_length(4)\n\n ::\n\n >>> print result.storage_format\n musicexpressiontools.IterablePayloadExpression(\n payload=((4, 16), (2, 16), (4, 16), (2, 16))\n )\n\n Returns newly constructed payload expression.\n '''\n payload = sequencetools.repeat_sequence_to_length(\n self.payload, length)\n result = self.new(payload=payload)\n return result\n\n def rotate(self, n):\n r'''Rotate payload expression.\n\n ::\n\n >>> result = payload_expression.rotate(-1)\n\n ::\n\n >>> print result.storage_format\n musicexpressiontools.IterablePayloadExpression(\n payload=((2, 16), (4, 16))\n )\n\n Returns newly constructed payload expression.\n '''\n payload = sequencetools.rotate_sequence(self.payload, n)\n result = self.new(payload=payload)\n return result\n","sub_path":"abjad/experimental/tools/musicexpressiontools/IterablePayloadExpression.py","file_name":"IterablePayloadExpression.py","file_ext":"py","file_size_in_byte":11151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"378545049","text":"from django.conf.urls import url\r\nfrom django.urls import path\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n\tpath('', views.home, name='home'),\r\n\tpath('about/', views.about, name='about'),\r\n\tpath('contact/', views.contact, name='contact'),\r\n\tpath('contact_lg/', views.contact_lg, name='contact_lg'),\r\n\tpath('contact_lb/', views.contact_lb, name='contact_lb'),\r\n\tpath('contact_n/', views.contact_n, name='contact_n'),\r\n\r\n\r\n\r\n\r\n \r\n]\r\n","sub_path":"pages/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"435989624","text":"class Demod:\n\tdef __init__(self, sample):\n\t\tself.s = sample\n\t\tself.state = 0\n\t\tself.index = 0\n\n\tdef detect(self):\n\t\tcount = 0\n\t\tstate = 0\n\t\tcurrent = 0\n\t\thead = []\n\t\twhile True:\n\t\t\tif self.index == len(self.s):\n\t\t\t\treturn False\n\t\t\tif state == 0:\n\t\t\t\tif self.s[self.index] != 0:\n\t\t\t\t\tcount += 1\n\t\t\t\t\tcurrent = self.s[self.index]\n\t\t\t\t\tstate = 1\n\t\t\telif state == 1:\n\t\t\t\tif self.s[self.index] == current:\n\t\t\t\t\tcount += 1\n\t\t\t\telse:\n\t\t\t\t\t# print(self.index)\n\t\t\t\t\tif count >= 66:\n\t\t\t\t\t\tif count <= 110:\n\t\t\t\t\t\t\thead.append(current)\n\t\t\t\t\t\t\tif len(head) == 3:\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif len(head) == 2:\n\t\t\t\t\t\t\t\thead.append(current)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tprint(\"Too long prefix!:\", self.index, count)\n\t\t\t\t\t\t\tcount = 0\n\t\t\t\t\t\t\tstate = 0\n\t\t\t\t\t\t\tcurrent = 0\n\t\t\t\t\t\t\thead = []\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(\"Too short prefix!:\", self.index, count)\n\t\t\t\t\t\tcount = 0\n\t\t\t\t\t\tstate = 0\n\t\t\t\t\t\tcurrent = 0\n\t\t\t\t\t\thead = []\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tcount = 0\n\t\t\t\t\tif self.s[self.index] == 0:\n\t\t\t\t\t\tstate = 0\n\t\t\t\t\t\tcurrent = 0\n\t\t\t\t\telse:\n\t\t\t\t\t\tcurrent = self.s[self.index]\n\t\t\tself.index += 1\n\n\t\tif head == [1,-1,1]:\n\t\t\treturn True\n\t\telse:\n\t\t\tprint(\"Wrong prefix!:\", head)\n\t\t\treturn False\n\n\tdef read(self):\n\t\tcount = 0\n\t\tstate = 0\n\t\tcurrent = 0\n\t\tpayload = []\n\t\twhile True:\n\t\t\tif self.index == len(self.s):\n\t\t\t\treturn []\n\t\t\tif state == 0:\n\t\t\t\tif self.s[self.index] != 0:\n\t\t\t\t\tcount += 1\n\t\t\t\t\tcurrent = self.s[self.index]\n\t\t\t\t\tstate = 1\n\t\t\telif state == 1:\n\t\t\t\tif self.s[self.index] == current:\n\t\t\t\t\tcount += 1\n\t\t\t\telse:\n\t\t\t\t\t# print(self.index)\n\t\t\t\t\tif count >= 165:\n\t\t\t\t\t\tif count <= 275:\n\t\t\t\t\t\t\tpayload.append(current)\n\t\t\t\t\t\t\tif len(payload) >= 24:\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telif count >= 330 and count <= 550:\n\t\t\t\t\t\t\tpayload.append(current)\n\t\t\t\t\t\t\tpayload.append(current)\n\t\t\t\t\t\t\tif len(payload) >= 24:\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telif count > 550 and len(payload) == 23:\n\t\t\t\t\t\t\tpayload.append(current)\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tprint(\"Ood length of symbol:\", len(payload), self.index, count)\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(\"Too short symbol!:\", self.index, count)\n\t\t\t\t\tcount = 0\n\t\t\t\t\tif self.s[self.index] == 0:\n\t\t\t\t\t\tstate = 0\n\t\t\t\t\t\tcurrent = 0\n\t\t\t\t\telse:\n\t\t\t\t\t\tcurrent = self.s[self.index]\n\t\t\tself.index += 1\n\t\tpayload = payload[:24]\n\t\tout = \"0b\"\n\t\tfor i in range(8):\n\t\t\tsymbol = payload[3*i:3*i+3]\n\t\t\tif symbol == [-1,1,-1]:\n\t\t\t\tout += \"0\"\n\t\t\telif symbol == [1,-1,1]:\n\t\t\t\tout += \"1\"\n\t\t\telse:\n\t\t\t\tprint(\"Wrong symbol:\", symbol)\n\t\t# print(out)\n\t\treturn int(out,2)\n\n\tdef demodulate(self):\n\t\tindex = []\n\t\tpayloads = []\n\t\twhile True:\n\t\t\tif self.detect():\n\t\t\t\tpayload = self.read()\n\t\t\t\tprint(payload)\n\t\t\t\tpayloads.append(payload)\n\t\t\t\tindex.append(self.index)\n\t\t\t\tprint(\"---------------------------------\") \n\t\t\tif self.index == len(self.s):\n\t\t\t\tbreak\n\t\treturn index, payloads","sub_path":"demodulator.py","file_name":"demodulator.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"573943083","text":"# -*- coding: utf-8 -*-\n\nimport logging\nimport random\n\nfrom twisted.internet import defer\nfrom twisted.spread import pb\nfrom client.cltremote import IRemote\nfrom client.cltgui.cltguidialogs import GuiRecapitulatif\nimport EXPERIENCE_NOMParams as pms\nfrom EXPERIENCE_NOMGui import GuiDecision\nimport EXPERIENCE_NOMTexts as texts_EXPERIENCE_NOM_COURT\n\n\nlogger = logging.getLogger(\"le2m\")\n\n\nclass RemoteEXPERIENCE_NOM_COURT(IRemote):\n \"\"\"\n Class remote, remote_ methods can be called by the server\n \"\"\"\n def __init__(self, le2mclt):\n IRemote.__init__(self, le2mclt)\n\n def remote_configure(self, params):\n \"\"\"\n Set the same parameters as in the server side\n :param params:\n :return:\n \"\"\"\n logger.info(u\"{} configure\".format(self._le2mclt.uid))\n for k, v in params.viewitems():\n setattr(pms, k, v)\n\n def remote_newperiod(self, period):\n \"\"\"\n Set the current period and delete the history\n :param period: the current period\n :return:\n \"\"\"\n logger.info(u\"{} Period {}\".format(self._le2mclt.uid, period))\n self.currentperiod = period\n if self.currentperiod <= 1:\n del self.histo[:]\n self.histo_vars = texts_EXPERIENCE_NOM_COURT.get_histo_vars()\n self.histo.append(texts_EXPERIENCE_NOM_COURT.get_histo_head())\n\n def remote_display_decision(self):\n \"\"\"\n Display the decision screen\n :return: deferred\n \"\"\"\n logger.info(u\"{} Decision\".format(self._le2mclt.uid))\n if self._le2mclt.simulation:\n decision = \\\n random.randrange(\n pms.DECISION_MIN,\n pms.DECISION_MAX + pms.DECISION_STEP,\n pms.DECISION_STEP)\n logger.info(u\"{} Send back {}\".format(self._le2mclt.uid, decision))\n return decision\n else: \n defered = defer.Deferred()\n ecran_decision = GuiDecision(\n defered, self._le2mclt.automatique,\n self._le2mclt.screen, self.currentperiod, self.histo)\n ecran_decision.show()\n return defered\n\n def remote_display_summary(self, period_content):\n \"\"\"\n Display the summary screen\n :param period_content: dictionary with the content of the current period\n :return: deferred\n \"\"\"\n logger.info(u\"{} Summary\".format(self._le2mclt.uid))\n self.histo.append([period_content.get(k) for k in self.histo_vars])\n if self._le2mclt.simulation:\n return 1\n else:\n defered = defer.Deferred()\n ecran_recap = GuiRecapitulatif(\n defered, self._le2mclt.automatique, self._le2mclt.screen,\n self.currentperiod, self.histo,\n texts_EXPERIENCE_NOM_COURT.get_text_summary(period_content))\n ecran_recap.show()\n return defered\n","sub_path":"le2m/creator/filestocopy/creator_Remote.py","file_name":"creator_Remote.py","file_ext":"py","file_size_in_byte":2950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"} +{"seq_id":"449719805","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport hashlib\nimport json\nimport os\nfrom os.path import exists\n\nimport pretty_errors\nfrom elasticsearch import Elasticsearch, helpers\nfrom environs import Env\nfrom loguru import logger\n\n\ndef get_md5(s):\n md = hashlib.md5()\n md.update(s.encode('utf-8'))\n return md.hexdigest()\n\n\npretty_errors.activate()\n\nes = Elasticsearch()\n\n\ndef build_index():\n mapping = {\n 'properties': {\n 'book_name': {\n 'type': 'text',\n 'analyzer': 'ik_max_word',\n 'search_analyzer': 'ik_max_word'\n }\n }\n }\n es.indices.delete(index='books', ignore=[400, 404])\n es.indices.create(index='books', ignore=400)\n result = es.indices.put_mapping(\n index='books', doc_type='books', body=mapping)\n logger.debug(result)\n\n es.indices.delete(index='movies', ignore=[400, 404])\n es.indices.create(index='movies', ignore=400)\n result = es.indices.put_mapping(\n index='movies', doc_type='movies', body=mapping)\n logger.debug(result)\n\n\ndef bulk_with_json(jsonFile, doc_type):\n if not exists(jsonFile):\n logger.debug('不存在'+jsonFile)\n return\n # 批量插入数据\n logger.debug(f\"bulk with {jsonFile}\")\n count = 0\n num = 0\n actions = []\n max_count = 2000\n with open(jsonFile, 'r', encoding='utf-8') as f:\n i = 0\n j = 0\n for line in f:\n j += 1\n try:\n action, triple_dict = getAction(doc_type, line)\n i += 1\n count += 1\n actions.append(action)\n except Exception as e:\n logger.error(e)\n logger.debug(f\"!!! {j} th row insert faied: {triple_dict}\")\n continue\n if count >= max_count:\n bulk(actions)\n actions = []\n count = 0\n num += 1\n logger.debug(\"Insert \" + str(num * max_count) + \" records.\")\n bulk(actions)\n logger.info(f'success insert {num * max_count + count} items')\n\n\ndef bulk(actions):\n try:\n helpers.bulk(es, actions)\n except Exception as e:\n logger.error(e)\n for action in actions:\n try:\n es.index(index=action['_index'], doc_type=action['_type'],\n body=action[\"_source\"],\n id=action['_id'])\n except Exception as e:\n logger.error(e)\n\n\ndef getAction(doc_type, line):\n d = json.loads(line)\n triple_dict = d if not d.get('_source') else d.get('_source')\n triple_dict['book_name_length'] = triple_dict.get(\n 'book_name_length', len(triple_dict['book_name']))\n # 如果数据量小可以用index的方法一条条插入\n # 这里index,doc_type就等于上一步建立索引所用的名称\n # es.index(index='index_test',doc_type='doc_type',body=triple_dict)\n action = {\n \"_index\": doc_type,\n \"_type\": doc_type,\n \"_id\": d.get('_id') if d.get('_id') else get_md5(triple_dict['book_url']),\n \"_source\": triple_dict\n }\n return action, triple_dict\n\n\nif __name__ == '__main__':\n env = Env()\n env.read_env()\n InCrontab = env.bool(\"InCrontab\", False)\n if InCrontab:\n book = 'CrontabBooks.json'\n movie = 'CrontabMovies.json'\n else:\n book = 'books.json'\n movie = 'movies.json'\n bulk_with_json(jsonFile='../helloScrapy/' + book, doc_type='books')\n bulk_with_json(jsonFile='../helloScrapy/' + movie, doc_type='movies')\n os.system('rm ../helloScrapy/' + book)\n os.system('rm ../helloScrapy/' + movie)\n\n # 建立index\n # build_index()\n # bulk_with_json(jsonFile='../movies.json', doc_type='movies')\n # bulk_with_json(jsonFile='../books.json', doc_type='books')\n\n # bulk_with_json(jsonFile='axcs.json', doc_type='books')\n # bulk_with_json(jsonFile='bttwo.json', doc_type='movies')\n # bulk_with_json(jsonFile='ddrk.json', doc_type='movies')\n # bulk_with_json(jsonFile='dvdhd.json', doc_type='movies')\n # bulk_with_json(jsonFile='itsck.json', doc_type='movies')\n # bulk_with_json(jsonFile='java1234.json', doc_type='books')\n # bulk_with_json(jsonFile='shudan1.json', doc_type='books')\n # bulk_with_json(jsonFile='volmoe1.json', doc_type='books')\n # bulk_with_json(jsonFile='xiangzhan.json', doc_type='books')\n # bulk_with_json(jsonFile='zhenbuka.json', doc_type='movies')\n","sub_path":"other/es store data.py","file_name":"es store data.py","file_ext":"py","file_size_in_byte":4474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"82"}