diff --git "a/3055.jsonl" "b/3055.jsonl" new file mode 100644--- /dev/null +++ "b/3055.jsonl" @@ -0,0 +1,710 @@ +{"seq_id":"37234286","text":"import re\nimport urllib\n\nurls = [\"http://google.com\", \"http://nytimes\", \"http://CNN.com\"]\n\nregex = '(.+?)'\npattern = re.compile(regex)\n\ni = 0\nwhile i < len(urls):\n htmlfile = urllib.urlopen(urls[i])\n htmltext = htmlfile.read()\n titles = re.findall(pattern, htmltext)\n print(titles)\n print(htmltext[0:100])\n i += 1\n","sub_path":"python3/16_Web_Services/others/03_web_scrapping/webScraping2.py","file_name":"webScraping2.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"473497921","text":"import streamlit as st\nimport pandas as pd\nimport altair as alt\nimport streamlit.components.v1 as components\n\n\n#lista de emotivons\n# https://raw.githubusercontent.com/omnidan/node-emoji/master/lib/emoji.json\nst.set_page_config(page_title='Grupo de Python - Visualização de dados', page_icon=':moneybag', layout='wide', )\n\n#pega o dataset completo\ndata = pd.read_csv('data.csv', sep=\";\", quotechar='\"', dtype='unicode')\n# data.info()\ndata['Valor FOB (US$)'] = (data['Valor FOB (US$)'].astype(str).astype('int64'))\n\n# identificando os estados existentes\ntodos_estados = data['UF do Produto'].unique().tolist()\ntodos_estados.sort()\n\n# função para auxiliar na normalização do valor\ndef f(s):\n return s/s.max()\n\ndef funEstadoEscolhido(tabela, estados):\n umEstado = st.selectbox('Choose on state to compare', (estados), index=0 )\n if umEstado != '':\n data_um_estado = data[data['UF do Produto'] == umEstado]\n anoValorUmEstado = data_um_estado.groupby(['Ano'],as_index=False)['Valor FOB (US$)'].agg('sum')\n\n # prepara a informação do estado escolhido\n max = anoValorUmEstado['Valor FOB (US$)'].max()\n # print(max)\n # cria uma coluna do Brasil\n tabela['FOB ' + umEstado] = anoValorUmEstado['Valor FOB (US$)'].apply(lambda x: x/max)\n # st.dataframe(tabela)\n return tabela\n\n\n\ndef main():\n st.title(\"Grupo de Python - Visualização de dados com Streamlit\")\n st.subheader(\"International Trade Monitor for Brazil\")\n st.subheader(\"Trajectory of Brazilian states exports between 1997 to 2020\")\n\n # apresentação do gráfico completo\n anoEstado = data.groupby(['UF do Produto'],as_index=False)['Valor FOB (US$)'].agg('sum')\n # criando um gráfico geral\n c = alt.Chart(anoEstado).mark_circle().encode(\n x='UF do Produto', y='Valor FOB (US$)')\n st.altair_chart(c, use_container_width=True)\n\n # outros modelos de gráficos \n # st.line_chart(data=anoEstado, use_container_width=True)\n # fig, ax = plt.subplots()\n # ax.hist(anoEstado, bins=26)\n # st.pyplot(fig)\n\n # inicia a distribuição por estado\n st.subheader('Total by state')\n # cria 2 colunas\n col1, col2 = st.beta_columns((3,8))\n \n estados = ['All']\n soEstados = ['']\n for i in todos_estados:\n estados.append(i)\n soEstados.append(i)\n estado = col1.radio('State', (estados), index=0 )\n if estado == 'All':\n data_estado = data.copy()\n else:\n data_estado = data[data['UF do Produto'] == estado]\n\n anoValor = data_estado.groupby(['Ano'],as_index=False)['Valor FOB (US$)'].agg('sum') \n # st.dataframe(anoValor) \n grupoValor = data_estado.groupby(['Descrição CGCE Nível 1'], as_index=False)['Valor FOB (US$)'].agg('sum')\n\n # criando um gráfico de ano x valor por estado ou geral\n c = alt.Chart(anoValor).mark_circle().encode(\n x='Ano', y='Valor FOB (US$)')\n col2.altair_chart(c, use_container_width=True)\n\n # criando um gráfico de ano x tipo por estado ou geral\n c = alt.Chart(grupoValor).mark_circle().encode(\n x='Descrição CGCE Nível 1', y='Valor FOB (US$)')\n col2.altair_chart(c, use_container_width=True)\n\n\n st.subheader('Comparing Brazil with one state (normalized data)')\n # fazendo comparação entre o global e um estado\n # pega o maior valor do geral\n max = anoValor['Valor FOB (US$)'].max()\n # print(max)\n # cria uma coluna do Brasil\n anoValor['FOB Brazil'] = anoValor['Valor FOB (US$)'].apply(lambda x: x/max)\n # st.dataframe(anoValor)\n anoValor = funEstadoEscolhido(anoValor, soEstados)\n # criando um gráfico comparativo entre Brasil e um estado\n # st.dataframe(anoValor)\n anoValor.drop('Valor FOB (US$)', inplace=True, axis='columns')\n anoValor.set_index('Ano', inplace = True)\n st.line_chart(anoValor)\n\n components.html(\"\"\"
\"\"\")\n st.write(\"Git: https://github.com/htsnet/international-trade-monitor-for-brazil\")\n\nif __name__ == '__main__':\n\tmain() ","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"309937256","text":"from flask import Flask, render_template, request, redirect, url_for\nfrom todo_app.flask_config import Config\nfrom todo_app.data import trello_items as trello\n\n\napp = Flask(__name__)\napp.config.from_object(Config)\n\n\n@app.route('/')\ndef index():\n items = trello.get_trello_cards()\n return render_template('index.html', items = items)\n\n@app.route('/items/new', methods=[\"POST\"])\ndef add_item():\n title = request.form['title']\n trello.add_item_trello(title)\n return redirect(url_for('index'))\n \n\n@app.route('/items//complete', methods=[\"POST\"])\ndef complete_item(id):\n trello.complete_item_trello(id)\n return redirect(url_for('index'))\n\n@app.route('/items//start', methods=[\"POST\"])\ndef start_item(id):\n trello.start_item_trello(id)\n return redirect(url_for('index'))\n\n@app.route('/items//uncomplete', methods=[\"POST\"])\ndef uncomplete_item(id):\n trello.uncomplete_item_trello(id)\n return redirect(url_for('index'))\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"todo_app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"311071694","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport cv2\nimport numpy as np\nimport os,sys\nos.environ['GLOG_minloglevel'] = '2'\nimport caffe\nimport time\nimport faceutils as fu\nimport math\nimport importlib\n\nclass facelandmark5p():\n\n\tdef __init__(self,dl_framework=\"caffe\",device=\"gpu\"):\n\t\tself.curfilepath=os.path.dirname(os.path.realpath(__file__))\n\t\tsys.path.append(\"%s/FaceLandmark/method/%s/\"%(self.curfilepath,dl_framework))\n\t\tfacelandmark_module=importlib.import_module(\"facelandmark5p_base\")\n\t\tself.facelandmark5p_base=facelandmark_module.facelandmark5p_base(device=device)\n\n\n\tdef getlandmark(self,image,landmarkscale=0,**kwargs):\n\t\t'''\n\t\tinput image must be face crop image\n\t\t'''\n\t\treturn self.facelandmark5p_base.getlandmark(image,landmarkscale=0,**kwargs)\n\n\tdef face_align(self,img,**kwargs):\n\t\tfacebox=kwargs.get(\"facebox\",fu.Facerect([0,0,img.shape[1],img.shape[0]]))\n\t\troi_face=facebox.get_roi(img)\n\t\tlandmark=self.getlandmark( roi_face )\n\t\tdegree=math.atan2((landmark[1][1]-landmark[0][1]),(landmark[1][0]-landmark[0][0]))*180/3.14\n\t\tlandmark=facebox.reprojectlandmark(landmark,scale=0)\n\t\trotateimg,rotate_facebox,rotate_landmark=fu.Rotate(img,degree,facebox=facebox,landmark=landmark)\n\n\t\tdistance_list=[]\n\t\tfor l in landmark:\n\t\t\td1=math.sqrt( (landmark[2][0]-l[0])**2+(landmark[2][1]-l[1])**2 )\n\t\t\tdistance_list.append(d1)\n\t\textend_l= int( max(distance_list) )\n\n\t\tadjust_bbox=fu.Face2point((rotate_landmark[0][0]-1.2*extend_l,rotate_landmark[0][1]-1.4*extend_l,rotate_landmark[4][0]+1.2*extend_l,rotate_landmark[4][1]+1.2*extend_l))\n\t\trotateface=adjust_bbox.get_roi(rotateimg)\n\t\treturn rotateface\n\n\tdef face_runphase_align(self,img,**kwargs):\n\t\tfacebox=kwargs.get(\"facebox\",fu.Facerect([0,0,img.shape[1],img.shape[0]]))\n\t\troi_face=facebox.get_roi(img)\n\t\tlandmark=self.getlandmark( roi_face )\n\t\tdegree=math.atan2((landmark[1][1]-landmark[0][1]),(landmark[1][0]-landmark[0][0]))*180/3.14\n\t\tlandmark=facebox.reprojectlandmark(landmark,scale=0)\n\t\trotateimg,rotate_facebox,rotate_landmark=fu.Rotate(img,degree,facebox=facebox,landmark=landmark)\n\n\t\tdistance_list=[]\n\t\tfor l in landmark:\n\t\t\td1=math.sqrt( (landmark[2][0]-l[0])**2+(landmark[2][1]-l[1])**2 )\n\t\t\tdistance_list.append(d1)\n\t\textend_l= int( max(distance_list) )\n\n\t\tadjust_bbox=fu.Face2point((rotate_landmark[0][0]-(0.4*extend_l),rotate_landmark[0][1]-(0.4*extend_l),rotate_landmark[4][0]+(0.4*extend_l),rotate_landmark[4][1]+(0.4*extend_l) ))\n\t\trotateface=adjust_bbox.get_roi(rotateimg)\n\t\treturn rotateface\n\n\n\n\tdef test(self):\n\t\timg=cv2.imread(\"%s/pictures/test_img/compare_2.jpg\"%self.curfilepath)\n\t\tlandmark=self.getlandmark(img)\n\t\tfu.showimg(img,landmarks=[landmark] )\n\n\nif __name__ == \"__main__\":\n\n\ttest=facelandmark5p()\n\ttest.test()\n","sub_path":"lib/facelandmark5p.py","file_name":"facelandmark5p.py","file_ext":"py","file_size_in_byte":2770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"93368390","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n/**\n * Raphael Delhome - september 2017\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n * \n * This library 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 GNU\n * Library General Public License for more details.\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, see .\n */\n\"\"\"\n\n# This script aims to validate a trained neural network model in order to read\n# street scene images produced by Mapillary\n# (https://www.mapillary.com/dataset/vistas)\n\nimport json\nimport logging\nimport math\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd\nimport tensorflow as tf\nimport sys\nimport time\n\nimport bpmll # Multilabel classification loss\nimport cnn_layers\nimport dashboard_building\nimport utils\n\nif __name__ == '__main__':\n # call the script following format 'python3 cnn_train.py configfile.json'\n if len(sys.argv) != 2:\n utils.logger.error(\"Usage: python3 cnn_train.py \")\n sys.exit(-1)\n NETWORK_NAME = sys.argv[1]\n # image dimensions (width, height, number of channels)\n IMG_SIZE = (768, 576)\n IMAGE_HEIGHT = IMG_SIZE[1]\n IMAGE_WIDTH = IMG_SIZE[0]\n NUM_CHANNELS = 3 # Colored images (RGB)\n\n utils.make_dir('../data/checkpoints')\n utils.make_dir('../data/checkpoints/'+NETWORK_NAME)\n\n utils.logger.info(\"Model {} validation\".format(NETWORK_NAME))\n config_file_name = NETWORK_NAME + \".json\"\n with open(os.path.join(\"..\", \"models\", \"to_run\", config_file_name)) as config_file:\n cnn_hyperparam = json.load(config_file)\n\n # number of output classes\n N_CLASSES = 66\n # number of images per batch\n BATCH_SIZE = 20\n N_BATCHES = int(len(os.listdir(os.path.join(\"..\", \"data\", \"validation\", \"images\"))) / BATCH_SIZE)\n # printing frequency during training\n SKIP_STEP = 10\n\n # Data recovering\n train_image_batch, train_label_batch, train_filename_batch = \\\n cnn_layers.prepare_data(IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS,\n BATCH_SIZE, \"training\", \"training_data_pipe\")\n validation_image_batch, validation_label_batch, validation_filename_batch =\\\n cnn_layers.prepare_data(IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS,\n BATCH_SIZE, \"validation\", \"validation_data_pipe\")\n\n X = tf.placeholder(tf.float32, [None, IMAGE_HEIGHT, IMAGE_WIDTH,\n NUM_CHANNELS], name='X')\n Y = tf.placeholder(tf.float32, [None, N_CLASSES], name='Y')\n\n # Model building\n last_fc, last_fc_layer_dim = cnn_layers.convnet_building(X, cnn_hyperparam,\n IMG_SIZE[0],\n IMG_SIZE[1],\n NUM_CHANNELS,\n 1.0,\n NETWORK_NAME)\n \n # Output building\n with tf.variable_scope(NETWORK_NAME + '_sigmoid_linear') as scope:\n # Create weights and biases for the final fully-connected layer\n w = tf.get_variable('weights', [last_fc_layer_dim, N_CLASSES],\n initializer=tf.truncated_normal_initializer())\n b = tf.get_variable('biases', [N_CLASSES],\n initializer=tf.random_normal_initializer())\n # Compute logits through a simple linear combination\n logits = tf.add(tf.matmul(last_fc, w), b)\n # Compute predicted outputs with sigmoid function\n Y_raw_predict = tf.nn.sigmoid(logits)\n Y_predict = tf.to_int32(tf.round(Y_raw_predict))\n\n # Loss function design\n with tf.name_scope(NETWORK_NAME + '_loss'):\n # Cross-entropy between predicted and real values: we use sigmoid instead\n # of softmax as we are in a multilabel classification problem\n entropy = tf.nn.sigmoid_cross_entropy_with_logits(labels=Y, logits=logits)\n loss = tf.reduce_mean(entropy, name=\"loss\")\n bpmll_loss = bpmll.bp_mll_loss(Y, Y_raw_predict)\n\n # Declare a saver instance\n saver = tf.train.Saver()\n\n # Running the neural network\n with tf.Session() as sess:\n # Initialize the tensorflow variables\n # To visualize using TensorBoard\n # tensorboard --logdir=\"../graphs/\"+NETWORK_NAME --port 6006)\n sess.run(tf.global_variables_initializer())\n # Create folders to store checkpoints\n ckpt = tf.train.get_checkpoint_state(os.path.dirname('../data/checkpoints/' + NETWORK_NAME + '/checkpoint'))\n # If that checkpoint exists, restore from checkpoint\n if ckpt and ckpt.model_checkpoint_path:\n utils.logger.info(\"Recover model state from {}\".format(ckpt.model_checkpoint_path))\n saver.restore(sess, ckpt.model_checkpoint_path)\n\n # Initialize threads to begin batching operations\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord)\n\n # Train the model\n start_time = time.time()\n dashboard = []\n best_accuracy = 0\n for index in range(N_BATCHES):\n X_val_batch, Y_val_batch = sess.run([validation_image_batch,\n validation_label_batch])\n Y_pred, loss_batch, bpmll_l = sess.run([Y_predict, loss, bpmll_loss],\n feed_dict={X: X_val_batch,\n Y: Y_val_batch})\n dashboard_batch = dashboard_building.dashboard_building(Y_val_batch, Y_pred)\n dashboard_batch.insert(0, bpmll_l)\n dashboard_batch.insert(0, loss_batch)\n dashboard_batch.insert(0, index)\n dashboard.append(dashboard_batch)\n\n utils.logger.info(\"\"\"Step {}: loss = {:5.3f}, accuracy={:1.3f}, precision={:1.3f}, recall={:1.3f}\"\"\".format(index, loss_batch, dashboard_batch[4], dashboard_batch[5], dashboard_batch[6]))\n\n utils.logger.info(\"Validation Finished!\")\n utils.logger.info(\"Total time: {:.2f} seconds\".format(time.time() - start_time))\n\n # The results are stored as a pandas dataframe and saved on the file\n # system\n dashboard_columns = [\"epoch\", \"loss\", \"bpmll_loss\", \"hamming_loss\",\n \"accuracy\", \"precision\", \"recall\", \"F_measure\"]\n dashboard_columns_by_label = [[\"accuracy_label\"+str(i),\n \"precision_label\"+str(i),\n \"recall_label\"+str(i)]\n for i in range(len(Y_val_batch[0]))]\n dashboard_columns_by_label = utils.unnest(dashboard_columns_by_label)\n dashboard_columns = dashboard_columns + dashboard_columns_by_label\n param_history = pd.DataFrame(dashboard, columns = dashboard_columns)\n param_history = param_history.set_index(\"epoch\")\n utils.make_dir(os.path.join(\"..\", \"data\", \"results\"))\n result_file_name = os.path.join(\"..\", \"data\", \"results\",\n NETWORK_NAME + \"_validation.csv\")\n param_history.to_csv(result_file_name, index=True)\n\n # Stop the threads used during the process\n coord.request_stop()\n coord.join(threads)\n","sub_path":"sources/cnn_validation.py","file_name":"cnn_validation.py","file_ext":"py","file_size_in_byte":7817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"245856340","text":"import os\nimport nltk\nimport string\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\n\n# find all the folders and set up nltk\ndirectory = \"./DB/\"\nusers = os.listdir(directory)\n\nnltk.download('stopwords')\nnltk.download('punkt')\nstop_words = set(stopwords.words('english'))\nstop_words.update(list(string.punctuation))\nstop_words.update('Subject')\n\n# obtain documents\nuser_folders = ['sent/'] #, 'sent_items/']\nd_user = []\nfor user in users:\n print(user)\n for folder in user_folders:\n fileList = os.listdir(directory + user + '/' + folder)\n for file in fileList:\n fp = open(directory + user + '/' + folder + '/' + file, 'r')\n \n # skip unwanted lines\n document = []\n line = fp.readline()\n while 'Subject' not in line:\n line = fp.readline()\n line = fp.readline()\n while 'Subject' not in line:\n line = fp.readline()\n \n tokens = word_tokenize(line)\n tokens.extend(word_tokenize(fp.read()))\n document = list(set(tokens))\n document = [w.lower() for w in document if w.lower() not in stop_words]\n d_user.append(document)\n break\n\n\nprint(d_user[1])\n \n","sub_path":"Enron Email Database/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"356229038","text":"# coding: utf-8\n\"\"\"\nТренер классификатора шаблонов интерпретации для чатбота\n03.08.2019 первая реализация\n03.08.2019 добавлен вариант архитектуры CRF\n15.09.2019 переход на word_embeddings.WordEmbeddings, чтобы чатбот мог использовать KeyedVectors.load(mmap='r')\n\"\"\"\n\nfrom __future__ import print_function\nimport numpy as np\nimport argparse\nimport io\nimport os\nimport json\nimport itertools\nimport logging\n\nfrom sklearn.model_selection import cross_val_score\nimport sklearn.metrics\nfrom sklearn.model_selection import StratifiedKFold\nimport tqdm\n\nimport keras.callbacks\nfrom keras import backend as K\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping\nfrom keras.layers import Conv1D, GlobalMaxPooling1D, GlobalAveragePooling1D, AveragePooling1D\nfrom keras.layers import Input\nfrom keras.layers import Lambda\nfrom keras.layers import recurrent\nfrom keras.layers import Dropout\nfrom keras.layers.core import RepeatVector\nfrom keras.layers.core import Dense\nfrom keras.layers.merge import concatenate, add, multiply\nfrom keras.layers.wrappers import Bidirectional\nfrom keras.models import Model\nfrom keras.models import model_from_json\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers import Flatten\nimport keras.regularizers\nfrom keras.wrappers.scikit_learn import KerasClassifier\n\nimport keras_contrib\nfrom keras_contrib.layers import CRF\nfrom keras_contrib.losses import crf_loss\nfrom keras_contrib.metrics import crf_viterbi_accuracy\nimport keras_contrib.optimizers\n\nfrom ruchatbot.utils.tokenizer import Tokenizer\nimport ruchatbot.utils.console_helpers\nimport ruchatbot.utils.logging_helpers\nfrom word_embeddings import WordEmbeddings\n\n\ndef get_params_str(model_params):\n return ' '.join('{}={}'.format(k, v) for (k, v) in model_params.items())\n\n\ndef prepare_phrase(phrase):\n for delim in u'?,!«»\"()':\n phrase = phrase.replace(delim, ' ' + delim + ' ')\n\n if phrase[-1] == '.':\n phrase = phrase[:-1]\n phrase = phrase.replace(' ', ' ').strip()\n return phrase\n\n\ndef instance_accuracy(y_true, y_pred):\n nb_good = sum(np.array_equal(y1, y2) for (y1, y2) in zip(y_true, y_pred))\n nb_total = len(y_true)\n return float(nb_good) / nb_total\n\n\nclass Sample(object):\n def __init__(self, question, short_answer, expanded_answer, template):\n self.question = question\n self.short_answer = short_answer\n self.expanded_answer = expanded_answer\n self.template = template\n self.question_words = None\n self.short_answer_words = None\n self.expanded_answer_words = None\n\n\nPAD_WORD = u''\nBEG_TOKEN = ''\nEND_TOKEN = ''\n\n\ndef load_data(dataset_path, tokenizer):\n samples = []\n max_inputseq_len = 0\n max_outputseq_len = 0\n all_labels = set()\n all_terms = set([BEG_TOKEN, END_TOKEN, PAD_WORD])\n logging.info('Loading dataset \"%s\"', dataset_path)\n with io.open(dataset_path, 'r', encoding='utf-8') as rdr:\n header = rdr.readline()\n for line in rdr:\n tx = line.strip().split('\\t')\n all_labels.add(tx[3])\n question_words = tokenizer.tokenize(tx[0])\n short_answer_words = tokenizer.tokenize(tx[1])\n expanded_answer_words = tokenizer.tokenize(tx[2])\n max_inputseq_len = max(max_inputseq_len, len(question_words), len(short_answer_words))\n max_outputseq_len = max(max_outputseq_len, len(expanded_answer_words))\n sample = Sample(tx[0], tx[1], tx[2], tx[3])\n sample.question_words = question_words\n sample.short_answer_words = short_answer_words\n sample.expanded_answer_words = expanded_answer_words\n samples.append(sample)\n\n terms = tx[3].split()\n all_terms.update(terms)\n\n label2index = dict((l, i) for i, l in enumerate(all_labels))\n term2index = dict((t, i) for i, t in enumerate(all_terms))\n\n computed_params = {'max_inputseq_len': max_inputseq_len,\n 'max_outputseq_len': max_outputseq_len,\n 'label2index': label2index,\n 'nb_labels': len(all_labels),\n 'term2index': term2index,\n 'nb_terms': len(all_terms)}\n\n return samples, computed_params\n\n\ndef lpad_wordseq(words, n):\n \"\"\" Слева добавляем пустые слова, чтобы длина строки words стала равна n \"\"\"\n return list(itertools.chain(itertools.repeat(PAD_WORD, n-len(words)), words))\n\n\ndef rpad_wordseq(words, n):\n \"\"\" Справа добавляем пустые слова, чтобы длина строки words стала равна n \"\"\"\n return list(itertools.chain(words, itertools.repeat(PAD_WORD, n-len(words))))\n\n\ndef pad_wordseq(words, n, padding):\n if padding == 'right':\n return rpad_wordseq(words, n)\n else:\n return lpad_wordseq(words, n)\n\n\ndef pad_for_crf(terms, max_len):\n terms2 = [BEG_TOKEN] + terms + [END_TOKEN] + [PAD_WORD]*(max_len-len(terms)-2)\n return terms2\n\n\ndef load_embeddings(wordchar2vector_path, word2vector_path, computed_params):\n embeddings = WordEmbeddings.load_word_vectors(wordchar2vector_path, word2vector_path)\n computed_params['word_dims'] = embeddings.get_vector_size()\n computed_params['word2vec'] = embeddings\n return embeddings\n\n\ndef vectorize_words(words, M, irow, word2vec):\n for iword,word in enumerate( words ):\n if word in word2vec:\n M[irow, iword, :] = word2vec[word]\n\n\ndef vectorize_samples(samples, params, computed_params):\n padding = params['padding']\n nb_samples = len(samples)\n max_inputseq_len = computed_params['max_inputseq_len']\n max_outputseq_len = computed_params['max_outputseq_len']\n word_dims = computed_params['word_dims']\n w2v = computed_params['word2vec']\n nb_labels = computed_params['nb_labels']\n label2index = computed_params['label2index']\n term2index = computed_params['term2index']\n nb_terms = computed_params['nb_terms']\n\n if params['arch'] == 'bilstm':\n X1_data = np.zeros((nb_samples, max_inputseq_len, word_dims), dtype=np.float32)\n X2_data = np.zeros((nb_samples, max_inputseq_len, word_dims), dtype=np.float32)\n y_data = np.zeros((nb_samples, nb_labels), dtype=np.bool)\n\n for isample, sample in enumerate(samples):\n words1 = pad_wordseq(sample.question_words, max_inputseq_len, padding)\n vectorize_words(words1, X1_data, isample, w2v)\n\n words2 = pad_wordseq(sample.short_answer_words, max_inputseq_len, padding)\n vectorize_words(words2, X2_data, isample, w2v)\n\n y_data[isample, label2index[sample.template]] = 1\n elif params['arch'] == 'crf':\n max_len = max(max_inputseq_len, max_outputseq_len)+2\n\n X1_data = np.zeros((nb_samples, max_len, word_dims), dtype=np.float32)\n X2_data = np.zeros((nb_samples, max_len, word_dims), dtype=np.float32)\n y_data = np.zeros((nb_samples, max_len, nb_terms), dtype=np.bool)\n\n for isample, sample in enumerate(samples):\n words1 = pad_wordseq(sample.question_words, max_len, padding)\n vectorize_words(words1, X1_data, isample, w2v)\n\n words2 = pad_wordseq(sample.short_answer_words, max_len, padding)\n vectorize_words(words2, X2_data, isample, w2v)\n\n for iterm, term in enumerate(pad_for_crf(sample.template.split(), max_len)):\n y_data[isample, iterm, term2index[term]] = 1\n\n return X1_data, X2_data, y_data\n\n\ndef create_model(computed_params, model_params):\n max_inputseq_len = computed_params['max_inputseq_len']\n max_outputseq_len = computed_params['max_outputseq_len']\n\n nb_labels = computed_params['nb_labels']\n word_dims = computed_params['word_dims']\n\n if model_params['arch'] == 'crf':\n max_len = max(max_inputseq_len, max_outputseq_len) + 2\n input1 = Input(shape=(max_len, word_dims,), dtype='float32', name='input1')\n input2 = Input(shape=(max_len, word_dims,), dtype='float32', name='input2')\n else:\n input1 = Input(shape=(max_inputseq_len, word_dims,), dtype='float32', name='input1')\n input2 = Input(shape=(max_inputseq_len, word_dims,), dtype='float32', name='input2')\n\n optimizer = model_params['optimizer']\n arch = model_params['arch']\n if arch == 'bilstm':\n net1 = Bidirectional(recurrent.LSTM(units=model_params['rnn_size'],\n dropout=model_params['dropout_rate'],\n return_sequences=False))(input1)\n\n net2 = Bidirectional(recurrent.LSTM(units=model_params['rnn_size'],\n dropout=model_params['dropout_rate'],\n return_sequences=False))(input2)\n\n net = concatenate([net1, net2])\n elif arch in ('crf', 'rnn_seq'):\n net1 = Bidirectional(recurrent.LSTM(units=model_params['rnn_size'],\n dropout=model_params['dropout_rate'],\n return_sequences=False))(input1)\n\n net2 = Bidirectional(recurrent.LSTM(units=model_params['rnn_size'],\n dropout=model_params['dropout_rate'],\n return_sequences=False))(input2)\n\n net = concatenate([net1, net2])\n else:\n raise NotImplementedError()\n\n if model_params['dense1'] > 0:\n net = Dense(units=model_params['dense1'], activation='sigmoid')(net)\n\n if arch == 'crf':\n net = RepeatVector(max_len)(net)\n net = recurrent.LSTM(model_params['rnn_size'], return_sequences=True)(net)\n net = CRF(units=computed_params['nb_terms'], sparse_target=False)(net)\n model = Model(inputs=[input1, input2], outputs=net)\n model.compile(loss=crf_loss, optimizer=optimizer, metrics=[crf_viterbi_accuracy])\n elif arch == 'bilstm':\n net = Dense(units=nb_labels, activation='softmax')(net)\n model = Model(inputs=[input1, input2], outputs=net)\n model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy'])\n\n return model\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--run_mode', type=str, default='gridsearch', choices='train query gridsearch report'.split())\n parser.add_argument('--tmp', type=str, default='../tmp')\n parser.add_argument('--dataset', default='../tmp/interpreter_templates.tsv')\n parser.add_argument('--wordchar2vector', type=str, default='../tmp/wc2v.kv', help='path to wordchar2vector model dataset')\n parser.add_argument('--word2vector', type=str, default='../tmp/w2v.kv', help='path to word2vector model file')\n\n args = parser.parse_args()\n tmp_dir = args.tmp\n run_mode = args.run_mode\n dataset_path = args.dataset\n\n wordchar2vector_path = args.wordchar2vector\n word2vector_path = os.path.expanduser(args.word2vector)\n\n # настраиваем логирование в файл\n ruchatbot.utils.logging_helpers.init_trainer_logging(os.path.join(tmp_dir, 'nn_interpreter_new1.log'))\n logging.debug('Started run_mode=%s', run_mode)\n\n weights_file = os.path.abspath(os.path.join(tmp_dir, 'nn_interpreter_new1.weights'))\n arch_file = os.path.abspath(os.path.join(tmp_dir, 'nn_interpreter_new1.arch'))\n config_file = os.path.abspath(os.path.join(tmp_dir, 'nn_interpreter_new1.config'))\n\n best_path = os.path.join(tmp_dir, 'nn_interpreter_new1.best_params.json')\n\n tokenizer = ruchatbot.utils.tokenizer.Tokenizer()\n tokenizer.load()\n\n if run_mode == 'gridsearch':\n best_params = None\n best_score = 0.0\n\n samples, computed_params = load_data(dataset_path, tokenizer)\n load_embeddings(wordchar2vector_path, word2vector_path, computed_params)\n sample_labels = [sample.template for sample in samples]\n\n model_params = dict()\n crossval_count = 0\n\n for padding in ['right']:\n model_params['padding'] = padding\n for arch in ['crf']: # 'rnn_seq', 'crf', 'bilstm'\n model_params['arch'] = arch\n X1_data, X2_data, y_data = vectorize_samples(samples, model_params, computed_params)\n\n for batch_size in [50]:\n for epochs in [40, 50, 60]:\n for optimizer in ['nadam']: # 'rmsprop', 'adam',\n for rnn_size in [100, 200]:\n for dropout_rate in [0.0]:\n for dense1 in [0]:\n model_params['batch_size'] = batch_size\n model_params['epochs'] = epochs\n model_params['padding'] = padding\n model_params['optimizer'] = optimizer\n model_params['rnn_size'] = rnn_size\n model_params['dropout_rate'] = dropout_rate\n model_params['dense1'] = dense1\n\n kf = StratifiedKFold(n_splits=5)\n scores = []\n crossval_count += 1\n for ifold, (train_index, test_index) in enumerate(kf.split(samples, sample_labels)):\n logging.info('KFold[%d]', ifold)\n X1_train = X1_data[train_index]\n X2_train = X2_data[train_index]\n y_train = y_data[train_index]\n\n X1_test = X1_data[test_index]\n X2_test = X2_data[test_index]\n y_test = y_data[test_index]\n\n model = create_model(computed_params, model_params)\n model.fit({'input1': X1_train, 'input2': X2_train}, y_train,\n batch_size=batch_size, epochs=epochs, verbose=2)\n y_pred = model.predict({'input1': X1_test, 'input2': X2_test}, verbose=0)\n\n max_len = max(computed_params['max_inputseq_len'], computed_params['max_outputseq_len']) + 2\n y_true2 = np.argmax(y_test, axis=-1).reshape(len(y_test)*max_len)\n y_pred2 = np.argmax(y_pred, axis=-1).reshape(len(y_test)*max_len)\n\n #score = sklearn.metrics.accuracy_score(y_true=y_true2, y_pred=y_pred2)\n score = instance_accuracy(y_true=np.argmax(y_test, axis=-1), y_pred=np.argmax(y_pred, axis=-1))\n logging.info('KFold[%d] score=%f', ifold, score)\n\n scores.append(score)\n\n score = np.mean(scores)\n score_std = np.std(scores)\n logging.info('Crossvalidation #%d score=%f std=%f', crossval_count, score, score_std)\n\n if score > best_score:\n logging.info('!!! NEW BEST !!! score=%f for %s', score, get_params_str(model_params))\n best_score = score\n best_params = model_params.copy()\n with open(best_path, 'w') as f:\n json.dump(best_params, f, indent=4)\n else:\n logging.info('No improvement over current best_score=%f', best_score)\n\n logging.info('All done, best_score=%f params=%s', best_score, get_params_str(best_params))\n elif run_mode == 'train':\n with open(best_path, 'r') as f:\n model_params = json.load(f)\n logging.info('Will train using params: %s', get_params_str(model_params))\n\n samples, computed_params = load_data(dataset_path, tokenizer)\n\n load_embeddings(wordchar2vector_path, word2vector_path, computed_params)\n\n X1_data, X2_data, y_data = vectorize_samples(samples, model_params, computed_params)\n\n epochs = model_params['epochs']\n batch_size = model_params['batch_size']\n\n model = create_model(computed_params, model_params)\n with open(arch_file, 'w') as f:\n f.write(model.to_json())\n\n model.fit({'input1': X1_data, 'input2': X2_data}, y_data, epochs=epochs, batch_size=batch_size, verbose=2)\n model.save_weights(weights_file)\n\n config = {'w2v_path': word2vector_path,\n 'index2label': [(i, l) for (l, i) in computed_params['label2index'].items()],\n 'index2term': [(i, t) for (t, i) in computed_params['term2index'].items()],\n 'weights': weights_file,\n 'arch_file': arch_file,\n }\n config.update(model_params)\n config['max_inputseq_len'] = computed_params['max_inputseq_len']\n config['max_outputseq_len'] = computed_params['max_outputseq_len']\n config['label2index'] = computed_params['label2index']\n config['nb_labels'] = computed_params['nb_labels']\n config['term2index'] = computed_params['term2index']\n config['nb_terms'] = computed_params['nb_terms']\n config['word_dims'] = computed_params['word_dims']\n\n with open(config_file, 'w') as f:\n json.dump(config, f, indent=4)\n elif run_mode == 'query':\n with open(config_file, 'r') as f:\n model_config = json.load(f)\n index2label = dict(model_config['index2label'])\n index2term = dict(model_config['index2term'])\n arch_file = model_config['arch_file']\n weights_file = model_config['weights']\n\n with open(arch_file, 'r') as f:\n model = model_from_json(f.read(), {'CRF': CRF})\n\n model.load_weights(weights_file)\n\n computed_params = model_config.copy()\n load_embeddings(wordchar2vector_path, word2vector_path, computed_params)\n\n while True:\n question = input('Q:> ').strip()\n question = prepare_phrase(question)\n\n short_answer = input('A:> ').strip()\n short_answer = prepare_phrase(short_answer)\n\n sample = Sample(question, short_answer, '', '')\n sample.question_words = tokenizer.tokenize(question)\n sample.short_answer_words = tokenizer.tokenize(short_answer)\n samples = [sample]\n X1_data, X2_data, y_data = vectorize_samples(samples, model_config, computed_params)\n\n y_pred = model.predict({'input1': X1_data, 'input2': X2_data}, verbose=0)\n if model_config['arch'] == 'bilstm':\n label = index2label[np.argmax(y_pred[0])]\n print(u'template={}'.format(label))\n elif model_config['arch'] == 'crf':\n terms = np.argmax(y_pred[0], axis=-1)\n terms = [index2term[i] for i in terms]\n print('{}\\n\\n'.format(u' '.join(terms)))\n else:\n raise NotImplementedError()\n elif run_mode == 'report':\n # Прогоним через обученную модель ВЕСЬ датасет и выведем те сэмплы,\n # на которых модель ошиблась.\n with open(config_file, 'r') as f:\n model_config = json.load(f)\n word_dims = int(model_config['word_dims'])\n index2label = dict(model_config['index2label'])\n index2term = dict(model_config['index2term'])\n arch_file = model_config['arch_file']\n weights_file = model_config['weights']\n\n with open(arch_file, 'r') as f:\n model = model_from_json(f.read(), {'CRF': CRF})\n\n model.load_weights(weights_file)\n\n computed_params = model_config.copy()\n\n samples, computed_params = load_data(dataset_path, tokenizer)\n\n load_embeddings(wordchar2vector_path, word2vector_path, computed_params)\n\n computed_params['word_dims'] = word_dims\n\n report_path = os.path.join(tmp_dir, 'nn_interpreter_new1.errors.report.txt')\n nb_errors = 0\n with io.open(report_path, 'w', encoding='utf-8') as wrt:\n for sample in tqdm.tqdm(samples, total=len(samples), desc='Predicting'):\n X1_data, X2_data, y_data = vectorize_samples([sample], model_config, computed_params)\n y_pred = model.predict({'input1': X1_data, 'input2': X2_data}, verbose=0)\n\n if model_config['arch'] == 'bilstm':\n pred_label = index2label[np.argmax(y_pred[0])]\n if pred_label != sample.template:\n raise NotImplementedError()\n\n elif model_config['arch'] == 'crf':\n terms = np.argmax(y_pred[0], axis=-1)\n terms = [index2term[i] for i in terms]\n #print('{}\\n\\n'.format(u' '.join(terms)))\n\n pred_template = ' '.join(t for t in terms if t not in (BEG_TOKEN, END_TOKEN, PAD_WORD))\n\n if pred_template != sample.template:\n wrt.write('{}\\n'.format(sample.question))\n wrt.write('{}|{}\\n'.format(sample.short_answer, sample.expanded_answer))\n wrt.write('expected terms: {}\\n'.format(sample.template))\n wrt.write('predicted terms: {}\\n\\n'.format(pred_template))\n wrt.flush()\n nb_errors += 1\n else:\n raise NotImplementedError()\n\n logging.info('%d samples processed, %d per-instance errors detected and stored in \"%s\"', len(samples), nb_errors, report_path)\n","sub_path":"ruchatbot/trainers/nn_interpreter_new2.py","file_name":"nn_interpreter_new2.py","file_ext":"py","file_size_in_byte":22418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"151066780","text":"# -*- coding: utf-8 -*-\r\n\r\ncountries = {\r\n 'mexico': 122,\r\n 'colombia': 49,\r\n 'argentina': 43,\r\n 'chile': 18,\r\n 'peru': 31\r\n}\r\n\r\ndef run():\r\n while True:\r\n country = str(input('Escribe el nombre de un país: ')).lower()\r\n\r\n if country == 's':\r\n break\r\n\r\n try:\r\n print('La población de {} es: {} millones'.format(country, countries[country]))\r\n except KeyError:\r\n print('No tenemos el dato de la población de {}'.format(country))\r\n else:\r\n print('Resultado Exitoso')\r\n finally:\r\n print('A continuación, ingrese la letra s para salir o el nombre de otro país')\r\n\r\n\r\nif __name__ == '__main__':\r\n print('P O B L A C I O N E S D E C A D A P A I S')\r\n run() ","sub_path":"Curso de Python/poblacion.py","file_name":"poblacion.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"449112780","text":"# 优化\n# 当知道a,b的值时c的值可通过1000-a-b得到无须遍历得出\nimport time\n\n\"\"\"测试需要多少时间\"\"\"\nstart_time = time.time()\n\"\"\"利用for循环挨个尝试\"\"\"\nfor a in range(0, 1001):\n for b in range(0, 1001):\n c = 1000 - a - b\n if a ** 2 + b ** 2 == c ** 2:\n print(\"a;,b:,c:%d %d %d\" % (a, b, c))\nend_time = time.time()\n\"\"\"打印出需要的时间\"\"\"\nprint(\"结束时间:%d\" % (end_time - start_time))\n\n\n# a;,b:,c:0 500 500\n# a;,b:,c:200 375 425\n# a;,b:,c:375 200 425\n# a;,b:,c:500 0 500\n# 结束时间:1","sub_path":"python/chapter-V-data-1/ch1-V-data-02.py","file_name":"ch1-V-data-02.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"271390916","text":"'''\n实验名称:Window(窗口)\n版本:v1.0\n日期:2020.7\n作者:01Studio【www.01Studio.org】\n'''\n\nimport lvgl as lv\nimport ujson\n\nfrom ili9341 import ili9341\nfrom xpt2046 import xpt2046\n\nTFT_IS_PORTRAIT =1 #竖屏:1 ,横屏:0 ;\nTOUCH_READY = 0 #用于检测触摸屏是否已经校准过;\n\n#LCD ili9341初始化\ndisp = ili9341(\n miso=12,\n mosi=13,\n clk=14,\n cs=15,\n dc=21,\n rst=33,\n power=50, #硬件不支持,随便配一个参数\n backlight=51, #硬件不支持,随便配一个参数\n backlight_on= 1,\n power_on= 1,\n width=240 if TFT_IS_PORTRAIT else 320,\n height=320 if TFT_IS_PORTRAIT else 240,\n rot=ili9341.PORTRAIT if TFT_IS_PORTRAIT else ili9341.LANDSCAPE #垂直方向PORTRAIT ;水平方向:LANDSCAPE\n)\n\n#触摸屏设置校准\nTOUCH_CS = 2 #触摸屏CS片选引脚\nTOUCH_INTERRUPT=0 #横屏\n\nif TFT_IS_PORTRAIT:\n TOUCH_CALI_FILE = \"touch_cali_PORTRAIT.json\" #保存为竖屏触摸参数\nelse:\n TOUCH_CALI_FILE = \"touch_cali_LANDSCAPE.json\" #保存为横屏触摸参数\n\n#从没做过触摸校准\nif TOUCH_CALI_FILE not in uos.listdir():\n touch = xpt2046(\n cs=TOUCH_CS,\n transpose=TFT_IS_PORTRAIT,\n )\n\n from touch_cali import TouchCali\n\n touch_cali = TouchCali(touch, TOUCH_CALI_FILE)\n touch_cali.start()\n\n#已经做过触摸校准,直接调用触摸参数文件\nelse:\n with open(TOUCH_CALI_FILE, 'r') as f:\n param = ujson.load(f)\n touch_x0 = param['cal_x0']\n touch_x1 = param['cal_x1']\n touch_y0 = param['cal_y0']\n touch_y1 = param['cal_y1']\n\n touch = xpt2046(\n cs=TOUCH_CS,\n transpose=TFT_IS_PORTRAIT,\n cal_x0=touch_x0,\n cal_x1=touch_x1,\n cal_y0=touch_y0,\n cal_y1=touch_y1,\n )\n\n TOUCH_READY = 1 #表示已经配置好触摸参数\n\n#############################################\n############### Window ##############\n#############################################\n\nif TOUCH_READY:\n\n # Create a window\n win = lv.win(lv.scr_act())\n win.set_title(\"Window title\") # Set the title\n\n\n # Add control button to the header\n close_btn = win.add_btn(lv.SYMBOL.CLOSE) # Add close button and use built-in close action\n close_btn.set_event_cb(lv.win.close_event_cb)\n win.add_btn(lv.SYMBOL.SETTINGS) # Add a setup button\n\n # Add some dummy content\n txt = lv.label(win)\n txt.set_text(\n\"\"\"This is the content of the window\nYou can add control buttons to\nthe window header\nThe content area becomes automatically\nscrollable is it's large enough.\nYou can scroll the content\nSee the scroll bar on the right!\"\"\"\n )\n","sub_path":"esp32_resources/3.pyWiFi-ESP32/5.LVGL/2.小部件实验/24-Window(窗口)/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"327513619","text":"\"\"\"\nThis is a example script which demo how to load data into neo4j and ElasticSearch without using Airflow DAG.\n\"\"\"\n\nimport logging\nfrom pyhocon import ConfigFactory\nimport sys\nfrom elasticsearch import Elasticsearch\nfrom databuilder.extractor.neo4j_es_last_updated_extractor import Neo4jEsLastUpdatedExtractor\nfrom databuilder.extractor.neo4j_search_data_extractor import Neo4jSearchDataExtractor\nimport uuid\nimport textwrap\n\nfrom databuilder.extractor.sql_alchemy_extractor import SQLAlchemyExtractor\nfrom databuilder.extractor.autonomous_extractor import OracleMetadataExtractor\nfrom databuilder.job.job import DefaultJob\n\nfrom databuilder.loader.file_system_neo4j_csv_loader import FsNeo4jCSVLoader\nfrom databuilder.loader.file_system_elasticsearch_json_loader import FSElasticsearchJSONLoader\n\nfrom databuilder.publisher import neo4j_csv_publisher\nfrom databuilder.extractor.neo4j_extractor import Neo4jExtractor\nfrom databuilder.publisher.neo4j_csv_publisher import Neo4jCsvPublisher\nfrom databuilder.publisher.elasticsearch_publisher import ElasticsearchPublisher\nfrom databuilder.task.task import DefaultTask\nfrom databuilder.transformer.base_transformer import NoopTransformer\n\n\n\nLOGGER = logging.getLogger(__name__)\nLOGGER.setLevel(logging.INFO)\n\n# Disable oracle logging\nlogging.getLogger(\"oracle_metadata.connector.network\").disabled = True\n\n# script should be called with command line arguments of user, password, and service string\nuser = sys.argv[1]\npassword = sys.argv[2]\nservice = sys.argv[3]\n\n#SQLAlchemy connection string\nORACLE_CONN_STRING = 'oracle://{0}:{1}@{2}'.format(user,password,service)\n\n# change to the address of Elasticsearch service\nes = Elasticsearch([\n {'host': 'localhost'},\n])\n\n# replace localhost with docker host ip\nNEO4J_ENDPOINT = 'bolt://localhost:7687'\nneo4j_endpoint = NEO4J_ENDPOINT\n\nneo4j_user = 'neo4j'\nneo4j_password = 'test'\n\n\n\ndef create_sample_oracle_job():\n\n tmp_folder = '/var/tmp/amundsen/{}'.format('tables')\n node_files_folder = '{tmp_folder}/nodes'.format(tmp_folder=tmp_folder)\n relationship_files_folder = '{tmp_folder}/relationships'.format(tmp_folder=tmp_folder)\n\n sql_extractor = OracleMetadataExtractor()\n csv_loader = FsNeo4jCSVLoader()\n\n task = DefaultTask(extractor=sql_extractor,\n loader=csv_loader)\n\n job_config = ConfigFactory.from_dict({\n 'extractor.oracle_metadata.extractor.sqlalchemy.{}'.format(SQLAlchemyExtractor.CONN_STRING): ORACLE_CONN_STRING,\n ## if you dont specify this value the default will be \"autonomous\"\n # 'extractor.oracle_metadata.{}'.format(OracleMetadataExtractor.DATABASE_KEY): 'YourSnowflakeDbName',\n 'loader.filesystem_csv_neo4j.{}'.format(FsNeo4jCSVLoader.NODE_DIR_PATH): node_files_folder,\n 'loader.filesystem_csv_neo4j.{}'.format(FsNeo4jCSVLoader.RELATION_DIR_PATH): relationship_files_folder,\n 'loader.filesystem_csv_neo4j.{}'.format(FsNeo4jCSVLoader.SHOULD_DELETE_CREATED_DIR): True,\n 'loader.filesystem_csv_neo4j.{}'.format(FsNeo4jCSVLoader.FORCE_CREATE_DIR): True,\n 'publisher.neo4j.{}'.format(neo4j_csv_publisher.NODE_FILES_DIR): node_files_folder,\n 'publisher.neo4j.{}'.format(neo4j_csv_publisher.RELATION_FILES_DIR): relationship_files_folder,\n 'publisher.neo4j.{}'.format(neo4j_csv_publisher.NEO4J_END_POINT_KEY): neo4j_endpoint,\n 'publisher.neo4j.{}'.format(neo4j_csv_publisher.NEO4J_USER): neo4j_user,\n 'publisher.neo4j.{}'.format(neo4j_csv_publisher.NEO4J_PASSWORD): neo4j_password,\n 'publisher.neo4j.{}'.format(neo4j_csv_publisher.JOB_PUBLISH_TAG): 'unique_tag'\n })\n job = DefaultJob(conf=job_config,\n task=task,\n publisher=Neo4jCsvPublisher())\n return job\n\ndef create_last_updated_job():\n # loader saves data to these folders and publisher reads it from here\n tmp_folder = '/var/tmp/amundsen/last_updated_data'\n node_files_folder = '{tmp_folder}/nodes'.format(tmp_folder=tmp_folder)\n relationship_files_folder = '{tmp_folder}/relationships'.format(tmp_folder=tmp_folder)\n\n task = DefaultTask(extractor=Neo4jEsLastUpdatedExtractor(),\n loader=FsNeo4jCSVLoader())\n\n job_config = ConfigFactory.from_dict({\n 'extractor.neo4j_es_last_updated.model_class':\n 'databuilder.models.neo4j_es_last_updated.Neo4jESLastUpdated',\n\n 'loader.filesystem_csv_neo4j.{}'.format(FsNeo4jCSVLoader.NODE_DIR_PATH):\n node_files_folder,\n 'loader.filesystem_csv_neo4j.{}'.format(FsNeo4jCSVLoader.RELATION_DIR_PATH):\n relationship_files_folder,\n\n 'publisher.neo4j.{}'.format(neo4j_csv_publisher.NODE_FILES_DIR):\n node_files_folder,\n 'publisher.neo4j.{}'.format(neo4j_csv_publisher.RELATION_FILES_DIR):\n relationship_files_folder,\n 'publisher.neo4j.{}'.format(neo4j_csv_publisher.NEO4J_END_POINT_KEY):\n neo4j_endpoint,\n 'publisher.neo4j.{}'.format(neo4j_csv_publisher.NEO4J_USER):\n neo4j_user,\n 'publisher.neo4j.{}'.format(neo4j_csv_publisher.NEO4J_PASSWORD):\n neo4j_password,\n 'publisher.neo4j.{}'.format(neo4j_csv_publisher.JOB_PUBLISH_TAG):\n 'unique_lastupdated_tag', # should use unique tag here like {ds}\n })\n\n job = DefaultJob(conf=job_config,\n task=task,\n publisher=Neo4jCsvPublisher())\n return job\n\n\ndef create_es_publisher_sample_job(elasticsearch_index_alias='table_search_index',\n elasticsearch_doc_type_key='table',\n model_name='databuilder.models.table_elasticsearch_document.TableESDocument',\n cypher_query=None,\n elasticsearch_mapping=None):\n \"\"\"\n :param elasticsearch_index_alias: alias for Elasticsearch used in\n amundsensearchlibrary/search_service/config.py as an index\n :param elasticsearch_doc_type_key: name the ElasticSearch index is prepended with. Defaults to `table` resulting in\n `table_search_index`\n :param model_name: the Databuilder model class used in transporting between Extractor and Loader\n :param cypher_query: Query handed to the `Neo4jSearchDataExtractor` class, if None is given (default)\n it uses the `Table` query baked into the Extractor\n :param elasticsearch_mapping: Elasticsearch field mapping \"DDL\" handed to the `ElasticsearchPublisher` class,\n if None is given (default) it uses the `Table` query baked into the Publisher\n \"\"\"\n # loader saves data to this location and publisher reads it from here\n extracted_search_data_path = '/var/tmp/amundsen/search_data.json'\n\n task = DefaultTask(loader=FSElasticsearchJSONLoader(),\n extractor=Neo4jSearchDataExtractor(),\n transformer=NoopTransformer())\n\n # elastic search client instance\n elasticsearch_client = es\n # unique name of new index in Elasticsearch\n elasticsearch_new_index_key = 'tables' + str(uuid.uuid4())\n\n job_config = ConfigFactory.from_dict({\n 'extractor.search_data.extractor.neo4j.{}'.format(Neo4jExtractor.GRAPH_URL_CONFIG_KEY): neo4j_endpoint,\n 'extractor.search_data.extractor.neo4j.{}'.format(Neo4jExtractor.MODEL_CLASS_CONFIG_KEY): model_name,\n 'extractor.search_data.extractor.neo4j.{}'.format(Neo4jExtractor.NEO4J_AUTH_USER): neo4j_user,\n 'extractor.search_data.extractor.neo4j.{}'.format(Neo4jExtractor.NEO4J_AUTH_PW): neo4j_password,\n 'loader.filesystem.elasticsearch.{}'.format(FSElasticsearchJSONLoader.FILE_PATH_CONFIG_KEY):\n extracted_search_data_path,\n 'loader.filesystem.elasticsearch.{}'.format(FSElasticsearchJSONLoader.FILE_MODE_CONFIG_KEY): 'w',\n 'publisher.elasticsearch.{}'.format(ElasticsearchPublisher.FILE_PATH_CONFIG_KEY):\n extracted_search_data_path,\n 'publisher.elasticsearch.{}'.format(ElasticsearchPublisher.FILE_MODE_CONFIG_KEY): 'r',\n 'publisher.elasticsearch.{}'.format(ElasticsearchPublisher.ELASTICSEARCH_CLIENT_CONFIG_KEY):\n elasticsearch_client,\n 'publisher.elasticsearch.{}'.format(ElasticsearchPublisher.ELASTICSEARCH_NEW_INDEX_CONFIG_KEY):\n elasticsearch_new_index_key,\n 'publisher.elasticsearch.{}'.format(ElasticsearchPublisher.ELASTICSEARCH_DOC_TYPE_CONFIG_KEY):\n elasticsearch_doc_type_key,\n 'publisher.elasticsearch.{}'.format(ElasticsearchPublisher.ELASTICSEARCH_ALIAS_CONFIG_KEY):\n elasticsearch_index_alias,\n })\n\n # only optionally add these keys, so need to dynamically `put` them\n if cypher_query:\n job_config.put('extractor.search_data.{}'.format(Neo4jSearchDataExtractor.CYPHER_QUERY_CONFIG_KEY),\n cypher_query)\n if elasticsearch_mapping:\n job_config.put('publisher.elasticsearch.{}'.format(ElasticsearchPublisher.ELASTICSEARCH_MAPPING_CONFIG_KEY),\n elasticsearch_mapping)\n\n job = DefaultJob(conf=job_config,\n task=task,\n publisher=ElasticsearchPublisher())\n return job\n\n\nif __name__ == \"__main__\":\n job = create_sample_oracle_job()\n job.launch()\n\n # start last updated job\n job_lastupdated = create_last_updated_job()\n job_lastupdated.launch()\n\n # start Elasticsearch publish jobs\n job_es_table = create_es_publisher_sample_job(\n elasticsearch_index_alias='table_search_index',\n elasticsearch_doc_type_key='table',\n model_name='databuilder.models.table_elasticsearch_document.TableESDocument')\n job_es_table.launch()\n\n user_cypher_query = textwrap.dedent(\n \"\"\"\n MATCH (user:User)\n OPTIONAL MATCH (user)-[read:READ]->(a)\n OPTIONAL MATCH (user)-[own:OWNER_OF]->(b)\n OPTIONAL MATCH (user)-[follow:FOLLOWED_BY]->(c)\n OPTIONAL MATCH (user)-[manage_by:MANAGE_BY]->(manager)\n with user, a, b, c, read, own, follow, manager\n where user.full_name is not null\n return user.email as email, user.first_name as first_name, user.last_name as last_name,\n user.full_name as name, user.github_username as github_username, user.team_name as team_name,\n user.employee_type as employee_type, manager.email as manager_email, user.slack_id as slack_id,\n user.is_active as is_active,\n REDUCE(sum_r = 0, r in COLLECT(DISTINCT read)| sum_r + r.read_count) AS total_read,\n count(distinct b) as total_own,\n count(distinct c) AS total_follow\n order by user.email\n \"\"\"\n )\n\n user_elasticsearch_mapping = \"\"\"\n {\n \"mappings\":{\n \"user\":{\n \"properties\": {\n \"email\": {\n \"type\":\"text\",\n \"analyzer\": \"simple\",\n \"fields\": {\n \"raw\": {\n \"type\": \"keyword\"\n }\n }\n },\n \"first_name\": {\n \"type\":\"text\",\n \"analyzer\": \"simple\",\n \"fields\": {\n \"raw\": {\n \"type\": \"keyword\"\n }\n }\n },\n \"last_name\": {\n \"type\":\"text\",\n \"analyzer\": \"simple\",\n \"fields\": {\n \"raw\": {\n \"type\": \"keyword\"\n }\n }\n },\n \"name\": {\n \"type\":\"text\",\n \"analyzer\": \"simple\",\n \"fields\": {\n \"raw\": {\n \"type\": \"keyword\"\n }\n }\n },\n \"total_read\":{\n \"type\": \"long\"\n },\n \"total_own\": {\n \"type\": \"long\"\n },\n \"total_follow\": {\n \"type\": \"long\"\n }\n }\n }\n }\n }\n \"\"\"\n","sub_path":"example/scripts/sample_oracle_loader.py","file_name":"sample_oracle_loader.py","file_ext":"py","file_size_in_byte":12471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"452326487","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport json\nimport argh\nfrom crate.client import connect\nfrom crate.client.exceptions import ProgrammingError\nfrom cr8.timeit import timeit\nfrom cr8.json2insert import to_insert\n\n\ndef _get_runtimes(hosts):\n conn = connect(hosts)\n c = conn.cursor()\n c.execute(\"select min(runtime_stats['avg']), statement from benchmarks group by statement\")\n rows = c.fetchall()\n for min_avg, statement in rows:\n c.execute(\"select runtime_stats['avg'] from benchmarks \"\n \"where statement = ? order by ended desc limit 1\", (statement,))\n yield min_avg, c.fetchall()[0][0], statement\n\n\ndef _query_supported(cursor, statement):\n try:\n cursor.execute(statement)\n return True\n except ProgrammingError:\n return False\n\n\n@argh.arg('benchmark_hosts', type=str, nargs='+',\n help='hosts of the crate cluster which will be used to run the queries')\n@argh.arg('log_host', type=str,\n help='host of the crate cluster where there is the table which contains benchmark results')\ndef find_perf_regressions(benchmark_hosts, log_host):\n \"\"\" finds performance regressions by running recorded queries\n\n Reads the benchmark table from the log_host and runs all queries again\n against the benchmark_hosts. It will compare the new runtimes with the\n previous runs and print runtime details.\n\n The new query runtimes are also persitet to the log_host.\n \"\"\"\n runtimes = _get_runtimes(log_host)\n regressions = []\n\n conn = connect(benchmark_hosts)\n benchmark_cursor = conn.cursor()\n\n conn = connect(log_host)\n log_cursor = conn.cursor()\n for min_avg, last_avg, statement in runtimes:\n if not _query_supported(benchmark_cursor, statement):\n yield 'Skipping statement as it run into an error: {}'.format(statement)\n continue\n yield 'Running: {}'.format(statement)\n result = timeit(statement, benchmark_hosts, warmup=5)\n yield 'Runtime: best: {} previous: {} current: {}'.format(\n min_avg, last_avg, result.runtime_stats['avg'])\n if (result.runtime_stats['avg'] * 1.05) > min_avg:\n regressions.append((vars(result), min_avg))\n\n d = vars(result).copy()\n del d['client_runtimes']\n del d['server_runtimes']\n stmt, args = to_insert('benchmarks', d)\n log_cursor.execute(stmt, args)\n if any(regressions):\n raise SystemExit(json.dumps(regressions, indent=4))\n else:\n yield json.dumps(regressions, indent=4)\n\n\ndef main():\n argh.dispatch_command(find_perf_regressions)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"cr8/perf_regressions.py","file_name":"perf_regressions.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"160665967","text":"#!/usr/bin/env python\n\n# Expects a standard input stream with raw text data\n# Emits an output stream with one word per line\n\nimport sys\n\ndef sanitizeWord(word):\n word = word.strip()\n word = word.lower()\n output = \"\"\n allowed = \"abcdefghijklmnopqrstuvwxyz\"\n for c in word:\n if c in allowed:\n output += c\n return output\n\nfor line in sys.stdin:\n words = line.split(' ')\n for word in words:\n word = sanitizeWord(word)\n if len(word) >= 1:\n print(word)\n","sub_path":"AndysWordCounter/tokenizer.py","file_name":"tokenizer.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"509161995","text":"import tkinter as tk\nimport shelve\nfrom Crypter import Crypter\nfrom keeper import KeeperGui\nimport os\n\nclass LoginWindow(tk.Frame):\n\n def __init__(self, parent):\n z = tk.Frame.__init__(self, parent)\n self.parent = parent\n self.parent.title(\"Login\")\n self.top_panel = tk.Frame(z)\n self.bot_panel = tk.Frame(z)\n self.user_lbl = tk.Label(self.top_panel, text=\"Username:\")\n self.user_entry = tk.Entry(self.top_panel)\n self.log_button = tk.Button(self.bot_panel,text=\"Login\", command=self.login_method)\n self.user_lbl.pack(side=tk.LEFT)\n self.user_entry.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.X)\n self.user_entry.bind(\"\", self.login_method)\n self.user_entry.focus_set()\n self.log_button.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.X)\n self.top_panel.pack(side=tk.LEFT, expand=tk.YES,fill=tk.BOTH)\n self.bot_panel.pack(side=tk.RIGHT, expand=tk.YES,fill=tk.BOTH)\n\n def unpack(self):\n self.user_entry.pack_forget()\n self.user_lbl.pack_forget()\n self.log_button.pack_forget()\n self.top_panel.pack_forget()\n self.bot_panel.pack_forget()\n\n def login_method(self, e):\n acc = Crypter.crypt(self.user_entry.get())\n if os._exists(acc):\n os.mkdir(acc)\n os.chdir(acc)\n f = shelve.open(acc, \"c\")\n self.unpack()\n KeeperGui(self.parent, f)","sub_path":"login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"551439524","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.views.generic import TemplateView\nfrom django.utils import timezone\nfrom .models import Snippets\nfrom .forms import AddSnippet\nfrom django.views.generic.edit import UpdateView\n\n# function to delete item from model and re render view\ndef delete_item(request, pk):\n # get item\n post = Snippets.objects.get(pk = pk)\n # delete it\n post.delete()\n snippets = Snippets.objects.all()\n # // reset the form\n form = AddSnippet()\n return render(request, 'index.html', {'form': form, \"snippets\": snippets, \"error\": \"\"})\n\n# function to select item for editing render to view\ndef edit_item(request, pk):\n # get item\n primaryKey = pk\n item = Snippets.objects.get(pk = pk)\n snippets = Snippets.objects.all()\n # // reset the form\n form = AddSnippet()\n # edititem = EditSnippet(instance=item)\n return render(request, 'index.html', {'form': form, \"snippets\": snippets, 'edititem': item, \"error\": \"\"})\n\n# function to edit based on pk\ndef update_item(request):\n error=\"\"\n if request.method == 'POST':\n pk=request.POST.get(\"pk\")\n newDict = {\"title\" : request.POST.get(\"title\"),\n \"language\": request.POST.get(\"language\"),\n \"snippet\" : request.POST.get(\"snippet\"),\n \"description\" : request.POST.get(\"description\") }\n # update and throw error message it duplicate title\n try:\n Snippets.objects.select_for_update().filter(pk=pk).update(**newDict)\n except:\n error = 'Title ' + newDict.get(\"title\") + ' already exists, try again.'\n # get list of all snippets for display on view\n snippets = Snippets.objects.all()\n # // reset the form\n form = AddSnippet()\n return render(request, 'index.html', {'form': form, \"snippets\": snippets, \"updateerror\": error})\n\n# Main Form View\nclass HomePageView(TemplateView):\n def get(self, request, **kwargs):\n # get list of all snippets for display on view\n snippets = Snippets.objects.all()\n # // reset the form\n form = AddSnippet()\n return render(request, 'index.html', {'form': form, \"snippets\": snippets, \"error\": \"\"})\n\n def post(self, request, **kwargs):\n form = AddSnippet(request.POST)\n error = \"\"\n # verify that form is valid\n if form.is_valid():\n # save the form data to database\n try:\n form.save(commit=True)\n except:\n error = 'Title already exists'\n # get list of all snippets for display on view\n snippets = Snippets.objects.all()\n # // reset the form\n form = AddSnippet()\n return render(request, 'index.html', {'form': form, \"snippets\": snippets, \"error\": error})\n\n\n\n","sub_path":"app/snippetsapp/snippets/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"621909243","text":"from django.urls import path\n\nfrom . import views\n\n\napp_name = \"player\"\n\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('add_channel/', views.add_channel, name='add_channel'),\n path('play_channel/', views.play_channel, name='play_channel'),\n path('stop_music/', views.stop_music, name='stop_music'),\n]\n","sub_path":"player/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"437501660","text":"from pathlib import Path\n\nfrom vcv import verify_card\n\nif __name__ == \"__main__\":\n\n img_path = str(Path(\"./example/data/IMG_1396.jpg\").resolve())\n template_path = str(Path(\"./templates/CDC_card_template_01.png\").resolve())\n # isValid = verify_card(img_path, template_path)\n isValid, failure_code = verify_card(img_path, template_path, show=True, output_dir=\"./example/output\", verbose=True)\n\n if isValid:\n print(\"Valid vaccination card detected!\")\n else:\n print(\"Invalid vaccination card detected!\")\n","sub_path":"example/verify_single_card.py","file_name":"verify_single_card.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"146737406","text":"#!/usr/bin/env python3\n#Author: Nurzhan Sapargali \n\"\"\"Concatenates census tables. Merges dbf files into a table and \nmakes dummies. Combines resultant tables for estimation.\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\n\nfrom simpledbf import Dbf5\nfrom itertools import product\n\n\nPOPULATION_FOLDER = './Population/'\nOUTPUT_FOLDER = './Output/'\n\ndef dbf_to_df(filename):\n \"\"\"Reads dbf files and creates a dataframe\"\"\"\n dbf = Dbf5(filename)\n df = dbf.to_dataframe()\n return df\n\ndef main():\n #Merge map data vertically by region name\n print('Merging and adding binary variables to regressors table')\n arable = dbf_to_df(OUTPUT_FOLDER + 'arable89.dbf')[['NAME_1',\n 'GID_0',\n 'Majority']]\n #Rename columns for merger\n arable.columns = ['unit','country','v_a']\n #Set region names as dataframe index for merger\n arable = arable.set_index('unit')\n fhb = dbf_to_df(OUTPUT_FOLDER + 'fusarium.dbf')[['NAME_1',\n 'Join_Count']]\n #Put dummies based on intersection rule\n fhb['Join_Count'] = np.where(fhb['Join_Count'] > 0, 1, 0)\n fhb.columns = ['unit','v_f']\n fhb = fhb.set_index('unit')\n util = dbf_to_df(OUTPUT_FOLDER + 'landutil61.dbf')[['NAME_1',\n 'Join_Count']]\n util['Join_Count'] = np.where(util['Join_Count'] > 0, 1, 0)\n util.columns = ['unit','v_u']\n util = util.set_index('unit')\n grain = dbf_to_df(OUTPUT_FOLDER + 'landuse82.dbf')[['NAME_1',\n 'Join_Count']]\n grain['Join_Count'] = np.where(grain['Join_Count'] > 0, 1, 0)\n grain.columns = ['unit','v_g']\n grain = grain.set_index('unit')\n delta = dbf_to_df(OUTPUT_FOLDER + 'delta.dbf')[['NAME_1',\n 'mean_53',\n 'mean_65']]\n delta['delta_6553'] = delta['mean_65'] - delta['mean_53']\n #Put dummies based on threshold rule\n delta['v_c'] = np.where(delta['delta_6553'] > 0.0207, 1, 0)\n delta = delta[['NAME_1','v_c']]\n delta.columns = ['unit','v_c']\n delta = delta.set_index('unit')\n #Left join tables on region names\n vs = arable.join([fhb, grain, util, delta])\n vs.columns = ['r'] + list(vs.columns)[1:]\n print('...Success')\n\n #Set up a matrix\n print('Calculating Jaccard coefficients')\n matrix = pd.DataFrame(index=vs.columns[1:], columns=vs.columns[1:])\n #Calculate all dummy pair permutations with repetition\n perms = [i for i in product(vs.columns[1:], repeat=2)]\n #Populate the matrix per permutation\n for p in perms:\n matches = 0\n values = [[i,j] for i,j in zip(vs[p[0]], vs[p[1]])]\n for v in values:\n if v[0] == v[1]:\n matches += 1\n J = matches/(2*len(vs) - matches)\n matrix[p[0]][p[1]] = round(J, 3)\n #Write to file\n matrix.to_csv('similarity_matrix.csv')\n print('...Success')\n\nif __name__ == '__main__':\n main()\n","sub_path":"_3_build_similarity_matrix.py","file_name":"_3_build_similarity_matrix.py","file_ext":"py","file_size_in_byte":3163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"134713497","text":"from django.utils.translation import ugettext as _\n\nfrom freenasUI.storage.models import Volume\nfrom freenasUI.system.alert import alertPlugins, Alert, BaseAlert\n\n\nclass VolumeVersionAlert(BaseAlert):\n\n interval = 5\n\n def run(self):\n alerts = []\n for vol in Volume.objects.filter(vol_fstype='ZFS'):\n if vol.is_upgraded is not True:\n alerts.append(Alert(\n Alert.WARN, _(\n 'New feature flags are available for volume %s. Refer '\n 'to the \"Upgrading a ZFS Pool\" section of the User '\n 'Guide for instructions.'\n ) % vol.vol_name,\n ))\n\n return alerts\n\nalertPlugins.register(VolumeVersionAlert)\n","sub_path":"gui/system/alertmods/volume_version.py","file_name":"volume_version.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"138529549","text":"#\n# author: Jungtaek Kim (jtkim@postech.ac.kr)\n# last updated: February 8, 2021\n#\n\nimport numpy as np\n\nfrom bayeso_benchmarks.benchmark_base import Function\n\n\ndef fun_target(bx, dim_bx):\n assert len(bx.shape) == 1\n assert bx.shape[0] == dim_bx\n\n y = 0.0\n\n for ind in range(0, dim_bx - 1):\n y += 100 * (bx[ind+1] - bx[ind]**2)**2 + (bx[ind] - 1.0)**2\n return y\n\n\nclass Rosenbrock(Function):\n def __init__(self, dim_problem, seed=None):\n assert isinstance(dim_problem, int)\n assert isinstance(seed, (type(None), int))\n assert dim_problem > 1\n\n dim_bx = np.inf\n bounds = np.array([\n [-2.048, 2.048],\n ])\n global_minimizers = np.array([\n [1.0],\n ])\n global_minimum = 0.0\n dim_problem = dim_problem\n\n function = lambda bx: fun_target(bx, dim_problem)\n\n try:\n super().__init__(dim_bx, bounds, global_minimizers, global_minimum, function, dim_problem=dim_problem, seed=seed)\n except:\n super(Rosenbrock, self).__init__(dim_bx, bounds, global_minimizers, global_minimum, function, dim_problem=dim_problem, seed=seed)\n","sub_path":"bayeso_benchmarks/inf_dim_rosenbrock.py","file_name":"inf_dim_rosenbrock.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"92768508","text":"#!/gpfsm/dulocal/sles11/other/SLES11.3/miniconda3/2019.03_py3.7/2019-05-15/bin/python\n\n#Plotting the results of a noah-mp run with calibrated parameters\n#Observation vs Model Output\n\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport csv\nimport datetime as dt\nimport os\n\nmainPath = '/discover/nobackup/jframe/gpr_fluxnet/'\n\n# load site/year combination\nsites =\tnp.genfromtxt(mainPath + 'data/pals/Site_Years.txt', delimiter = ' ')\nNs = sites.shape[0]\n\n#----- Set up runtime directories ---------------------------\n# Delete and reinit test dirs\nplotLoc = mainPath + 'plots/init_plots/'\n\nfor s in range(0, Ns):\n\n # get sites and year, need in string\n S = str(int(sites[s,0]))\n Y = str(int(sites[s,1]))\n siteyear = S + '_' + Y \n # Screen report\n print('Plotting initialization results for site = %d, year = %d, ' % (sites[s,0], sites[s,1]))\n\n dirPath = mainPath + 'soil_moisture/init_dirs/'\n dataDir = dirPath+'run_'+siteyear+'/'\n\n x = []\n xDays = []\n y_obs = []\n y_noah = []\n y_assm = []\n y_1stp = []\n p = []\n count_row = 0\n xDays.append(0)\n with open(dataDir+'output.noah','r') as csvfile:\n model = csv.reader(csvfile, delimiter=' ', skipinitialspace=True )\n for row in model:\n p.append(float(row[9]))\n y_noah.append(float(row[10]))\n simLength = len(y_noah)\n with open(dataDir+'output.onestep','r') as csvfile:\n model = csv.reader(csvfile, delimiter=' ', skipinitialspace=True )\n for row in model:\n y_1stp.append(float(row[10]))\n simLength = len(y_1stp)\n with open(dataDir+'output.da','r') as csvfile:\n model = csv.reader(csvfile, delimiter=' ', skipinitialspace=True )\n for row in model:\n y_assm.append(float(row[10]))\n simLength = len(y_assm)\n with open(dataDir+'obs.txt','r') as csvfile:\n observations = csv.reader(csvfile, delimiter=' ', skipinitialspace=True )\n for row in observations:\n if count_row < simLength:\t\n D = dt.datetime(int(row[0]),1,1) + \\\n dt.timedelta((int(row[1])-1) + float(row[2])/24)\n x.append(D)\n y_obs.append(float(row[5]))\n if count_row > 0:\n xDays.append(xDays[count_row-1] + 1/48)\n count_row = count_row + 1\n \n sYear = x[0].year\n sMonth = x[0].month\n sDay = x[0].day\n \n startPlot = dt.date(sYear,sMonth,sDay)\n endPlot = startPlot + dt.timedelta(365)\n plotDates = [startPlot, endPlot]\n \n fig, ax1 = plt.subplots(figsize=(15,10)) \n ax1.plot(x,y_obs, label='Observed')\n ax1.plot(x,y_noah, label='Noah')\n ax1.plot(x,y_1stp, label='Noah 1-step')\n ax1.plot(x,y_assm, label='Noah EnKS')\n #ax1.set_xlim(plotDates)\n ax1.set_ylabel('Soil moisture')\n ax1.set_ylim([0,1])\n #ax1.set_xlabel('')\n plt.legend(loc='upper left')\n ax2 = ax1.twinx()\n ax2.plot(x,p, label='precipitation', linewidth=0.1, color='grey')\n ax2.set_ylabel('precip')\n #ax2.set_xlim(plotDates)\n plt.title(siteyear + ' Observed and modeled soil moisture')\n plt.legend(loc='upper right')\n fig.tight_layout() # otherwise the right y-label is slightly clipped\n plt.savefig(plotLoc+siteyear+'.png', dpi=400)\n plt.close()\n","sub_path":"setup_dir/plot_ALL_init_sm.py","file_name":"plot_ALL_init_sm.py","file_ext":"py","file_size_in_byte":3349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"466465406","text":"import numpy as np \nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n\ntrain_datagen = ImageDataGenerator(\n rescale=1./255,\n horizontal_flip=True,\n vertical_flip=True,\n width_shift_range=0.1,\n height_shift_range=0.1,\n rotation_range=5,\n zoom_range=1.2,\n shear_range=0.7,\n fill_mode='nearest'\n)\n\ntest_datagen = ImageDataGenerator( rescale=1./255 )\n\nxy_train = train_datagen.flow_from_directory(\n './data/brain/train',\n target_size=(150, 150),\n batch_size=5,\n class_mode='binary',\n shuffle=True \n)\n\n# 그냥 실행했을 때 Found 160 images belonging to 2 classes.\n\nxy_test = test_datagen.flow_from_directory(\n './data/brain/test',\n target_size=(150, 150),\n batch_size=5,\n class_mode='binary'\n)\n\n# Found 120 images belonging to 2 classes.\n\n# print(xy_train.class_indices) # {'ad': 0, 'normal': 1}\n# print(xy_train)\n# # \n# print(xy_train[0][0]) # x 값\n# print(xy_train[0][1]) # y 값\n# # print(xy_train[0][2]) # 없어\n# # print(xy_train[0][0].shape, xy_train[0][1].shape) # (5 <- batch_size, 150, 150, 3) (5,)\n\n# print(type(xy_train)) # \n# print(type(xy_train[0])) # \n# print(type(xy_train[0][0])) # \n# print(type(xy_train[0][1])) # \n\n\n","sub_path":"keras/keras59_1_ImageDataGenerator.py","file_name":"keras59_1_ImageDataGenerator.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"469889875","text":"\"\"\"Wall Game (Python version) demonstration.\n\nThis demo is a simple version where a single click can take care of any unit.\n\"\"\"\n\nimport random\n\nfrom cocos import scene\nfrom cocos.batch import BatchNode\nfrom cocos.layer import ColorLayer\nfrom cocos.director import director\nfrom cocos.sprite import Sprite\n\n\nWAVES = [\n {'num_units': 3, 'unit_type': 'dino'}\n]\n\nUNIT_TYPES = {\n 'dino': {\n 'health': 10,\n 'speed': 5,\n 'asset': 'assets/85857.png'\n }\n}\n\n\nclass InputLayer(ColorLayer):\n \"\"\"Contains all game mechanics.\"\"\"\n\n is_event_handler = True\n\n NUM_LADDERS = 5\n LADDERS = [{'x': 100*i} for i in range(1, NUM_LADDERS)]\n DT = 0.1\n\n def __init__(self, x=320, y=240):\n \"\"\"Initialize the game.\"\"\"\n super(InputLayer, self).__init__(46, 204, 113, 1000)\n self.batches = set()\n self.units = []\n self.start_wave(**WAVES[0])\n self.schedule_interval(self.update_units, self.DT)\n\n def start_wave(self, num_units: int, unit_type: str, duration: int=3):\n \"\"\"Start the indicated wave.\n\n This method randomly initializes `num_units` of `unit_types` over a\n span of `duration`. Each unit is started from a random ladder.\n\n Args:\n num_units: Number of units to spawn\n unit_type: Name of unit type\n duration (s): Duration of time for all units to randomly spawn\n \"\"\"\n assert num_units < 100, 'Function needs to be optimized for 100+ units'\n assert unit_type in UNIT_TYPES, 'Invalid unit type invoked in wave.'\n batch = BatchNode()\n self.add(batch)\n\n world_width, world_height = director.get_window_size()\n for i in range(num_units):\n unit_info = UNIT_TYPES[unit_type]\n unit = Sprite(unit_info['asset'])\n unit.position = random.choice(self.LADDERS)['x'], \\\n - unit_info['speed'] * (random.random() * duration) / self.DT\n unit.info = unit_info\n unit.parent_batch = batch\n batch.add(unit)\n self.units.append(unit)\n self.batches.add(batch)\n\n def update_units(self, _):\n \"\"\"Update all units.\n\n Each unit's position is updated, per the unit's speed.\n \"\"\"\n world_width, world_height = director.get_window_size()\n for unit in self.units:\n unit.position = unit.position[0], unit.position[1] + unit.info['speed']\n\n def on_mouse_press(self, x: float, y: float, _, __):\n \"\"\"Update units based on mouse press.\n\n Locate the unit clicked on, and remove the unit.\n\n Args:\n x: x position for the mouse click\n y: y position for the mouse click\n \"\"\"\n for i, unit in enumerate(self.units):\n if unit.get_rect().contains(x, y):\n self.units.pop(i)\n unit.parent_batch.remove(unit)\n break\n\n\ndirector.init()\ndirector.run(scene.Scene(InputLayer()))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"257183370","text":"from django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('home', views.home, name='home'),\n path('', views.customer, name='customer'),\n path('register', views.register, name='register'),\n path('custadmin',views.custadmin,name='custadmin'),\n path('adminhome',views.adminhome,name='adminhome'),\n path('adminlogout',views.adminlogout,name='adminlogout'),\n path('admindelete/',views.admindelete,name='admindelete'),\n path('login', views.login, name='login'),\n path('dashboard', views.dashboard, name='dashboard'),\n path('logout', views.logout, name='logout'),\n path('shipping', views.shipping, name='shipping'),\n path('profile', views.Profile, name='profile'),\n path('custdelete/', views.custdestroy, name='delete'),\n path('custedit/', views.custedit, name='edit'),\n path('custupdate/', views.custupdate, name='update')\n]\n","sub_path":"users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"375497746","text":"try:\n from django.conf import settings\nexcept ImportError:\n settings = {}\nelse:\n if not settings.configured:\n settings.configure()\n\n\ndef ga(name, default):\n try:\n return getattr(settings, name, default)\n except ImportError:\n return default\n\nDEBUG = ga('BUTLER_DEBUG', None)\n\nif DEBUG is None:\n DEBUG = ga('DEBUG', False)\n\nDATE_TIME_FORMAT = ga('BUTLER_DATE_TIME_FORMAT', '%Y-%m-%d %H:%M:%S')\nDATE_FORMAT = ga('BUTLER_DATE_FORMAT', '%Y-%m-%d')\n\nFILTER_SEPARATOR = '__'","sub_path":"butler/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"336056176","text":"\"\"\"\nCopyright (c) Facebook, Inc. and its affiliates.\n\"\"\"\nimport numpy as np\nimport logging\nfrom rotation import yaw_pitch\nfrom scipy.spatial.transform import Rotation\n\nMAX_PAN_RAD = np.pi / 4\nCAMERA_HEIGHT = 0.6\nARM_HEIGHT = 0.5\n\n\ndef angle_diff(a, b):\n r = b - a\n r = r % (2 * np.pi)\n if r > np.pi:\n r = r - 2 * np.pi\n return r\n\n\ndef get_camera_angles(camera_pos, look_at_pnt):\n \"\"\"get the new yaw/pan and pitch/tilt angle values and update the camera's\n new look direction.\"\"\"\n logging.debug(f\"look_at_point: {np.array(look_at_pnt)}\")\n logging.debug(f\"camera_position: {np.array(camera_pos)}\")\n logging.debug(f\"difference: {np.array(look_at_pnt) - np.array(camera_pos)}\")\n look_dir = np.array(look_at_pnt) - np.array(camera_pos)\n logging.debug(f\"Un-normalized look direction: {look_dir}\")\n if np.linalg.norm(look_dir) < 0.01:\n return 0.0, 0.0\n look_dir = look_dir / np.linalg.norm(look_dir)\n return yaw_pitch(look_dir)\n\n\ndef get_arm_angle(locobot_pos, marker_pos):\n H = 0.2\n dir_xy_vect = np.array(marker_pos)[:2] - np.array(locobot_pos)[:2]\n angle = -np.arctan((marker_pos[2] - H) / np.linalg.norm(dir_xy_vect))\n return angle\n\n\ndef get_bot_angle(locobot_pos, marker_pos):\n dir_xy_vect = np.array(marker_pos)[:2] - np.array(locobot_pos)[:2]\n angle = np.arctan(dir_xy_vect[1] / dir_xy_vect[0])\n return angle\n\n\ndef transform_pose(XYZ, current_pose):\n \"\"\"\n Transforms the point cloud into geocentric frame to account for\n camera position\n Input:\n XYZ : ...x3\n current_pose : camera position (x, y, theta (radians))\n Output:\n XYZ : ...x3\n \"\"\"\n R = Rotation.from_euler(\"Z\", current_pose[2]).as_matrix()\n XYZ = np.matmul(XYZ.reshape(-1, 3), R.T).reshape((-1, 3))\n XYZ[:, 0] = XYZ[:, 0] + current_pose[0]\n XYZ[:, 1] = XYZ[:, 1] + current_pose[1]\n return XYZ\n\n\ndef base_canonical_coords_to_pyrobot_coords(xyt):\n \"\"\"converts the robot's base coords from canonical to pyrobot coords.\"\"\"\n return [xyt[1], -xyt[0], xyt[2]]\n\n\ndef xyz_pyrobot_to_canonical_coords(xyz):\n \"\"\"converts 3D coords from pyrobot to canonical coords.\"\"\"\n return [-xyz[1], xyz[2], xyz[0]]\n","sub_path":"locobot/agent/locobot_mover_utils.py","file_name":"locobot_mover_utils.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"183707871","text":"from flask_moment import Moment\nfrom flask_json import FlaskJSON\nfrom flask_bootstrap import Bootstrap\nmoment = Moment()\nflaskjson = FlaskJSON()\nbootstrap=Bootstrap()\n\n# 初始化\ndef extension_config(app):\n moment.init_app(app)\n flaskjson.init_app(app)\n bootstrap.init_app(app)\n","sub_path":"8.flask_project/2.flask_web/app/extension/extensions.py","file_name":"extensions.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"537526353","text":"from telegram.ext import Updater, CommandHandler\nimport settings\n\ndef start_bot(bot, update):\n\ttxt = \"\"\"Привет!\n\tКак ты?\n\t\"\"\"\n\tupdate.messenger.reply_text(txt)\n\tprint(\"start\")\n\ndef main():\n\tupd = Updater('845270052:AAEEhdj9Qz4Q4ndVwwngKtNsGcB_rEcYz0Q')\n\t\n\tupd.dispatcher.add_handler(CommandHandler(\"start\", start_bot))\n\n\tupd.start_polling()\n\tupd.idle()\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"226053598","text":"from django.shortcuts import render, HttpResponse, redirect\nfrom .models import User\nfrom django.contrib import messages\n\n\ndef index(request):\n print('\\n======== inside INDEX ======')\n userDB = User.objects.all().order_by(\"-created_at\")\n context = {\n 'users': userDB\n }\n return render(request, \"semirestfulusers/index.html\", context)\ndef new(request):\n print('\\n======== inside NEW ======')\n # calls the new method to display a form allowing users to create a new user. This will need a template.\n return render(request, \"semirestfulusers/new.html\")\n\ndef edit(request, id):\n print('\\n======== inside EDIT ======')\n getid = User.objects.get(id=id)\n context = {\n 'user': getid\n }\n return render(request, \"semirestfulusers/edit.html\", context)\n\ndef update(request):\n print('\\n======== inside UPDATE ======')\n if request.method == 'POST': # pass the post data to the method we wrote and save the response in a variable called errors\n id = request.POST['id']\n print('-=-=-=-==-- =- =- -=- ID ', id)\n print('=====', request.POST['first_name'])\n print('=====', request.POST['last_name'])\n print('=====', request.POST['email'])\n errors = User.objects.user_validator(request.POST)\n print('erros? = ', errors)\n if len(errors):\n print('INSIDE ERRORS @@@@@@@')\n for key, value in errors.items(): # if the errors object contains anything, loop through each key-value pair and make a flash message\n print('#@$@#@#$@#$@# inside the key kanrue error')\n messages.error(request, value)\n return redirect('/users/'+id+'/edit') # redirect the user back to the form to fix the errors\n else:\n u = User.objects.get(id=id)\n u.first_name = request.POST['first_name']\n u.last_name = request.POST['last_name']\n u.email = request.POST['email']\n u.save()\n return redirect('/')\n\n\ndef show(request, id):\n print('\\n======== inside SHOW ======') \n userDB = User.objects.get(id=id)\n context = {\n 'users': userDB\n }\n return render(request, \"semirestfulusers/show.html\", context)\n\ndef create(request):\n print('\\n======== inside CREATE ======')\n if request.method == 'POST': # pass the post data to the method we wrote and save the response in a variable called errors\n print('=====', request.POST['first_name'])\n print('=====', request.POST['last_name'])\n print('=====', request.POST['email'])\n errors = User.objects.user_validator(request.POST)\n print('erros? = ', errors)\n if len(errors):\n print('INSIDE ERRORS @@@@@@@')\n for key, value in errors.items(): # if the errors object contains anything, loop through each key-value pair and make a flash message\n print('#@$@#@#$@#$@# inside the key kanrue error')\n messages.error(request, value)\n return redirect('/users/new') # redirect the user back to the form to fix the errors\n \n else:\n user = User.objects.create(first_name=request.POST['first_name'], last_name=request.POST['last_name'], email=request.POST['email'])\n user.save()\n return redirect('/')\n\ndef destroy(request, id):\n print('\\n======== inside DESTROY ======')\n User.objects.get(id=id).delete()\n return redirect('/')\n\n","sub_path":"Django/semiRestfulUsers/main/apps/semirestfulusers/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"86156286","text":"import json\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nfrom richard_utils import RichardUtils\nfrom article import Article\n\n\nclass Richard:\n\n RICARDO_URL = \"https://www.ricardo.ch\"\n RICARDO_URL_SEARCH = \"/en/s/{query}/?sort={sort_by}&next_offset={next_offset}\"\n\n SEARCH_OFFSET_STEP = 59\n\n # TODO: Put path constants somewhere else ?\n PATH_RESULT = [\"initialState\", \"srp\"]\n PATH_ARTICLE_LIST = PATH_RESULT + [\"results\"]\n PATH_TOTAL_ARTICLES_COUNT = PATH_RESULT + [\"totalArticlesCount\"]\n\n PATH_ARTICLE_URL = [\"url\"]\n\n SORT_BY_RELEVANCE = \"default\"\n SORT_BY_CLOSE_TO_END = \"close_to_end\"\n SORT_BY_NEWEST = \"newest\"\n SORT_BY_MOST_BIDS = \"most_bids\"\n SORT_BY_CHEAPEST = \"cheapest\"\n SORT_BY_MOST_EXPENSIVE = \"most_expensive\"\n\n CONDITION_NEW = \"new\"\n CONDITION_LIKE_NEW = \"like_new\"\n CONDITION_USED = \"used\"\n CONDITION_DAMAGED = \"damaged\"\n CONDITION_ANTIQUE = \"antique\"\n\n FILTER_PARAM_CONDITION = \"item_condition\"\n FILTER_CONDITION_NEW_SEE_DESCRIPTION = \"new_see_description\"\n FILTER_CONDITION_NEW_ORIGINAL_PACKAGE = \"new_original_package\"\n FILTER_CONDITION_USED = \"used\"\n FILTER_CONDITION_ANTIQUE = \"antik\"\n FILTER_CONDITION_DAMAGED = \"defekt\"\n\n FILTER_PARAM_OFFER_TYPE = \"offer_type\"\n FILTER_OFFER_TYPE_AUCTION = \"auction\"\n FILTER_OFFER_TYPE_FIXED_PRICE = \"fixed_price\"\n\n FILTER_PARAM_PRICE_RANGE_MIN = \"range_filters.price.min\"\n FILTER_PARAM_PRICE_RANGE_MAX = \"range_filters.price.max\"\n\n def __init__(self):\n self.article_list: list = []\n\n # TODO: Really heavy function, could use some cleaning up\n def load_articles(self, query: str, quantity: int = 100, sort_by: str = SORT_BY_CLOSE_TO_END, filter_str: str = \"\"):\n result_dict = self.load_result_dict(Richard.build_search_url(query, sort_by, filter_string=filter_str))\n total_articles_count = RichardUtils.access_property(result_dict, Richard.PATH_TOTAL_ARTICLES_COUNT)\n\n loaded_articles = []\n current_offset = 0\n\n if total_articles_count < quantity:\n quantity = total_articles_count\n\n while quantity > len(loaded_articles):\n articles_list = RichardUtils.access_property(result_dict, Richard.PATH_ARTICLE_LIST)\n\n for article in articles_list:\n article_url = Richard.RICARDO_URL + RichardUtils.access_property(article, Richard.PATH_ARTICLE_URL)\n article_obj = Article(article_url)\n article_obj.quick_update(article)\n loaded_articles.append(article_obj)\n\n if quantity <= len(loaded_articles):\n break\n\n current_offset += Richard.SEARCH_OFFSET_STEP\n result_dict = self.load_result_dict(Richard.build_search_url(query, sort_by, current_offset, filter_str))\n\n self.article_list.extend(loaded_articles)\n\n def update_articles(self):\n for article in self.article_list:\n article.update()\n\n def clear_articles(self):\n self.article_list.clear()\n\n def sort_list_by_end_date(self):\n self.article_list.sort(key=lambda x: x.article_end_date)\n\n # TODO: Clean up\n def sort_list_by_price(self):\n lmbd = lambda x: x.article_next_bid if x.article_offer_type != \"fixed_price\" else x.article_fixed_price\n self.article_list.sort(key=lmbd)\n\n @staticmethod\n def load_result_dict(search_url: str) -> dict:\n page = requests.get(search_url)\n soup = BeautifulSoup(page.content, 'html.parser')\n soup_js = soup.find_all(\"script\")[4]\n return json.loads(soup_js.contents[0][15:-1])\n\n # TODO: Function too heavy ?\n @staticmethod\n def build_filter_string(price_range: tuple = None, condition: list = None, offer_type: list = None):\n filter_list = []\n str_price_range = \"\"\n if price_range is not None and type(price_range) is tuple:\n str_price_range += Richard.FILTER_PARAM_PRICE_RANGE_MIN + \"=\" + str(min(price_range))\n str_price_range += \"&\"\n str_price_range += Richard.FILTER_PARAM_PRICE_RANGE_MAX + \"=\" + str(max(price_range))\n filter_list.append(str_price_range)\n\n str_condition = \"\"\n if condition is not None and len(condition) > 0:\n str_condition += Richard.FILTER_PARAM_CONDITION + \"=\"\n str_condition += \"%2C\".join(condition)\n filter_list.append(str_condition)\n\n str_offer_type = \"\"\n if offer_type is not None and len(offer_type) > 0:\n str_offer_type += Richard.FILTER_PARAM_OFFER_TYPE + \"=\"\n str_offer_type += \"%2C\".join(offer_type)\n filter_list.append(str_offer_type)\n\n return \"&\".join(filter_list)\n\n @staticmethod\n def build_search_url(query: str, sort_by: str, next_offset: int = 0, filter_string: str = \"\") -> str:\n return Richard.RICARDO_URL + Richard.RICARDO_URL_SEARCH.format(\n query=query,\n sort_by=sort_by,\n next_offset=next_offset\n ) + filter_string\n\n","sub_path":"richard.py","file_name":"richard.py","file_ext":"py","file_size_in_byte":5012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"366920383","text":"# 複数の約定情報websocketを束ねて一本化するためのwebsocketプロキシ\n# 主にローカル環境でのデータ蓄積、分析、モニタリングなどで\n# 複数のwebsocketを生成したくない(できない)場合を想定しています。\n# 処理遅延が発生するので本番環境ではおすすめしません。\n\n# websocketサーバのポートとデバッグ用のポートを指定して実行\n# $ python3 trade_proxy.py 51000 51001\n\n# クライアント側のon_openで購読したいチャンネルの情報を送信\n# ws.send('{\"exchange\": \"Bitflyer\", \"symbol\": \"FX_BTC_JPY\"}')\n# 複数チャンネルには対応していないのでチャンネルごとにwebsocketを生成してください。\n\nimport logging\nimport json\nimport sys\n\nfrom websocket_server import WebsocketServer\n\nimport botfw as fw\n\nserver_port, debug_port = sys.argv[1:]\n\nlog = logging.getLogger()\nfw.setup_logger()\n\n# デバッグ用\ncmd = fw.Cmd(globals())\ncmd_server = fw.CmdServer(int(debug_port))\ncmd_server.register_command(cmd.eval)\ncmd_server.register_command(cmd.exec)\ncmd_server.register_command(cmd.print, log=False)\n\nclients = {} # {client: ((exchange, symbol), callback)}\ntrades = {} # {(exchange, symbol)}\n\n\ndef on_new_client(client, server):\n addr = client['address']\n log.info(f'{addr}: OPEN')\n\n clients[addr] = ()\n\n\ndef on_client_left(client, server):\n addr = client['address']\n log.info(f'{addr}: CLOSE')\n\n info = clients[addr]\n if info:\n key, cb = info\n t = trades[key]\n t.remove_callback(cb)\n if not t.cb:\n t.ws.stop()\n del trades[key]\n\n del clients[addr]\n\n\ndef on_message_received(client, server, message):\n addr = client['address']\n log.info(f'{addr}: \"{message}\"')\n\n data = json.loads(message)\n exchange = data['exchange']\n symbol = data['symbol']\n key = (exchange, symbol)\n\n if clients[addr]:\n log.error(f'{addr}: already subscribed channel')\n return\n\n t = trades.get(key)\n if not t:\n ex = getattr(fw, exchange)\n t = ex.Trade(symbol)\n trades[key] = t\n\n def cb(ts, price, size):\n server.send_message(client, json.dumps([ts, price, size]))\n\n t.add_callback(cb)\n clients[addr] = (key, cb)\n\n\nif __name__ == \"__main__\":\n server = WebsocketServer(port=int(server_port), host='127.0.0.1')\n server.set_fn_new_client(on_new_client)\n server.set_fn_client_left(on_client_left)\n server.set_fn_message_received(on_message_received)\n server.run_forever()\n","sub_path":"samples/etc/trade_proxy.py","file_name":"trade_proxy.py","file_ext":"py","file_size_in_byte":2554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"223781212","text":"import psycopg2\nfrom bs4 import *\nimport requests\nimport random as rd\nurl = 'http://kinoteatr.kg/index.php/category/view?id=17'\n\n\nname_film = []\ngenre = []\ngenres = []\nyear = []\n\nreq = requests.get(url)\nscr = req.text\n# print (scr)\nsoup = BeautifulSoup(scr, \"html.parser\")\nall_product_h = soup.find_all(class_ =\"card-title text-danger\")\nfor i in all_product_h:\n name_film.append(i.text) \nprint(name_film) \n\n\nall_product_a = soup.find_all(class_ =\"card-text\")\nfor j in all_product_a:\n genre.append(j.text)\n# print(genre)\n\n\nfor item in range(len(genre)):\n if item % 2 == 0:\n genres.append(genre[item][6:])\n# print (genres)\n \nfor item in range(len(genre)):\n if item % 2 != 0:\n year.append(genre[item][5:])\n# print (year)\n\ndatabase = 'films'\nuser = 'postgres'\npassword = 'postgres'\nhost = '127.0.0.1'\nport = '5432'\n\nconnection = psycopg2.connect(\n database=database,\n user=user,\n password=password,\n host=host,\n port=port\n)\nprint ('''\n ПОДКЛЮЧЕНИЯ ПРОШЛО УСПЕШНО!!!\n \n ВЫ ЯВЛЯЙТЕСЬ PostgreSQL ПОЛЬЗОВАТЕЛЕМ\n''')\ncursor = connection.cursor()\n\nquery = '''insert into film (name,janr,year) values '''\nfor i in range (len(name_film)):\n query += f'''(\n '{name_film[i]}',\n '{genres[i]}',\n '{year[i]}'\n\n ),'''\nprint ('INSERT 01')\nsql_query = query[:-1]+';'\ncursor.execute(sql_query)\nconnection.commit()\ncursor.close()\nconnection.close()","sub_path":"hakaton3/hacaton.py","file_name":"hacaton.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"558935012","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index),\n url(r'^register$', views.register),\n url(r'^home_dashboard$', views.home_dashboard),\n url(r'^login$', views.login),\n url(r'^logout$', views.logout),\n url(r'^addHome/(?P\\d+)$', views.addHome),\n url(r'^add/(?P\\d+)$', views.add),\n url(r'^wishList/(?P\\d+)$', views.wishList),\n url(r'^addWish/(?P\\d+)/(?P\\d+)$', views.addWish),\n url(r'^removeWish/(?P\\d+)/(?P\\d+)$', views.removeWish),\n url(r'^delete/(?P\\d+)/(?P\\d+)$', views.delete),\n url(r'^descHome/(?P\\d+)/(?P\\d+)$', views.descHome),\n]","sub_path":"apps/projectApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"634761510","text":"from django.http.response import HttpResponse\nfrom django.shortcuts import render\nimport pandas as pd\nimport numpy as np\nimport string\nfrom imblearn.over_sampling import SMOTE\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport spacy\nfrom sklearn.preprocessing import LabelEncoder\nfrom spacy.lang.en.stop_words import STOP_WORDS\nfrom spacy.lang.en import English\nfrom sklearn.ensemble import RandomForestClassifier\nimport logging\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nfrom imblearn import under_sampling\n# Create your views here.\ndef home(request):\n render(request,'home.html')\n\ndef index(request):\n return render(request, 'registration.html')\ndef clean_text(text):\n text = text.strip().lower()\n nopunc =[char for char in text if char not in string.punctuation and not char.isdigit()]\n nopunc=''.join(nopunc)\n list = [word for word in nopunc.split()]\n return \" \".join([word for word in list])\ndef convert_bool(value):\n if value == 'yes':\n return 1\n else :\n return 0\ndef predict(request):\n df = pd.read_csv('C:/Users/home/Downloads/Fake Job Predictor/fake_jobs.csv',index_col=0)\n title = request.POST[\"title\"]\n company_profile = request.POST[\"company_profile\"]\n description = request.POST[\"description\"]\n requirements = request.POST[\"requirements\"]\n benefits = request.POST[\"benefits\"]\n has_questions = request.POST[\"has_questions\"]\n has_questions = convert_bool(has_questions)\n employment_type = request.POST[\"employment_type\"]\n loc = request.POST[\"loc\"]\n salary_range = request.POST[\"salary_range\"]\n salary_range = convert_bool(salary_range)\n text = title+ ' ' + company_profile+' '+description+' '+requirements+' '+benefits\n df.fillna('',inplace=True)\n df['fraudulent'] = df['fraudulent'].astype(int)\n fraudulent = ''\n \n \n dict = {'title' : [title] , 'company_profile' : [company_profile], 'description' : [description],'requirements' :[requirements],'benefits':[benefits],'fraudulent' : [fraudulent],'has_questions' : [has_questions], 'employment_type' : [employment_type] , 'loc' : loc, 'salary_range' : [salary_range]}\n test_df = pd.DataFrame(dict)\n test_df['text'] = clean_text(text)\n del test_df['title']\n del test_df['company_profile']\n del test_df['description']\n del test_df['requirements']\n del test_df['benefits']\n df = df.append(test_df,ignore_index=True)\n enc = LabelEncoder()\n df.loc[:,['employment_type','loc']] = df.loc[:,['employment_type','loc']].apply(enc.fit_transform)\n tf = TfidfVectorizer(max_features=2000)\n df1 = pd.DataFrame(tf.fit_transform(df['text']).toarray(),columns=tf.get_feature_names())\n df.drop(['text'],axis=1,inplace=True)\n main_df = pd.concat([df1,df],axis=1)\n y_train = main_df.iloc[:17880,-1]\n\n x_train = main_df.iloc[:17880,:-1]\n x_test = main_df.iloc[17880:,:-1]\n x_train = np.asarray(x_train).astype('float')\n y_train = np.asarray(y_train).astype('int')\n x_test = np.asarray(x_test).astype('float')\n sm = under_sampling.RandomUnderSampler(sampling_strategy='auto',random_state=42)\n x_train_under_sample , y_train_under_sample = sm.fit_resample(x_train,y_train)\n x_train_under_sample = np.asarray(x_train_under_sample)\n y_train_under_sample = np.asarray(y_train_under_sample)\n model = Sequential()\n model.add(Dense(units=150, activation='tanh'))\n model.add(Dense(units=100, activation='tanh'))\n model.add(Dense(1, activation='sigmoid'))\n model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n model.fit(\n x=x_train_under_sample,\n y=y_train_under_sample,\n epochs=35,\n shuffle=True,\n verbose=2,\n batch_size = 20,\n )\n pred = model.predict(x_test)\n pred = [int(round(x[0])) for x in pred]\n prediction = pred[0]\n if (prediction == 1):\n return render(request, 'fake.html')\n else :\n return render(request, 'real.html')","sub_path":"fakeJobs/jobs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"618616566","text":"import unittest\n\nfrom pirate.registry import Registry\nfrom pirate.dbconfig.base import InteractionBase\n\nfrom utils import init_db, tear_down_db, User, Avatar, Picture, Coltest\n\nclass DBConfigTest(unittest.TestCase):\n def setUp(self):\n init_db(self)\n self.user = User(first_name='First', last_name='Last', age=10).save()\n self.avatar = Avatar(name='an avatar name', user_id=self.user.id).save()\n self.picture = Picture(name='a pic', size=10, user_id=self.user.id).save()\n self.dbconfig = Registry.get_config()\n\n def tearDown(self):\n tear_down_db(self)\n\n def test_select(self):\n # make a fake user\n user = User(first_name='Another First').save()\n tablename = User.tablename()\n\n where = ['first_name = ?', 'First']\n result = self.dbconfig.select(tablename, where=where, limit=1, orderby='first_name ASC')\n self.assertTrue(result is not None)\n self.assertEqual(result['id'], self.user.id)\n\n result = self.dbconfig.select(tablename, limit=100, orderby='first_name ASC' )\n self.assertEqual(len(result), 2)\n self.assertTrue(result[0]['id'] == user.id and result[1]['id'] == self.user.id)\n\n def test_delete(self):\n tablename = User.tablename()\n\n User(first_name='Another First').save()\n self.dbconfig.delete(tablename, ['first_name like ?', '%nother Fir%'])\n\n result = self.dbconfig.select(tablename)\n self.assertEqual(len(result), 1)\n self.assertTrue(result[0]['id'] == self.user.id)\n\n def test_update(self):\n tablename = User.tablename()\n user = User(first_name='Another First').save()\n\n # Save must always return the object\n self.assertEqual(user, user.save())\n\n args = {'first_name': 'test', 'last_name': 'foo', 'age': 91}\n self.dbconfig.update(tablename, args, ['id = ?', user.id])\n user.refresh()\n\n for key, value in args.items():\n self.assertEqual(value, getattr(user, key))\n\n def test_insert(self):\n tablename = User.tablename()\n args = {'first_name': 'test', 'last_name': 'foo', 'age': 91}\n self.dbconfig.insert(tablename, args)\n\n where = ['first_name = ? AND last_name = ? AND age = ?']\n where = where + ['test', 'foo', 91]\n users = User.find(where=where)\n\n self.assertEqual(len(users), 1)\n for key, value in args.items():\n self.assertEqual(value, getattr(users[0], key))\n\n def test_insert_many(self):\n tablename = User.tablename()\n\n args = []\n for counter in range(10):\n args.append({'first_name': 'test_insert_many', 'last_name': 'foo', 'age': counter})\n self.dbconfig.insert_many(tablename, args)\n\n users = User.find(where=['first_name = ?', 'test_insert_many'], orderby='age ASC')\n\n for counter in range(10):\n for key, value in args[counter].items():\n self.assertEqual(value, getattr(users[counter], key))\n\n def test_insert_obj(self):\n args = {'first_name': 'test_insert_obj', 'last_name': 'foo', 'age': 91}\n user = User(**args)\n\n self.dbconfig.insert_obj(user)\n user = User.find(where=['first_name = ?', 'test_insert_obj'], limit=1)\n\n for key, value in args.items():\n self.assertEqual(value, getattr(user, key))\n\n def test_update_obj(self):\n args = {'first_name': 'test_insert_obj', 'last_name': 'foo', 'age': 91}\n user = User(**args).save()\n\n args = {'first_name': 'test_insert_obj_foo', 'last_name': 'bar', 'age': 191}\n for key, value in args.items():\n setattr(user, key, value)\n\n self.dbconfig.update_obj(user)\n user = User.find(user.id)\n\n for key, value in args.items():\n self.assertEqual(value, getattr(user, key))\n\n def test_colname_escaping(self):\n args = {'select': 'some text', 'where': 'other text'}\n coltest = Coltest(**args)\n self.dbconfig.insert_obj(coltest)\n\n args = {'select': 'other text', 'where': 'some text'}\n for key, value in args.items():\n setattr(coltest, key, value)\n\n self.dbconfig.update_obj(coltest)\n\n tablename = Coltest.tablename()\n colnames = self.dbconfig.escape_col_names(['select'])\n ctest = self.dbconfig.select(tablename, where=['%s = ?' % colnames[0], args['select']], limit=1)\n\n for key, value in args.items():\n self.assertEqual(value, ctest[key])\n\n def test_unicode_logging(self):\n import logging\n InteractionBase.LOG = logging\n\n ustr = u'\\N{SNOWMAN}'\n InteractionBase().log(ustr, [ustr], {ustr: ustr})\n\n ustr = '\\xc3\\xa8'\n InteractionBase().log(ustr, [ustr], {ustr: ustr})\n\n InteractionBase.LOG = False\n\n\n","sub_path":"pirate/tests/test_dbconfig.py","file_name":"test_dbconfig.py","file_ext":"py","file_size_in_byte":4809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"120518174","text":"from pygments.lexer import RegexLexer, bygroups, include\nfrom pygments.token import *\n\n__all__ = [\"BroLexer\"]\n\nclass BroLexer(RegexLexer):\n name = 'Bro'\n aliases = ['bro']\n filenames = ['*.bro']\n\n _hex = r'[0-9a-fA-F_]+'\n _float = r'((\\d*\\.?\\d+)|(\\d+\\.?\\d*))([eE][-+]?\\d+)?'\n _h = r'[A-Za-z0-9][-A-Za-z0-9]*'\n\n tokens = {\n 'root': [\n # Whitespace\n ('^@.*?\\n', Comment.Preproc),\n (r'#.*?\\n', Comment.Single),\n (r'\\n', Text),\n (r'\\s+', Text),\n (r'\\\\\\n', Text),\n # Keywords\n (r'(add|alarm|break|case|const|continue|delete|do|else|enum|event'\n r'|export|for|function|if|global|local|module|next'\n r'|of|print|redef|return|schedule|when|while)\\b', Keyword),\n (r'(addr|any|bool|count|counter|double|file|int|interval|net'\n r'|pattern|port|record|set|string|subnet|table|time|timer'\n r'|vector)\\b', Keyword.Type),\n (r'(T|F)\\b', Keyword.Constant),\n (r'(&)((?:add|delete|expire)_func|attr|(create|read|write)_expire'\n r'|default|disable_print_hook|raw_output|encrypt|group|log'\n r'|mergeable|optional|persistent|priority|redef'\n r'|rotate_(?:interval|size)|synchronized)\\b', bygroups(Punctuation,\n Keyword)),\n (r'\\s+module\\b', Keyword.Namespace),\n # Addresses, ports and networks\n (r'\\d+/(tcp|udp|icmp|unknown)\\b', Number),\n (r'(\\d+\\.){3}\\d+', Number),\n (r'(' + _hex + r'){7}' + _hex, Number),\n (r'0x' + _hex + r'(' + _hex + r'|:)*::(' + _hex + r'|:)*', Number),\n (r'((\\d+|:)(' + _hex + r'|:)*)?::(' + _hex + r'|:)*', Number),\n (r'(\\d+\\.\\d+\\.|(\\d+\\.){2}\\d+)', Number),\n # Hostnames\n (_h + r'(\\.' + _h + r')+', String),\n # Numeric\n (_float + r'\\s+(day|hr|min|sec|msec|usec)s?\\b', Literal.Date),\n (r'0[xX]' + _hex, Number.Hex),\n (_float, Number.Float),\n (r'\\d+', Number.Integer),\n (r'/', String.Regex, 'regex'),\n (r'\"', String, 'string'),\n # Operators\n (r'[!%*/+-:<=>?~|]', Operator),\n (r'([-+=&|]{2}|[+-=!><]=)', Operator),\n (r'(in|match)\\b', Operator.Word),\n (r'[{}()\\[\\]$.,;]', Punctuation),\n # Identfier\n (r'([_a-zA-Z]\\w*)(::)', bygroups(Name, Name.Namespace)),\n (r'[a-zA-Z_][a-zA-Z_0-9]*', Name)\n ],\n 'string': [\n (r'\"', String, '#pop'),\n (r'\\\\([\\\\abfnrtv\"\\']|x[a-fA-F0-9]{2,4}|[0-7]{1,3})', String.Escape),\n (r'[^\\\\\"\\n]+', String),\n (r'\\\\\\n', String),\n (r'\\\\', String)\n ],\n 'regex': [\n (r'/', String.Regex, '#pop'),\n (r'\\\\[\\\\nt/]', String.Regex), # String.Escape is too intense.\n (r'[^\\\\/\\n]+', String.Regex),\n (r'\\\\\\n', String.Regex),\n (r'\\\\', String.Regex)\n ]\n }\n","sub_path":"classifiers/bro-2.1/doc/ext/bro_lexer/bro.py","file_name":"bro.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"23949928","text":"# Utilities相關函式庫\nimport os\nimport random\nimport pickle\nfrom glob import glob\n\n# 圖像處理相關函式庫\nimport cv2\nimport numpy as np\n\n# 讓Keras只使用GPU來進行訓練\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = '0'\n\nimport colorsys\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom PIL import Image, ImageDraw, ImageFont\n\n# 深度學習相關函式庫\nfrom keras.models import Sequential, Model\nfrom keras.layers import Reshape, Activation, Conv2D, Input, MaxPooling2D, BatchNormalization, Flatten, Dense, Lambda\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard\nfrom keras.optimizers import SGD, Adam, RMSprop\nfrom keras.layers.merge import concatenate\nimport keras.backend as K\nfrom keras.utils import plot_model\nimport tensorflow as tf\n\n# 專案相關函式庫\nfrom yolov2.preprocessing import parse_annotation, udacity1_annotation, BatchGenerator\nfrom yolov2.utils import WeightReader, decode_netout, draw_boxes\n\n\n# Yolov2 參數\nLABELS = ['Car']\n\nIMAGE_H, IMAGE_W = 416, 416 # 模型輸入的圖像長寬\nGRID_H, GRID_W = 13, 13\nBOX = 5\nCLASS = len(LABELS)\nCLASS_WEIGHTS = np.ones(CLASS, dtype='float32')\nOBJ_THRESHOLD = 0.3\nNMS_THRESHOLD = 0.3 # NMS非極大值抑制 , 說明(https://chenzomi12.github.io/2016/12/14/YOLO-nms/)\nANCHORS = [0.57273, 0.677385, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282, 3.52778, 9.77052, 9.16828]\n\nNO_OBJECT_SCALE = 1.0\nOBJECT_SCALE = 5.0\nCOORD_SCALE = 1.0\nCLASS_SCALE = 1.0\n\nBATCH_SIZE = 20\nWARM_UP_BATCHES = 0\nTRUE_BOX_BUFFER = 50\n\n# 用來產生Keras訓練模型的BatchGenerator的設定:\ngenerator_config = {\n 'IMAGE_H': IMAGE_H, # YOLOv2網絡輸入的image_h\n 'IMAGE_W': IMAGE_W, # YOLOv2網絡輸入的image_w\n 'GRID_H': GRID_H, # 直向網格的拆分數量\n 'GRID_W': GRID_W, # 橫向網格的拆分數量\n 'BOX': BOX, # 每個單一網格要預測的邊界框數量\n 'LABELS': LABELS, # 要預測的圖像種類列表\n 'CLASS': len(LABELS), # 要預測的圖像種類數\n 'ANCHORS': ANCHORS, # 每個單一網格要預測的邊界框時用的錨點\n 'BATCH_SIZE': BATCH_SIZE, # 訓練時的批量數\n 'TRUE_BOX_BUFFER': 50, # 一個訓練圖像最大數量的邊界框數\n}\n\n# Darknet預訓練權重檔與訓練/驗證資料目錄\nwt_path = 'yolov2.weights'\n\n\ndef space_to_depth_x2(x):\n return tf.space_to_depth(x, block_size=2)\n\n\ninput_image = Input(shape=(IMAGE_H, IMAGE_W, 3))\ntrue_boxes = Input(shape=(1, 1, 1, TRUE_BOX_BUFFER, 4))\n\n\n# YOLOv2 網絡架構\ndef yolov2_model():\n # Layer 1\n x = Conv2D(32, (3, 3), strides=(1, 1), padding='same', name='conv_1', use_bias=False)(input_image)\n x = BatchNormalization(name='norm_1')(x)\n x = LeakyReLU(alpha=0.1)(x)\n x = MaxPooling2D(pool_size=(2, 2))(x)\n\n # Layer 2\n x = Conv2D(64, (3, 3), strides=(1, 1), padding='same', name='conv_2', use_bias=False)(x)\n x = BatchNormalization(name='norm_2')(x)\n x = LeakyReLU(alpha=0.1)(x)\n x = MaxPooling2D(pool_size=(2, 2))(x)\n\n # Layer 3\n x = Conv2D(128, (3, 3), strides=(1, 1), padding='same', name='conv_3', use_bias=False)(x)\n x = BatchNormalization(name='norm_3')(x)\n x = LeakyReLU(alpha=0.1)(x)\n\n # Layer 4\n x = Conv2D(64, (1, 1), strides=(1, 1), padding='same', name='conv_4', use_bias=False)(x)\n x = BatchNormalization(name='norm_4')(x)\n x = LeakyReLU(alpha=0.1)(x)\n\n # Layer 5\n x = Conv2D(128, (3, 3), strides=(1, 1), padding='same', name='conv_5', use_bias=False)(x)\n x = BatchNormalization(name='norm_5')(x)\n x = LeakyReLU(alpha=0.1)(x)\n x = MaxPooling2D(pool_size=(2, 2))(x)\n\n # Layer 6\n x = Conv2D(256, (3, 3), strides=(1, 1), padding='same', name='conv_6', use_bias=False)(x)\n x = BatchNormalization(name='norm_6')(x)\n x = LeakyReLU(alpha=0.1)(x)\n\n # Layer 7\n x = Conv2D(128, (1, 1), strides=(1, 1), padding='same', name='conv_7', use_bias=False)(x)\n x = BatchNormalization(name='norm_7')(x)\n x = LeakyReLU(alpha=0.1)(x)\n\n # Layer 8\n x = Conv2D(256, (3, 3), strides=(1, 1), padding='same', name='conv_8', use_bias=False)(x)\n x = BatchNormalization(name='norm_8')(x)\n x = LeakyReLU(alpha=0.1)(x)\n x = MaxPooling2D(pool_size=(2, 2))(x)\n\n # Layer 9\n x = Conv2D(512, (3, 3), strides=(1, 1), padding='same', name='conv_9', use_bias=False)(x)\n x = BatchNormalization(name='norm_9')(x)\n x = LeakyReLU(alpha=0.1)(x)\n\n # Layer 10\n x = Conv2D(256, (1, 1), strides=(1, 1), padding='same', name='conv_10', use_bias=False)(x)\n x = BatchNormalization(name='norm_10')(x)\n x = LeakyReLU(alpha=0.1)(x)\n\n # Layer 11\n x = Conv2D(512, (3, 3), strides=(1, 1), padding='same', name='conv_11', use_bias=False)(x)\n x = BatchNormalization(name='norm_11')(x)\n x = LeakyReLU(alpha=0.1)(x)\n\n # Layer 12\n x = Conv2D(256, (1, 1), strides=(1, 1), padding='same', name='conv_12', use_bias=False)(x)\n x = BatchNormalization(name='norm_12')(x)\n x = LeakyReLU(alpha=0.1)(x)\n\n # Layer 13\n x = Conv2D(512, (3, 3), strides=(1, 1), padding='same', name='conv_13', use_bias=False)(x)\n x = BatchNormalization(name='norm_13')(x)\n x = LeakyReLU(alpha=0.1)(x)\n\n skip_connection = x\n\n x = MaxPooling2D(pool_size=(2, 2))(x)\n\n # Layer 14\n x = Conv2D(1024, (3, 3), strides=(1, 1), padding='same', name='conv_14', use_bias=False)(x)\n x = BatchNormalization(name='norm_14')(x)\n x = LeakyReLU(alpha=0.1)(x)\n\n # Layer 15\n x = Conv2D(512, (1, 1), strides=(1, 1), padding='same', name='conv_15', use_bias=False)(x)\n x = BatchNormalization(name='norm_15')(x)\n x = LeakyReLU(alpha=0.1)(x)\n\n # Layer 16\n x = Conv2D(1024, (3, 3), strides=(1, 1), padding='same', name='conv_16', use_bias=False)(x)\n x = BatchNormalization(name='norm_16')(x)\n x = LeakyReLU(alpha=0.1)(x)\n\n # Layer 17\n x = Conv2D(512, (1, 1), strides=(1, 1), padding='same', name='conv_17', use_bias=False)(x)\n x = BatchNormalization(name='norm_17')(x)\n x = LeakyReLU(alpha=0.1)(x)\n\n # Layer 18\n x = Conv2D(1024, (3, 3), strides=(1, 1), padding='same', name='conv_18', use_bias=False)(x)\n x = BatchNormalization(name='norm_18')(x)\n x = LeakyReLU(alpha=0.1)(x)\n\n # Layer 19\n x = Conv2D(1024, (3, 3), strides=(1, 1), padding='same', name='conv_19', use_bias=False)(x)\n x = BatchNormalization(name='norm_19')(x)\n x = LeakyReLU(alpha=0.1)(x)\n\n # Layer 20\n x = Conv2D(1024, (3, 3), strides=(1, 1), padding='same', name='conv_20', use_bias=False)(x)\n x = BatchNormalization(name='norm_20')(x)\n x = LeakyReLU(alpha=0.1)(x)\n\n # Layer 21\n skip_connection = Conv2D(64, (1, 1), strides=(1, 1), padding='same', name='conv_21', use_bias=False)(\n skip_connection)\n skip_connection = BatchNormalization(name='norm_21')(skip_connection)\n skip_connection = LeakyReLU(alpha=0.1)(skip_connection)\n skip_connection = Lambda(space_to_depth_x2)(skip_connection)\n\n x = concatenate([skip_connection, x])\n\n # Layer 22\n x = Conv2D(1024, (3, 3), strides=(1, 1), padding='same', name='conv_22', use_bias=False)(x)\n x = BatchNormalization(name='norm_22')(x)\n x = LeakyReLU(alpha=0.1)(x)\n\n # Layer 23\n x = Conv2D(BOX * (4 + 1 + CLASS), (1, 1), strides=(1, 1), padding='same', name='conv_23')(x)\n output = Reshape((GRID_H, GRID_W, BOX, 4 + 1 + CLASS))(x)\n\n # small hack to allow true_boxes to be registered when Keras build the model\n # for more information: https://github.com/fchollet/keras/issues/2790\n output = Lambda(lambda args: args[0])([output, true_boxes])\n\n model = Model([input_image, true_boxes], output)\n model.summary() # 打印模型\n return model\n\n\ndef yolov2_load_weight():\n weight_reader = WeightReader(wt_path) # 初始讀取Darknet預訓練權重檔物件\n weight_reader.reset()\n nb_conv = 23 # 總共有23層的卷積層\n\n for i in range(1, nb_conv + 1):\n conv_layer = model.get_layer('conv_' + str(i))\n\n # 在conv_1~conv_22的卷積組合裡都包含了\"conv + norm\"二層, 只有conv_23是獨立一層\n if i < nb_conv:\n print(\"handle norm_\" + str(i) + \" start\")\n norm_layer = model.get_layer('norm_' + str(i)) # 取得BatchNormalization層\n\n size = np.prod(norm_layer.get_weights()[0].shape) # 取得BatchNormalization層的參數量\n print(\"shape: \", norm_layer.get_weights()[0].shape)\n\n beta = weight_reader.read_bytes(size)\n gamma = weight_reader.read_bytes(size)\n mean = weight_reader.read_bytes(size)\n var = weight_reader.read_bytes(size)\n weights = norm_layer.set_weights([gamma, beta, mean, var])\n print(\"handle norm_\" + str(i) + \" completed\")\n\n if len(conv_layer.get_weights()) > 1:\n print(\"handle conv_\" + str(i) + \" start\")\n print(\"len:\", len(conv_layer.get_weights()))\n bias = weight_reader.read_bytes(np.prod(conv_layer.get_weights()[1].shape))\n kernel = weight_reader.read_bytes(np.prod(conv_layer.get_weights()[0].shape))\n kernel = kernel.reshape(list(reversed(conv_layer.get_weights()[0].shape)))\n kernel = kernel.transpose([2, 3, 1, 0])\n conv_layer.set_weights([kernel, bias])\n print(\"handle conv_\" + str(i) + \" completed\")\n else:\n print(\"handle conv_\" + str(i) + \" start\")\n kernel = weight_reader.read_bytes(np.prod(conv_layer.get_weights()[0].shape))\n kernel = kernel.reshape(list(reversed(conv_layer.get_weights()[0].shape)))\n kernel = kernel.transpose([2, 3, 1, 0])\n conv_layer.set_weights([kernel])\n print(\"handle conv_\" + str(i) + \" completed\")\n\n\ndef custom_loss(y_true, y_pred):\n mask_shape = tf.shape(y_true)[:4]\n\n cell_x = tf.to_float(tf.reshape(tf.tile(tf.range(GRID_W), [GRID_H]), (1, GRID_H, GRID_W, 1, 1)))\n cell_y = tf.transpose(cell_x, (0, 2, 1, 3, 4))\n\n cell_grid = tf.tile(tf.concat([cell_x, cell_y], -1), [BATCH_SIZE, 1, 1, 5, 1])\n\n coord_mask = tf.zeros(mask_shape)\n conf_mask = tf.zeros(mask_shape)\n class_mask = tf.zeros(mask_shape)\n\n seen = tf.Variable(0.)\n total_recall = tf.Variable(0.)\n\n \"\"\"\n Adjust prediction\n \"\"\"\n # adjust x and y\n pred_box_xy = tf.sigmoid(y_pred[..., :2]) + cell_grid\n\n # adjust w and h\n pred_box_wh = tf.exp(y_pred[..., 2:4]) * np.reshape(ANCHORS, [1, 1, 1, BOX, 2])\n\n # adjust confidence\n pred_box_conf = tf.sigmoid(y_pred[..., 4])\n\n # adjust class probabilities\n pred_box_class = y_pred[..., 5:]\n\n \"\"\"\n Adjust ground truth\n \"\"\"\n # adjust x and y\n true_box_xy = y_true[..., 0:2] # relative position to the containing cell\n\n # adjust w and h\n true_box_wh = y_true[..., 2:4] # number of cells accross, horizontally and vertically\n\n # adjust confidence\n true_wh_half = true_box_wh / 2.\n true_mins = true_box_xy - true_wh_half\n true_maxes = true_box_xy + true_wh_half\n\n pred_wh_half = pred_box_wh / 2.\n pred_mins = pred_box_xy - pred_wh_half\n pred_maxes = pred_box_xy + pred_wh_half\n\n intersect_mins = tf.maximum(pred_mins, true_mins)\n intersect_maxes = tf.minimum(pred_maxes, true_maxes)\n intersect_wh = tf.maximum(intersect_maxes - intersect_mins, 0.)\n intersect_areas = intersect_wh[..., 0] * intersect_wh[..., 1]\n\n true_areas = true_box_wh[..., 0] * true_box_wh[..., 1]\n pred_areas = pred_box_wh[..., 0] * pred_box_wh[..., 1]\n\n union_areas = pred_areas + true_areas - intersect_areas\n iou_scores = tf.truediv(intersect_areas, union_areas)\n\n true_box_conf = iou_scores * y_true[..., 4]\n\n # adjust class probabilities\n true_box_class = tf.argmax(y_true[..., 5:], -1)\n\n \"\"\"\n Determine the masks\n \"\"\"\n # coordinate mask: simply the position of the ground truth boxes (the predictors)\n coord_mask = tf.expand_dims(y_true[..., 4], axis=-1) * COORD_SCALE\n\n # confidence mask: penelize predictors + penalize boxes with low IOU\n # penalize the confidence of the boxes, which have IOU with some ground truth box < 0.6\n true_xy = true_boxes[..., 0:2]\n true_wh = true_boxes[..., 2:4]\n\n true_wh_half = true_wh / 2.\n true_mins = true_xy - true_wh_half\n true_maxes = true_xy + true_wh_half\n\n pred_xy = tf.expand_dims(pred_box_xy, 4)\n pred_wh = tf.expand_dims(pred_box_wh, 4)\n\n pred_wh_half = pred_wh / 2.\n pred_mins = pred_xy - pred_wh_half\n pred_maxes = pred_xy + pred_wh_half\n\n intersect_mins = tf.maximum(pred_mins, true_mins)\n intersect_maxes = tf.minimum(pred_maxes, true_maxes)\n intersect_wh = tf.maximum(intersect_maxes - intersect_mins, 0.)\n intersect_areas = intersect_wh[..., 0] * intersect_wh[..., 1]\n\n true_areas = true_wh[..., 0] * true_wh[..., 1]\n pred_areas = pred_wh[..., 0] * pred_wh[..., 1]\n\n union_areas = pred_areas + true_areas - intersect_areas\n iou_scores = tf.truediv(intersect_areas, union_areas)\n\n best_ious = tf.reduce_max(iou_scores, axis=4)\n conf_mask = conf_mask + tf.to_float(best_ious < 0.6) * (1 - y_true[..., 4]) * NO_OBJECT_SCALE\n\n # penalize the confidence of the boxes, which are reponsible for corresponding ground truth box\n conf_mask = conf_mask + y_true[..., 4] * OBJECT_SCALE\n\n # class mask: simply the position of the ground truth boxes (the predictors)\n class_mask = y_true[..., 4] * tf.gather(CLASS_WEIGHTS, true_box_class) * CLASS_SCALE\n\n \"\"\"\n Warm-up training\n \"\"\"\n no_boxes_mask = tf.to_float(coord_mask < COORD_SCALE / 2.)\n seen = tf.assign_add(seen, 1.)\n\n true_box_xy, true_box_wh, coord_mask = tf.cond(tf.less(seen, WARM_UP_BATCHES),\n lambda: [true_box_xy + (0.5 + cell_grid) * no_boxes_mask,\n true_box_wh + tf.ones_like(true_box_wh) * np.reshape(\n ANCHORS, [1, 1, 1, BOX, 2]) * no_boxes_mask,\n tf.ones_like(coord_mask)],\n lambda: [true_box_xy,\n true_box_wh,\n coord_mask])\n\n \"\"\"\n Finalize the loss\n \"\"\"\n nb_coord_box = tf.reduce_sum(tf.to_float(coord_mask > 0.0))\n nb_conf_box = tf.reduce_sum(tf.to_float(conf_mask > 0.0))\n nb_class_box = tf.reduce_sum(tf.to_float(class_mask > 0.0))\n\n loss_xy = tf.reduce_sum(tf.square(true_box_xy - pred_box_xy) * coord_mask) / (nb_coord_box + 1e-6) / 2.\n loss_wh = tf.reduce_sum(tf.square(true_box_wh - pred_box_wh) * coord_mask) / (nb_coord_box + 1e-6) / 2.\n loss_conf = tf.reduce_sum(tf.square(true_box_conf - pred_box_conf) * conf_mask) / (nb_conf_box + 1e-6) / 2.\n loss_class = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=true_box_class, logits=pred_box_class)\n loss_class = tf.reduce_sum(loss_class * class_mask) / (nb_class_box + 1e-6)\n\n loss = loss_xy + loss_wh + loss_conf + loss_class\n\n nb_true_box = tf.reduce_sum(y_true[..., 4])\n nb_pred_box = tf.reduce_sum(tf.to_float(true_box_conf > 0.5) * tf.to_float(pred_box_conf > 0.3))\n\n \"\"\"\n Debugging code\n \"\"\"\n current_recall = nb_pred_box / (nb_true_box + 1e-6)\n total_recall = tf.assign_add(total_recall, current_recall)\n\n # loss = tf.Print(loss, [tf.zeros((1))], message='Dummy Line \\t', summarize=1000)\n # loss = tf.Print(loss, [loss_xy], message='Loss XY \\t', summarize=1000)\n # loss = tf.Print(loss, [loss_wh], message='Loss WH \\t', summarize=1000)\n # loss = tf.Print(loss, [loss_conf], message='Loss Conf \\t', summarize=1000)\n # loss = tf.Print(loss, [loss_class], message='Loss Class \\t', summarize=1000)\n # loss = tf.Print(loss, [loss], message='Total Loss \\t', summarize=1000)\n # loss = tf.Print(loss, [current_recall], message='Current Recall \\t', summarize=1000)\n # loss = tf.Print(loss, [total_recall / seen], message='Average Recall \\t', summarize=1000)\n\n return loss\n\n\n# 產生一個Dummy的標籤輸入\n# 在訓練階段放的是真實的邊界框與圖像類別訊息\n# 但在預測階段還是需要有一個Dummy的輸入, 因為定義在網絡的結構中有兩個輸入:\n# 1.圖像的輸人\n# 2.圖像邊界框/錨點/信心分數的輸入\ndummy_array = np.zeros((1, 1, 1, 1, TRUE_BOX_BUFFER, 4))\n\n\ndef testing_yolov2(image):\n # 進行圖像輸入的前處理\n input_image = cv2.resize(image, (IMAGE_W, IMAGE_H))\n input_image = input_image / 255.\n input_image = input_image[:, :, ::-1]\n input_image = np.expand_dims(input_image, 0)\n\n # 進行圖像偵測\n netout = model.predict([input_image, dummy_array])\n\n # 解析網絡的輸出來取得最後偵測出來的邊界框(bounding boxes)列表\n boxes = decode_netout(netout[0],\n obj_threshold=OBJ_THRESHOLD,\n # obj_threshold=0.3,\n nms_threshold=NMS_THRESHOLD,\n # nms_threshold=0.001,\n anchors=ANCHORS,\n nb_class=CLASS)\n\n # \"draw_bgr_image_boxes\"\n # 一個簡單把邊界框與預測結果打印到原始圖像(BGR)上的工具函式\n # 參數: image 是image的numpy ndarray [h, w, channels(BGR)]\n # boxes 是偵測的結果\n # labels 是模型訓練的圖像類別列表\n # 回傳: image 是image的numpy ndarray [h, w, channels(RGB)]\n img = draw_boxes(image, boxes, labels=LABELS)\n return image\n\n\ndef normalize(image):\n return image / 255.\n\n\nif __name__ == \"__main__\":\n ROOT_PATH = os.getcwd()\n DATA_PATH = '/home/share/dataset'\n CAR_DATASET = os.path.join(DATA_PATH, \"car\")\n COCO_DATASET = os.path.join(DATA_PATH, \"coco\")\n IMAGES_TEST = os.path.join(ROOT_PATH, \"test_images\")\n # 訓練資料\n UDACITY_DATASET1 = os.path.join(CAR_DATASET, \"object-detection-crowdai\")\n UDACITY_DATASET2 = os.path.join(CAR_DATASET, \"object-dataset\")\n\n MODE = 'training'\n MODE = 'testing'\n if MODE == 'training':\n model = yolov2_model()\n # Step 1.產生網絡拓撲圖\n plot_model(model, to_file='yolov2_graph.png')\n\n # Step 2.載入預訓練的模型權重\n yolov2_load_weight()\n\n # Step 3.設定要���調(fine-tune)的模型層級權重\n layer = model.layers[-4] # 找出最後一層的卷積層\n weights = layer.get_weights()\n\n new_kernel = np.random.normal(size=weights[0].shape) / (GRID_H * GRID_W)\n new_bias = np.random.normal(size=weights[1].shape) / (GRID_H * GRID_W)\n\n layer.set_weights([new_kernel, new_bias]) # 重初始化權重\n\n # TODO: 因為更換dataset, 所以需要更改讀取方式\n # Step 4. 讀取影像和標注檔\n\n car_data1, seen_car_labels1 = udacity1_annotation(UDACITY_DATASET1, LABELS)\n # car_data2, seen_car_labels2 = udacity_annotation(UDACITY_DATASET2, LABELS)\n\n # training_data = np.concatenate(car_data1, car_data2)\n # 將資料分為 training set 和 validation set\n train_data, valid_data, = train_test_split(car_data1, test_size=0.2, shuffle=True)\n # 建立一個訓練用的資料產生器\n train_batch = BatchGenerator(train_data, generator_config, norm=normalize)\n # 建立一個驗證用的資料產生器\n valid_batch = BatchGenerator(valid_data, generator_config, norm=normalize, jitter=False)\n\n # Step 5.設定keras 訓練的EarlyStopping 和 Checkpoint\n # 如果超過15次的循環在loss的收歛上沒有改善就停止訓練\n early_stop = EarlyStopping(monitor='val_loss',\n min_delta=0.001,\n patience=15, # 如果超過15次的循環在loss的收歛上沒有改善就停止訓練\n mode='min',\n verbose=1)\n\n # 每次的訓練循都去比較模型的loss是否有改善, 有就把模型的權重儲存下來\n checkpoint = ModelCheckpoint('weights_car.h5',\n monitor='val_loss',\n verbose=1,\n save_best_only=True,\n mode='min',\n period=1)\n\n tb_counter = len([log for log in os.listdir(os.path.join(os.getcwd(), 'logs/')) if 'coco_' in log]) + 1\n tensorboard = TensorBoard(log_dir=os.path.join(os.getcwd(), 'logs/') + 'coco_' + '_' + str(tb_counter),\n histogram_freq=0,\n write_graph=True,\n write_images=False)\n\n # Step 6.開始訓練\n optimizer = Adam(lr=0.5e-4, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\n # optimizer = SGD(lr=1e-4, decay=0.0005, momentum=0.9)\n # optimizer = RMSprop(lr=1e-4, rho=0.9, epsilon=1e-08, decay=0.0)\n\n model.compile(loss=custom_loss, optimizer=optimizer)\n\n model.fit_generator(generator=train_batch,\n steps_per_epoch=len(train_batch),\n epochs=100,\n verbose=1,\n validation_data=valid_batch,\n validation_steps=len(valid_batch),\n callbacks=[early_stop, checkpoint, tensorboard],\n max_queue_size=3)\n else:\n model = yolov2_model()\n\n # Step 7.載入訓練好的權重\n model.load_weights(\"weights_car.h5\")\n\n # Step 8.測試\n # 選一張圖像\n img_files = glob(IMAGES_TEST + '/*')\n for img_file in img_files:\n # 使用OpenCV讀入圖像\n img = cv2.imread(img_file)\n\n # predict\n img = testing_yolov2(img)\n # 把最後的結果秀出來\n plt.figure(figsize=(10, 10))\n plt.imshow(img[:, :, ::-1])\n plt.show()\nelse:\n model = yolov2_model()\n model.load_weights(\"weights_car.h5\")\n","sub_path":"yolo_v2_training.py","file_name":"yolo_v2_training.py","file_ext":"py","file_size_in_byte":22195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"73573439","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu May 27 11:17:49 2021\r\n\r\n@author: oislen\r\n\"\"\"\r\n\r\n# import relevant libraries\r\nimport pandas as pd\r\n\r\ndef token_dist_check(data,\r\n text_col,\r\n n = 10\r\n ):\r\n \r\n \"\"\"\r\n \r\n Token Distribution Check Documentation\r\n \r\n Function Overview\r\n \r\n This function plots the a bar plot of the tokens for a given dataset and text column\r\n \r\n Defaults\r\n \r\n token_dist_check(data,\r\n text_col,\r\n n = 10\r\n )\r\n \r\n Parameters\r\n \r\n data - DataFrame, the data to plot the tokens of the text_col with\r\n text_col - String, the column name of the text to plot in the data\r\n n - Integer, the number of levels to show from 1\r\n \r\n Returns\r\n \r\n tokens_series - Series, the token series use to create the plot from the data and text column\r\n \r\n Example\r\n \r\n token_dist_check(data = data,\r\n text_col = 'text_norm_clean',\r\n n = 10\r\n )\r\n \r\n \"\"\"\r\n \r\n # extract out all tokens seperated by spaces\r\n tokens = [word for tweet in data[text_col].to_list() for word in tweet.split(' ')]\r\n \r\n # count up all tokens\r\n tokens_series = pd.Series(tokens).value_counts()\r\n \r\n # token series counts distribution\r\n tokens_series_dist = tokens_series.value_counts()\r\n \r\n # plot a bar plot od the distribution\r\n tokens_series_dist.head(n).plot(kind = 'bar', title = text_col)\r\n \r\n return tokens_series\r\n","sub_path":"competitions/Disaster_Tweets/scripts/utilities/token_dist_check.py","file_name":"token_dist_check.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"434550664","text":"# SPDX-License-Identifier: MIT\n# Copyright (c) 2018-2022 Amano Team\n\nfrom pyrogram import types\nfrom pyrogram.helpers import bki, ikb\n\nfrom userlixo.database import Message\n\n\nasync def query_edit(\n self, text: str, reply_markup=None, answer_kwargs={}, *args, **kwargs\n):\n try:\n await self.answer(**answer_kwargs)\n except BaseException:\n pass\n edit = await self.edit_message_text(\n text=text, reply_markup=reply_markup, *args, **kwargs\n )\n return edit\n\n\ndef remove_keyboard(self, message_id=None, *args, **kwargs):\n return self._client.edit_message_reply_markup(\n self.chat.id, message_id or self.id, {}\n )\n\n\nasync def edit_text(self, text: str, reply_markup=None, *args, **kwargs):\n if type(reply_markup) == list:\n reply_markup = ikb(reply_markup)\n return await self._client.edit_message_text(\n self.chat.id, self.id, text, reply_markup=reply_markup, **kwargs\n )\n\n\nasync def reply_text(self, text: str, reply_markup=None, *args, **kwargs):\n if not reply_markup or self._client.name == \"bot\":\n return await self.reply_text(text, reply_markup=reply_markup, *args, **kwargs)\n if type(reply_markup) == types.InlineKeyboardMarkup:\n reply_markup = bki(reply_markup)\n message = await Message.create(text=text, keyboard=reply_markup)\n\n bot = self._client.assistant\n inline_results = await self._client.get_inline_bot_results(\n bot.me.username or bot.me.id, str(message.key)\n )\n result = inline_results.results[0]\n\n reply_to = None\n if kwargs.get(\"quote\"):\n reply_to = self.id\n\n return await self._client.send_inline_bot_result(\n self.chat.id,\n inline_results.query_id,\n result.id,\n reply_to_message_id=reply_to,\n )\n","sub_path":"userlixo/utils/patches.py","file_name":"patches.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"104202724","text":"import discord\nfrom discord.ext import commands\nfrom discord.activity import Game\nimport math\n\n\nintents = discord.Intents.default()\nintents.members = True\nprefix = \"?\"\nbot = commands.Bot(command_prefix=prefix, intents=intents, case_insensitive=True, help_command=None)\n\n@bot.event\nasync def on_ready():\n print('{0.user} login'.format(bot))\n count = len(bot.guilds)\n await bot.change_presence(activity=discord.Game(name=str(count) + \"servers\"))\n\n#コマンド\n\n#help\n@bot.command()\nasync def help(ctx):\n await ctx.send(\"Please check **https://halu-33.github.io**\")\n\n\n#挨拶\n@bot.command()\nasync def hello(ctx, arg):\n await ctx.send(\"hello \" + arg)\n\n#四則計算\n@bot.command()\nasync def add(ctx, x:int, y:int):\n answer_add = x + y\n await ctx.send(f\"``{x} + {y} = {answer_add}``\")\n\n@bot.command()\nasync def sub(ctx, x:int, y:int):\n answer_sub = x - y\n await ctx.send(f\"``{x} - {y} = {answer_sub}``\")\n\n@bot.command()\nasync def mul(ctx, x:int, y:int):\n answer_mul = x * y\n await ctx.send(f\"``{x} * {y} = {answer_mul}``\")\n\n@bot.command()\nasync def div(ctx, x:int, y:int):\n answer_div = x / y\n await ctx.send(f\"``{x} / {y} = {answer_div}``\")\n\n@bot.command()\nasync def mod(ctx, x:int, y:int):\n answer_mod = x % y\n await ctx.send(f\"``{x} (mod {y} ) = {answer_mod}``\")\n\n@bot.command()\nasync def exp(ctx, x:int, y:int):\n answer_exp = x ** y\n await ctx.send(f\"``{x} ^ {y} = {answer_exp}``\")\n\n#招待リンク\n@bot.command()\nasync def inv(ctx):\n await ctx.send('``Invitation link for this bot`` -> https://discord.com/api/oauth2/authorize?client_id=875102698352025600&permissions=8&scope=bot')\n\n#開発者用URL\n@bot.command()\nasync def api(ctx):\n await ctx.send('``Twitter API`` -> https://developer.twitter.com/en/portal/dashboard\\n``Discord API`` -> https://discord.com/developers/applications')\n\n#白猫のルーン周回数計算\n@bot.command()\nasync def gather(ctx, once:int, now:int, total:int):\n #once:1回あたりのルーン数 now:現在のルーン数 total:必要なルーン数\n remain: int = total - now\n laps: int = remain / once\n extra: int = remain % once\n await ctx.send(f\"***【白猫】ルーンの必要数と周回数を計算***\\n>>> **1回あたり手に入るルーン数 : ``{once}個``\\n現在あるルーン数 : ``{now}個``\\n必要なルーン数 : ``{total}個``\\n残りのルーン数 : ``{remain}個``\\n残り周回数 : ``{math.ceil(laps)}周``\\n余るルーン数 : ``{math.ceil(extra)}個``**\")\n\n\ntoken = \"OTUwMDYyODQxMzE3MTgzNTU5.YiTc-A.e843dqh1ApUUuiTMsh_srHQpF_U\"\n#token = getenv('DISCORD_BOT_TOKEN')\nbot.run(token)\n","sub_path":"discordbot.py","file_name":"discordbot.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"608646607","text":"def InitialiseArray():\n Pastry = [None] + [['',0,0] for i in range(1,11)]\n Pastry[1][0] = \"Cranberry\"\n Pastry[1][1] = 1.10\n Pastry[1][2] = 1\n Pastry[2][0] = \"Blueberry\"\n Pastry[2][1] = 1.10\n Pastry[2][2] = 6\n Pastry[3][0] = \"Sweet Potato\"\n Pastry[3][1] = 1.20\n Pastry[3][2] = 4\n Pastry[4][0] = \"Pumpkin Toast\"\n Pastry[4][1] = 1.30\n Pastry[4][2] = 8\n Pastry[5][0] = \"Coconut Kaya\"\n Pastry[5][1] = 1.60\n Pastry[5][2] = 0\n Pastry[6][0] = \"Red Bean\"\n Pastry[6][1] = 0.80\n Pastry[6][2] = 1\n Pastry[7][0] = \"Peanut Butter\"\n Pastry[7][1] = 0.90\n Pastry[7][2] = 7\n Pastry[8][0] = \"Pineapple Longan\"\n Pastry[8][1] = 1.40\n Pastry[8][2] = 0\n Pastry[9][0] = \"Apple Strudel\"\n Pastry[9][1] = 1.50\n Pastry[9][2] = 6\n Pastry[10][0] = \"Spicy Floss\"\n Pastry[10][1] = 1.90\n Pastry[10][2] = 5\n \n return Pastry\n\ndef availability():\n pastry = input('Enter pastry name: ')\n p_list = InitialiseArray()\n print(p_list)\n for i in range(1, len(p_list)):\n if pastry == p_list[i][0]:\n stock = p_list[i][2]\n break\n if stock == 0:\n print('Sold out!')\n else:\n print('Available.')\n\navailability()\n","sub_path":"Revision Papers/04 Dunman High Prelim 2014/task_2/task_2_1.py","file_name":"task_2_1.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"151262840","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2020/1/15 18:16\n# @Author : chuan.yang\n# @File : test_process.py\n# @Desc :\nimport subprocess\nimport socket\nfrom common.info import Constants\nfrom PyQt5.QtCore import pyqtSignal\nfrom PyQt5 import QtCore\n\nfrom .com_control_device_constant import ModuleConstants\nfrom common.logConfig import Logger\nlogger = Logger.module_logger(\"ThComControlDeviceTestProcess\")\nclass ThComControlDeviceTestProcess:\n \"\"\"\n udp client sender\n \"\"\"\n\n def __init__(self):\n self.udp_remote_client = None\n self.udp_local_server = None\n self.com_contents = ModuleConstants.UDP_SEND_CONTENTS\n self.udp_test_result = False\n self.local_udp_server_alive = True\n\n def test_ip_connection(self, url):\n \"\"\"\n test ip destination can be connected\n :param url: ip address\n :return:\n \"\"\"\n try:\n num = 1\n wait = 1000\n ping = subprocess.Popen(\"ping -n {} -w {} {}\".format(num, wait, url),\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n exit_code = ping.wait()\n if exit_code != 0:\n return False\n else:\n return True\n except BaseException as e:\n logger.error(str(e))\n\n def udp_send(self,host,port,contents=ModuleConstants.UDP_SEND_CONTENTS):\n \"\"\"\n udp sends method\n :param host: str,ip address\n :param port: str,ip address port\n :param contents: str,send information\n :return:\n \"\"\"\n self.com_contents = contents\n logger.info(\"udp_send\")\n try:\n socket.setdefaulttimeout(1)\n serverAddressPort = (host, int(port))\n self.udp_remote_client = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)\n result = self.udp_remote_client.sendto(self.com_contents.encode(\"utf-8\"), serverAddressPort)\n if result > 0:\n return True\n else:\n return False\n except BaseException as e:\n logger.error(str(e))\n\n\n\nclass UdpServerThread(QtCore.QThread):\n \"\"\"\n local udp server for listen and receive information\n _signalInfo:signal for caller\n \"\"\"\n _signalInfo = pyqtSignal(str,object)\n\n def __init__(self,host:str,port:str,verify_contents:str):\n \"\"\"\n init method\n :param host:str,ip address\n :param port:str,ip address port\n :param verify_contents: str,information waitting to be checked\n \"\"\"\n super(UdpServerThread, self).__init__()\n self.local_host = host\n self.local_port = int(port)\n self.verify_contents = verify_contents\n self.local_udp_server_alive = True\n self._signalInfo.emit(Constants.SIGNAL_INFORMATION,\"thread start\")\n\n def __del__(self):\n self.wait()\n\n def run(self):\n \"\"\"\n thread core function\n :return:\n \"\"\"\n try:\n self._signalInfo.emit(Constants.SIGNAL_INFORMATION, \"local udp server starting\")\n logger.info(\"local udp server starting\")\n self.udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self.udp_socket.bind((self.local_host, self.local_port))\n self.udp_socket.settimeout(10.0)\n self._signalInfo.emit(Constants.SIGNAL_INFORMATION, \"local udp server started\")\n logger.info(\"local udp server started\")\n while self.local_udp_server_alive:\n recv_msg = self.udp_socket.recvfrom(1024)\n recv_msg = recv_msg[0].decode(\"utf-8\")\n if self.verify_contents == recv_msg:\n self._signalInfo.emit(Constants.SIGNAL_INFORMATION,\"local udp server received:\" + recv_msg)\n logger.info(\"local udp server received:\" + recv_msg)\n self._signalInfo.emit(Constants.SIGNAL_TEST_RESULT, {\"result\":\"success\"})\n except socket.timeout as e1:\n self._signalInfo.emit(Constants.SIGNAL_INFORMATION, str(e1))\n self._signalInfo.emit(Constants.SIGNAL_TEST_RESULT, {\"result\": \"fail\"})\n logger.error(str(e1))\n except BaseException as e:\n self._signalInfo.emit(Constants.SIGNAL_INFORMATION,str(e))\n logger.error(str(e))\n\n def stop_thread(self):\n \"\"\"\n stop socket object and stop the thread\n :return:\n \"\"\"\n if self.udp_socket:\n self.udp_socket.close()\n self.local_udp_server_alive == False\n\n","sub_path":"modules/com_control_device_new/test_process.py","file_name":"test_process.py","file_ext":"py","file_size_in_byte":4570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"410237555","text":"import sys\nimport h5py\nimport subprocess\nimport numpy as np\nimport pandas as pd\nfrom glob import glob\nfrom datetime import datetime\n\nsys.path.insert(0, '/glade/u/home/ksha/ML_repo/utils/')\nimport data_utils as du\nimport QC_utils as qu\nfrom namelist_QC import *\n\n# ==================== Import Raw Data ==================== #\nif del_old:\n print('Re zeros: files under {} will be purged.'.format(INPUT_dir))\nprint('Import Raw Data')\n# station metadata\nhdf_io = pd.HDFStore(BCH_meta_file, 'r')\nmetadata = hdf_io['metadata']\nhdf_io.close()\nstn_lon = metadata['lon'][:].values\nstn_lat = metadata['lat'][:].values\nstn_code = metadata['code'][:].values\n# capa datetime\ntemp_data = np.load(CaPA_datetime_file)\ncapa_dt = temp_data[()]['date']\ncapa_sec = np.array(du.dt_to_sec(capa_dt))\n# load capa\ncapa_labels = ['capa1', 'capa2', 'capa3', 'capa4', 'capa5', 'capa6'][:ens]\netopo_labels = ['etopo1', 'etopo2', 'etopo3', 'etopo4', 'etopo5', 'etopo6'][:ens]\nxgrid_labels = ['xgrid1', 'xgrid2', 'xgrid3', 'xgrid4', 'xgrid5', 'xgrid6'][:ens]\nygrid_labels = ['ygrid1', 'ygrid2', 'ygrid3', 'ygrid4', 'ygrid5', 'ygrid6'][:ens]\ncapa_tuple, indx_capa, indy_capa = qu.load_capa_data(GRID_INPUT_file, stn_lon, stn_lat, capa_labels, etopo_labels, xgrid_labels, ygrid_labels, ocean_flag=keep_ocean)\n#\nprint('Generate Base Files by Station')\nif del_old:\n # clean up\n cmd = 'rm '+INPUT_dir+freq+'*'\n print(cmd)\n subprocess.call(cmd, shell=True)\n cmd = 'rm '+BATCH_dir+freq+'*'\n print(cmd)\n subprocess.call(cmd, shell=True)\n cmd = 'rm '+HOLD_dir+freq+'*'\n print(cmd)\n subprocess.call(cmd, shell=True)\n# gen by station\nperfix = freq+'DBASE_'\nout_dir = INPUT_dir\nvalid_range = [[datetime(2017, 2, 5) , datetime(2017, 2, 20)],\n [datetime(2017, 4, 11) , datetime(2017, 4, 26)],\n [datetime(2017, 6, 4) , datetime(2017, 6, 19)],\n [datetime(2017, 10, 25), datetime(2017, 11, 9)]]\n\ntest_range = [[datetime(2017, 1, 5) , datetime(2017, 1, 20)],\n [datetime(2017, 3, 21) , datetime(2017, 4, 5)] ,\n [datetime(2017, 8, 8) , datetime(2017, 8, 23)],\n [datetime(2017, 11, 17), datetime(2017, 12, 2)]]\nif freq == 'HIGH_':\n BCH_input = BCH_high_file\nelif freq == 'LOW_':\n BCH_input = BCH_low_file\nelse:\n BCH_input = BCH_file\n\n\n_, _ = qu.gen_by_stn_capa(capa_tuple, indx_capa, indy_capa, ens,\n half_edge, capa_sec, valid_range, test_range, \n stn_code, BCH_input, perfix, out_dir)\n# ========================================================= #\n# ================ Assign Labels and Merge ================ #\nprint('Assign labels and Merge Files')\ndata_dir = INPUT_dir+freq+'DBASE*hdf'; filenames = glob(data_dir)\n\nlabels = ['stn_input', 'capa_input', 'time_info', 'cate_out', 'xstn_code']\np_group, n_group = qu.merge_input_capa(filenames, precip_thres=thres, option='TRAIN')\ndu.save_hdf5(p_group, labels, BATCH_dir, filename=freq+'TRAIN_p.hdf')\ndu.save_hdf5(n_group, labels, BATCH_dir, filename=freq+'TRAIN_n.hdf')\n\np_group, n_group = qu.merge_input_capa(filenames, precip_thres=thres, option='VALID')\ndu.save_hdf5(p_group, labels, BATCH_dir, filename=freq+'VALID_p.hdf')\ndu.save_hdf5(n_group, labels, BATCH_dir, filename=freq+'VALID_n.hdf')\n\np_group, n_group = qu.merge_input_capa(filenames, precip_thres=thres, option='TEST')\ndu.save_hdf5(p_group, labels, BATCH_dir, filename=freq+'TEST_p.hdf')\ndu.save_hdf5(n_group, labels, BATCH_dir, filename=freq+'TEST_n.hdf')\n# ========================================================= #\n# =================== Split into Batches ================== #\nprint('Split into Batches')\ntrain_name_p = BATCH_dir+freq+'TRAIN_p.hdf'; train_name_n = BATCH_dir+freq+'TRAIN_n.hdf'\nvalid_name_p = BATCH_dir+freq+'VALID_p.hdf'; valid_name_n = BATCH_dir+freq+'VALID_n.hdf'\ntest_name_p = BATCH_dir+freq+'TEST_p.hdf' ; test_name_n = BATCH_dir+freq+'TEST_n.hdf'\n# generating batches\nlabels_capa = ['capa_input', 'stn_input', 'time_info', 'cate_out', 'xstn_code']\nqu.balanced_batches(test_name_p , test_name_n , labels_capa, BATCH_dir, pos_rate=0.5, padx=padx, pady=pady, batch_size=200, prefix=freq+'CAPA_TEST' , option='CAPA')\nqu.balanced_batches(valid_name_p, valid_name_n, labels_capa, BATCH_dir, pos_rate=0.5, padx=padx, pady=pady, batch_size=200, prefix=freq+'CAPA_VALID', option='CAPA')\nqu.balanced_batches(train_name_p, train_name_n, labels_capa, BATCH_dir, pos_rate=0.5, padx=padx, pady=pady, batch_size=200, prefix=freq+'CAPA_TRAIN', option='CAPA')\n# #\nfile_name = glob(BATCH_dir+freq+'CAPA_TRAIN*npy')\nqu.split_batches_mlp(BATCH_dir, file_name, ens, freq+'ENS_CAPA_TRAIN')\nfile_name = glob(BATCH_dir+freq+'CAPA_VALID*npy')\nqu.split_batches_mlp(BATCH_dir, file_name, ens, freq+'ENS_CAPA_VALID')\n# ========================================================= #\n# ==================== Regroup batches ==================== #\nfile_name = glob(BATCH_dir+freq+'CAPA_VALID*')\nqu.packing_data(file_name, HOLD_dir, batch_size=200, labels=labels_capa, prefix=freq+'CAPA_VALID')\nfile_name = glob(BATCH_dir+freq+'CAPA_TRAIN*')\nqu.packing_data(file_name, HOLD_dir, batch_size=200, labels=labels_capa, prefix=freq+'CAPA_TRAIN')\nfile_name = glob(BATCH_dir+freq+'CAPA_TEST*')\nqu.packing_data(file_name, HOLD_dir, batch_size=200, labels=labels_capa, prefix=freq+'CAPA_TEST')\n# ========================================================== #","sub_path":"scripts/PIPELINE_QC_MLP.py","file_name":"PIPELINE_QC_MLP.py","file_ext":"py","file_size_in_byte":5392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"616343221","text":"import logging\nimport uuid\n\nfrom .framework import datastore\n\n\nlogger = logging.getLogger('rsrcs')\n\n\nresources = datastore.Datastore('Resource',\n 'key', 'stack_key', 'name', 'phys_id')\n\n\nclass Resource(object):\n def __init__(self, name, stack, defn, phys_id=None,\n key=None):\n self.key = key\n self.name = name\n self.stack = stack\n self.defn = defn\n self.physical_resource_id = phys_id\n\n @classmethod\n def _load_from_store(cls, key, get_stack):\n loaded = resources.read(key)\n return cls(loaded.name, get_stack(loaded.stack_key),\n None,\n loaded.phys_id,\n loaded.key)\n\n @classmethod\n def load(cls, key):\n from . import stack\n\n return cls._load_from_store(key, stack.Stack.load)\n\n @classmethod\n def load_all_from_stack(cls, stack):\n stored = resources.find(stack_key=stack.key)\n return (cls._load_from_store(key, lambda sk: stack) for key in stored)\n\n def store(self):\n data = {\n 'name': self.name,\n 'stack_key': self.stack.key,\n 'phys_id': self.physical_resource_id,\n }\n\n if self.key is None:\n self.key = resources.create(**data)\n else:\n resources.update(self.key, **data)\n\n def create(self):\n self.physical_resource_id = str(uuid.uuid4())\n logger.info('[%s(%d)] Created %s' % (self.name,\n self.key,\n self.physical_resource_id))\n self.store()\n\n def delete(self):\n logger.info('[%s(%d)] Deleted %s' % (self.name,\n self.key,\n self.physical_resource_id))\n resources.delete(self.key)\n","sub_path":"converge/resource.py","file_name":"resource.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"232927853","text":"import pathlib\nimport pandas as pd\nfrom pycytominer.cyto_utils import infer_cp_features\n\n\ndef load_data(\n y_col=\"Metadata_CellLine\", wt_col=\"WT\", return_meta=False, shuffle_row_order=False\n):\n train_file = pathlib.Path(\"data\", \"example_train.tsv.gz\")\n train_df = pd.read_csv(train_file, sep=\"\\t\")\n\n test_file = pathlib.Path(\"data\", \"example_test.tsv.gz\")\n test_df = pd.read_csv(test_file, sep=\"\\t\")\n\n if shuffle_row_order:\n train_df = train_df.sample(frac=1).reset_index(drop=True)\n test_df = test_df.sample(frac=1).reset_index(drop=True)\n\n y_train_df = pd.DataFrame(train_df.loc[:, y_col]).assign(status=0)\n y_train_df.loc[y_train_df.loc[:, y_col] != wt_col, \"status\"] = 1\n\n y_test_df = pd.DataFrame(test_df.loc[:, y_col]).assign(status=0)\n y_test_df.loc[y_test_df.loc[:, y_col] != wt_col, \"status\"] = 1\n\n cp_features = infer_cp_features(train_df)\n x_train_df = train_df.loc[:, cp_features]\n x_test_df = test_df.loc[:, cp_features]\n\n if return_meta:\n meta_train_df = train_df.drop(cp_features, axis=\"columns\")\n meta_test_df = test_df.drop(cp_features, axis=\"columns\")\n return x_train_df, y_train_df, meta_train_df, x_test_df, y_test_df, meta_test_df\n else:\n return x_train_df, y_train_df, x_test_df, y_test_df\n","sub_path":"4.single-cell/utils/data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"253717925","text":"import re\nfrom datetime import datetime\nfrom .driver import Driver\nfrom .settings import Settings\nfrom .user import User\nfrom PyInquirer import prompt\nfrom PyInquirer import Validator, ValidationError\n##\nfrom .validators import AmountValidator, MonthValidator, LimitValidator, PriceValidator, NumberValidator, TimeValidator, DateValidator, DurationValidator, PromoDurationValidator, ExpirationValidator, ListValidator\nfrom . import remote as Remote\nfrom .file import File, Folder, Google_File, Google_Folder\n\nclass Poll:\n \"\"\"OnlyFans Poll class\"\"\"\n\n def __init__(self):\n \"\"\"OnlyFans Poll object\"\"\"\n\n # duration of poll\n self.duration = None\n # list of strings\n self.questions = []\n # prevents double prompts\n self.gotten = False\n\n def check(self):\n \"\"\"Check if poll is ready with valid values\n\n Returns\n -------\n bool\n Whether the poll is ready to be posted or not\n\n \"\"\"\n\n if len(self.get_questions()) > 0: return True\n if self.get_duration(): return True\n return False\n\n def get(self):\n if self.gotten: return\n gotten = self.get_duration()\n # return early if skipped\n if not gotten: return\n gotten = self.get_questions()\n # return early if skipped\n if not gotten: return\n self.gotten = True\n\n def get_duration(self):\n \"\"\"\n Gets the duration value if not none else sets it from args or prompts.\n\n Returns\n -------\n int\n The duration as an int\n\n \"\"\"\n\n if self.duration: return self.duration\n # retrieve from args and return if exists\n duration = Settings.get_duration()\n if duration: \n self.duration = duration\n return duration\n # prompt skip\n if not Settings.prompt(\"duration\"): return None\n question = {\n 'type': 'input',\n 'name': 'duration',\n 'message': 'Duration [1, 3, 7, 99 (\\'No Limit\\')]',\n 'validate': DurationValidator\n }\n duration = prompt(question)[\"duration\"]\n # confirm duration\n if not Settings.confirm(duration): return self.get_duration()\n self.duration = duration\n return self.duration\n\n def get_questions(self):\n \"\"\"\n Gets the questions value if not none else sets it from args or prompts.\n\n Returns\n -------\n list\n The questions as strings in a list\n\n \"\"\"\n\n if len(self.questions) > 0: return self.questions\n # retrieve from args and return if exists\n questions = Settings.get_questions()\n if len(questions) > 0: \n self.questions = questions\n return questions\n # prompt skip\n if not Settings.prompt(\"questions\"): return []\n print(\"Enter Questions\")\n while True:\n question = {\n 'type': 'input',\n 'name': 'question',\n 'message': 'Question:',\n }\n answers = prompt(question)[\"question\"]\n if str(question) == \"\": break\n questions.append(question)\n # confirm questions\n if not Settings.confirm(questions): return self.get_questions()\n self.questions = questions\n return self.questions","sub_path":"src/OnlySnarf/lib/actions/poll.py","file_name":"poll.py","file_ext":"py","file_size_in_byte":3356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"523603051","text":"# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common options. For a full\n# list see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\n# -- Path setup --------------------------------------------------------------\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\n# import os\n# import sys\n# sys.path.insert(0, os.path.abspath('.'))\n\nfrom recommonmark.transform import AutoStructify\nimport pdbecif\n# -- Project information -----------------------------------------------------\n\nproject = \"PDBeCIF\"\ncopyright = \"2020, Glen van Ginkel (Protein Data Bank in Europe; https://pdbe.org)\"\nauthor = \"Glen van Ginkel (Protein Data Bank in Europe; https://pdbe.org)\"\nversion = pdbecif.__version__\n\n# -- General configuration ---------------------------------------------------\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n \"sphinx.ext.autodoc\",\n \"sphinx.ext.napoleon\",\n \"sphinx.ext.todo\",\n \"sphinx_markdown_tables\",\n \"sphinx.ext.coverage\",\n \"sphinx.ext.intersphinx\",\n \"recommonmark\",\n]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = [\"_templates\"]\nsource_parsers = {\".rst\": \"restructuredtext\", \".txt\": \"markdown\", \".md\": \"markdown\"}\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path.\nexclude_patterns = [\"_build\", \"Thumbs.db\", \".DS_Store\"]\n\n\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\n#\nhtml_theme = \"sphinx_rtd_theme\"\nhtml_theme_options = {\n \"collapse_navigation\": False,\n \"sticky_navigation\": True,\n \"navigation_depth\": 4,\n \"logo_only\": False,\n \"display_version\": True,\n \"prev_next_buttons_location\": \"bottom\",\n}\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\n\nhtml_static_path = [\"_static\"]\nhtml_logo = \"logo.png\"\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = \"sphinx\"\n\n# region Extension configuration\ngithub_doc_root = \"https://github.com/rtfd/recommonmark/tree/master/doc/\"\n\n\ndef setup(app):\n app.add_config_value(\n \"recommonmark_config\",\n {\n \"url_resolver\": lambda url: github_doc_root + url,\n \"auto_toc_tree_section\": \"Contents\",\n },\n True,\n )\n app.add_transform(AutoStructify)\n app.connect(\n \"autodoc-process-docstring\", no_namedtuple_attrib_docstring,\n )\n\n\ndef no_namedtuple_attrib_docstring(app, what, name, obj, options, lines):\n is_namedtuple_docstring = len(lines) == 1 and lines[0].startswith(\n \"Alias for field number\"\n )\n if is_namedtuple_docstring:\n # We don't return, so we need to purge in-place\n del lines[:]\n\n\n# endregion\n","sub_path":"docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":3427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"32852292","text":"\"\"\"\nSmall code to handle colored text\n\"\"\"\nimport re\n\nbold = '\\033[1m'\nend = '\\033[0m'\n\nblack = '\\033[0;30m'\nred = '\\033[0;31m'\ngreen = '\\033[0;32m'\nyellow = '\\033[0;33m'\nblue = '\\033[0;34m'\npurple = '\\033[0;35m'\ncyan = '\\033[0;36m'\ngrey = '\\033[0;37m'\n\nok = green\nerror = red\nnormal = grey\ncitekey = purple\nfilepath = bold\ntag = cyan\n\ndef dye(s, color=end, bold=False):\n assert color[0] == '\\033'\n if bold:\n color = '\\033[1' + color[3:]\n return color + s + end\n\n_dye = dye\ndef _nodye(s, *args, **kwargs):\n return s\n\ndef setup(enable = True):\n global dye\n if enable:\n dye = _dye\n else:\n dye = _nodye\n\n\nundye_re = re.compile('\\x1b\\[[;\\d]*[A-Za-z]')\n\ndef undye(s):\n \"\"\"Purge string s of color\"\"\"\n return undye_re.sub('', s)\n","sub_path":"pubs/color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"387679657","text":"import requests\nimport discord\nfrom discord.ext import tasks, commands\n\nimport configManager\n\nintents = discord.Intents.all()\nclient = commands.Bot(command_prefix=\"!\", case_insensitive=True, intents=intents)\nclient.db = \"\"\n\n\n@client.event\nasync def on_ready():\n print(\"Bot has started\")\n await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=\"a ton of ducks\"))\n sendDuck.start()\n sendFact.start()\n\n\n@tasks.loop(minutes = 1)\nasync def sendDuck():\n id = configManager.serverData[\"duckChannel\"]\n channel = client.get_channel(id)\n response = requests.get(\"https://random-d.uk/api/v2/random\").json()\n url = response.get('url')\n await channel.send(url)\n\n@tasks.loop(minutes = 1)\nasync def sendFact():\n id = configManager.serverData[\"factChannel\"]\n channel = client.get_channel(id)\n response = requests.get(\"https://uselessfacts.jsph.pl/random.json?language=en\").json()\n fact = response.get('text')\n await channel.send(fact)\n\n\n\ntry:\n client.run(configManager.botData[\"bottoken\"])\nexcept Exception as e:\n print(\"Something went wrong when starting the bot.\")\n print(e)\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"530260118","text":"import json\nimport re\n\nimport os\nfrom random import shuffle\n\nimport emoji\nfrom hazm import word_tokenize\n\n\ndef remove_mentions(word_lst):\n return [w for w in word_lst if not w.startswith(\"@\")]\n\n\ndef remove_question_marks(word_lst):\n return [re.sub('[?!؟!]', '', w) for w in word_lst]\n\n\ndef remove_additional_chars(word_lst):\n return [re.sub('[ًٌٍَُِّْ]', '', w) for w in word_lst]\n\n\ndef remove_hashtag_sign(word_lst):\n for i in range(len(word_lst)):\n word = word_lst[i]\n if not word.startswith(\"#\"):\n continue\n\n word = word.replace(\"_\", \"‌\")\n\n word_lst[i] = word\n\n return word_lst\n\n\ndef merge_plural(word_lst):\n if (len(word_lst) <= 1):\n return word_lst\n\n result = [word_lst[0]]\n for w in word_lst[1:]:\n if w == \"ها\":\n result.append(\n result.pop() + \"‌\" + w\n )\n else:\n result.append(w)\n\n return result\n\n\ndef merge_mi(word_lst):\n if (len(word_lst) <= 1):\n return word_lst\n\n word_lst.reverse()\n result = [word_lst[0]]\n for w in word_lst[1:]:\n if w == \"می\":\n result.append(\n w + \"‌\" + result.pop()\n )\n else:\n result.append(w)\n word_lst.reverse()\n result.reverse()\n return result\n\n\ndef merge_nmi(word_lst):\n if (len(word_lst) <= 1):\n return word_lst\n\n word_lst.reverse()\n result = [word_lst[0]]\n for w in word_lst[1:]:\n if w == \"نمی\":\n result.append(\n w + \"‌\" + result.pop()\n )\n else:\n result.append(w)\n word_lst.reverse()\n result.reverse()\n return result\n\n\ndef separate_emoji(word_lst):\n p = emoji.get_emoji_regexp()\n\n result = []\n for w in word_lst:\n matches = re.findall(p, w)\n if len(matches) > 0:\n result += [emoji.demojize(m) for m in matches]\n else:\n result.append(w)\n\n return result\n\n\ndef is_just_persian(w):\n ptr = re.compile(\n \"^(([۰-۹0-9])|([\\s,کگۀی،,تثجحخد,غيًٌٍَ,ُپٰچژ,ء-ةذ-عف-ٔ])|((،|؟|«|»|؛|٬))|((\\.|:|\\!|\\-|\\[|\\]|\\(|\\)|\\/)))+$\")\n res = re.findall(ptr, w)\n return len(res) > 0\n\n\ndef tokenize(text, stopwords):\n word_candidates = word_tokenize(text)\n # word_candidates = remove_question_marks(word_candidates)\n word_candidates = remove_additional_chars(word_candidates)\n # word_candidates = remove_mentions(word_candidates)\n word_candidates = remove_hashtag_sign(word_candidates)\n word_candidates = merge_plural(word_candidates)\n word_candidates = merge_mi(word_candidates)\n word_candidates = merge_nmi(word_candidates)\n word_candidates = separate_emoji(word_candidates)\n word_candidates = [w for w in word_candidates if len(w) > 0]\n return word_candidates\n\n\ndef extract_documents(username):\n stopwords = set(open(\"stop_words_%s.txt\" % username, encoding=\"utf8\").read().split())\n docs = []\n user_ids = os.listdir(\"json_data_%s\" % username)\n count = 0\n for id in user_ids:\n with open(\"json_data_%s/%s\" % (username, id), encoding=\"utf8\") as f:\n count += 1\n tweet_lst = json.load(f)\n docs.extend([tokenize(t, stopwords) for t in tweet_lst])\n print(\"# %s / %s - %s\" % (count, len(user_ids), len(docs)))\n\n return docs\n\n\ndef extract_posts(username):\n stopwords = set(open(\"stop_words_%s.txt\" % username, encoding=\"utf8\").read().split())\n docs = []\n user_ids = os.listdir(\"json_data_%s\" % username)\n count = 0\n for id in user_ids:\n with open(\"json_data_%s/%s\" % (username, id), encoding=\"utf8\") as f:\n count += 1\n tweet_lst = json.load(f)\n docs.extend([word_lst for word_lst in [tokenize(t, stopwords) for t in tweet_lst] if len(word_lst) >= 5])\n print(\"# %s / %s - %s\" % (count, len(user_ids), len(docs)))\n\n return docs\n\n\ndef save_documents(documents, output_filename, word_separator='\\n'):\n with open(output_filename, \"w\", encoding=\"utf8\") as f:\n for d in documents:\n f.write(word_separator.join(d))\n f.write(\"\\n\")\n\n\ndef extract_post_per_line(username):\n docs = extract_posts(username)\n for _ in range(10):\n shuffle(docs)\n\n save_documents(docs, \"documents_%s.txt\" % username, word_separator='#')\n\n\ndef extract_word(username):\n docs = extract_documents(username)\n # save_documents(docs, \"words_%s.txt\" % username)\n with open(\"posts_%s.txt\" % username, 'w', encoding=\"utf8\") as f:\n json.dump(docs, f, ensure_ascii=False)\n\n\ndef one_line_per_word(username):\n out = open(\"l_words_%s.txt\" % username, \"w\", encoding=\"utf8\")\n inf = open(\"words_%s.txt\" % username, \"r\", encoding=\"utf8\")\n for line in inf:\n words = line.split()\n out.write(\"\\n\".join(words))\n out.write(\"\\n\")\n\n inf.close()\n out.close()\n","sub_path":"data_tokenization.py","file_name":"data_tokenization.py","file_ext":"py","file_size_in_byte":4913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"11835765","text":"# coding: utf-8\n\nfrom django.views.generic.simple import direct_to_template\nfrom django.http import HttpResponseRedirect\n\nfrom django.db import models\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.cache import cache\n\nimport logging\n\nimport models\nimport forms\n\n##################################################################\ndef cache_key_recipients(request):\n\treturn 'recipienti' + str(request.user.id)\n\ndef cache_key_messages(request):\n\treturn 'mesaje' + str(request.user.id)\n\n##################################################################\n@login_required\ndef listObjects(request):\n\t\n\t#cache.delete(cache_key_recipients(request))\n\trecipients = cache.get(cache_key_recipients(request))\n\tif recipients is None:\n\t\trecipients = models.Recipient.objects.filter(owner=request.user).order_by('last_name')\n\t\tcache.add(cache_key_recipients(request), recipients)\n\t\n\t#cache.delete(cache_key_messages(request))\n\tmesaje = cache.get(cache_key_messages(request))\n\tif mesaje is None:\n\t\tmesaje = models.Message.objects.filter(author=request.user)\n\t\tcache.add(cache_key_messages(request), mesaje)\n\n\t# cu ce ne-am logat ultima data\n\tlast_login_provider = (request.session['social_auth_last_login_backend'] if 'social_auth_last_login_backend' in request.session else 'cardsby.me')\n\t#logging.info('last login provider : %s', last_login_provider)\n\n\t# care e uid-ul de site social pe care l-am folosit pentru logare\n\tsocial_user = request.user.social_auth.filter(provider=last_login_provider).get()\n\t\n\t# preparam contextul paginii\n\tcontext = { \n\t\t'recipients': recipients,\n\t\t'mesaje' : mesaje,\n\t\t'last_login_provider' : last_login_provider,\n\t\t'social_id' : social_user.extra_data['access_token'],\n\t}\n \n\treturn direct_to_template(request, 'index.html', context)\n\n##################################################################\n@login_required\ndef createMessage(request):\n\tif request.method == 'GET':\n\t\tform = forms.MessageForm(user=request.user)\n\t\n\tif request.method == 'POST':\n\t\tform = forms.MessageForm(request.POST, user=request.user)\n\t\n\t\tif form.is_valid():\n\t\t\tcontent = form.cleaned_data['content']\n\t\t\trecipients = form.cleaned_data['recipients']\n\t\t\t\n\t\t\tfor r in recipients:\n\t\t\t\tm = models.Message()\n\t\t\t\tm.author = request.user\n\t\t\t\tm.content = content\n\t\t\t\t\n\t\t\t\tm.recipient = r\n\t\t\t\t\n\t\t\t\tm.save()\n\t\t\t\n\t\t\tcache.delete(cache_key_messages(request))\n\t\t\treturn HttpResponseRedirect('/')\n \n\tcontext = { \n\t\t'form': form,\n\t}\n\treturn direct_to_template(request, 'createMessage.html', context)\n\n##################################################################\n@login_required\ndef renderMessage(request):\n\tif request.method == 'GET':\n\t\tid = request.GET.get('id')\n\t\tm = models.Message.objects.get(id=id)\n\t\t\n\t\tcontent = m.content\n\t\n\tcontext = { \n\t\t'content': content,\n\t}\n\treturn direct_to_template(request, 'renderMessage.html', context)\n\t\n##################################################################\ndef renderPDF(request):\n\tfrom django import http\n\tfrom django.template.loader import get_template\n\tfrom django.template import Context\n\timport ho.pisa as pisa\n\tfrom django.conf import settings\n\n\t# functie care intoarce id-ul de memcache al pdf-ului nostru\n\tdef pdf_cache_id(id):\n\t\treturn 'pdf' + id\n\t\n\t# functie care prelucreaza link-uri catre imagini externe din metoda de creare pdf de mai jos\n\tdef link_callback(uri, rel):\n\t\treturn uri\n\n\t# daca s-a cerut ceva prin get\n\tif request.method == 'GET':\n\t\tid = request.GET.get('id')\n\t\t\n\t\t# vedem intii daca nu e deja in cache\n\t\tpdf = cache.get(pdf_cache_id(id))\n\t\tif not pdf is None:\n\t\t\treturn pdf\n\t\t\n\t\t# nu e, il facem\n\t\tm = models.Message.objects.get(id=id)\n\t\t\n\t\ttemplate = get_template('renderMessage.html')\n\t\tcontext = { \n\t\t\t'content': m.content,\n\t\t\t'mediaroot': settings.MEDIA_ROOT,\n\t\t}\n\t\thtml = template.render(Context(context))\n\t\t\n\t\tresponse = http.HttpResponse()\n\t\tresponse['Content-Type'] ='application/pdf'\n\t\t\n\t\tpdf = pisa.pisaDocument(\n\t\t\thtml.encode('UTF-8'), \n\t\t\tdest=response,\n\t\t\tencoding='UTF-8',\n\t\t\tlink_callback=link_callback)\n\t\t\n\t\tif not pdf.err:\n\t\t\tcache.add(pdf_cache_id(id), response)\n\t\t\treturn response\n\t\t\n\t\treturn http.HttpResponse('Gremlins ate your pdf : ' + str(pdf.log))\n\n\treturn HttpResponseRedirect('/')\n\n##################################################################\n@login_required\ndef createRecipients(request):\n\tr = models.Recipient(first_name='Paul', last_name='Paulescu', address='3, Aleea cu Flori', owner=request.user).save()\n\tr = models.Recipient(first_name='Ion', last_name='Iliescu', address='4, Aleea fara Flori', owner=request.user).save()\n\t\n\tcache.delete(cache_key_recipients(request))\n\treturn HttpResponseRedirect('/')\n\t\n##################################################################\n@login_required\ndef createMessages(request):\n\tr = models.Recipient.objects.all()[0]\n\tm = models.Message(content='Mesaju meu.', recipient=r, author=request.user).save()\n\t\n\tcache.delete(cache_key_messages(request))\n\treturn HttpResponseRedirect('/')\n\t","sub_path":"expedioapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"2467781","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jun 24 22:46:47 2020\r\n\r\n@author: ISIL\r\n\"\"\"\r\nfrom preprocess import read_data, read_TFIDF, create_vectors, get_vectors, split_data,convert_list_to_nd_array\r\nfrom TFIDF import compute_TFIDF\r\nfrom logistic_regression import logistic_reg\r\nfrom SVM import support_vector_machine\r\n\r\n\r\npath = \"./data\" \r\n\r\nif __name__ == \"__main__\":\r\n \r\n\t#PROCESS THE DATA\r\n sentences, labels = read_data(path)\r\n TFIDF = compute_TFIDF(sentences,path) #calculate TFIDF values\r\n word_list, TFIDF = read_TFIDF(path) #read unique words list and TFIDF values\r\n create_vectors(word_list,TFIDF,path) #vectorize data\r\n \r\n NROWS = len(TFIDF)\r\n NCOLS = len(word_list)\r\n \r\n #vectorized corpus (premise+hypothesis)\r\n data = get_vectors(path,NROWS,NCOLS) #get vectorized data\r\n \r\n y = convert_list_to_nd_array(\"y\",labels)\r\n \r\n train_x,train_y,test_x,test_y = split_data(data,y,path) #split %80 for training %20 for test\r\n \r\n #2D arrays converted into 1D arrays to use in SVM \r\n train_y_1 = train_y.flatten() \r\n test_y_1 = test_y.flatten() \r\n \r\n accuracy_lg = logistic_reg(train_x,train_y,test_x,test_y)\r\n accuracy_svm = support_vector_machine(train_x,train_y_1,test_x,test_y_1)\r\n \r\n ","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"12524847","text":"#!/usr/bin/env python\nimport sys, os\nimport requests\nfrom bs4 import BeautifulSoup\n\nfrom optparse import OptionParser\n\ndef main():\n\n parser = OptionParser()\n parser.add_option(\"-l\", \"--link\", help=\"Select a link to scrap.\")\n\n options, arguments = parser.parse_args()\n\n if options.link:\n\n link = options.link\n\n else:\n\n link = 'https://en.wikipedia.org/wiki/Physics'\n\n\n resp = requests.get(link)\n soup = BeautifulSoup(resp.text, 'lxml')\n\n urls = []\n for h in soup.find_all('p'):\n\n a = h.find_all('a')\n\n for t in a:\n\n urls.append(t.attrs['href'])\n\n\n f = open('urls.txt', 'w')\n\n for url in urls:\n\n if '#' in url:\n pass\n else:\n f.write(link + url)\n f.write(\"\\n\")\n\n f.close()\n\nif __name__==\"__main__\":\n main()\n","sub_path":"pythonwebscraper.py","file_name":"pythonwebscraper.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"7334894","text":"#from random import randint\nimport numpy as np\n#import pandas as pand\nimport math\nimport cmath\nimport random\nimport copy\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nrng = np.random\n#import sys\n\nSIZE = 1000\n\nOPCODE = ['', \"sqrt(\", \"sin(\", \"cos(\", \"tan(\"]\nSolutions = []\nEquations = []\nCleanedEquations = []\n\n\n# Parameters\nlearning_rate = 0.01\ntraining_epochs = 500\ndisplay_step = 20\n\ndef main():\n \n count = 0\n\n \n eq = arrayInit(9, SIZE)\n \n# print(eq[1])\n \n while count < SIZE:\n generateEquations(count, SIZE, eq)\n count += 1\n \n# print(\"\\n\") \n# print(eq)\n# print(\"EQUATIONS: \" + str(Equations))\n# print(\"SOLUTIONS: \" + str(Solutions))\n\n print(\"\\n\")\n \n# for equations in eq:\n count = 0\n \n tempEQN = copy.deepcopy(Equations)\n\n for equation in tempEQN:\n# print(\"Here: \" + str(count))\n opIndex = 0\n for var in equation:\n \n# print(\"OPindex : \" + str(opIndex) + \" Var: \" + str(var))\n\n if var == OPCODE[0]:\n var = \"40\"\n equation[opIndex] = float(var)\n \n elif var == OPCODE[1]:\n var = \"41\"\n equation[opIndex] = float(var)\n \n elif var == OPCODE[2]:\n var = \"42\"\n equation[opIndex] = float(var)\n \n elif var == OPCODE[3]:\n var = \"43\"\n equation[opIndex] = float(var)\n \n elif var == OPCODE[4]:\n var = \"44\"\n equation[opIndex] = float(var)\n \n elif var == \")\":\n var = \"99\"\n equation[opIndex] = float(var)\n\n \n elif var == \"+\":\n var = \"0\"\n equation[opIndex] = float(var)\n \n elif var == \"-\":\n var = \"1\"\n equation[opIndex] = float(var)\n \n elif var == \"*\":\n var = \"2\"\n equation[opIndex] = float(var)\n \n elif var == \"/\":\n var = \"3\"\n equation[opIndex] = float(var)\n \n else:\n equation[opIndex] = float(var)\n \n opIndex += 1\n \n CleanedEquations.append(equation)\n \n# print(equation)\n count += 1\n \n \n x = eq\n \n# print(\"Formatted Print Statement:\")\n# print('\\n'.join([''.join(['{:6}'.format(item) for item in row]) \n# for row in x]))\n# sys.exit(\"Stop\")\n\n#---------------------------------------------------------------- \n \n\n train_X = np.asarray(CleanedEquations)\n train_Y = np.asarray(Solutions)\n \n n_samples = train_X.shape[0]\n print(n_samples)\n \n print(train_X.shape)\n print(train_Y.shape)\n \n # tf Graph Input\n X = tf.placeholder(dtype=\"float\")\n Y = tf.placeholder(dtype=\"float\")\n \n print(X.shape)\n print(Y.shape)\n \n # Set model weights\n W = tf.Variable(rng.randn(), name=\"weight\")\n b = tf.Variable(rng.randn(), name=\"bias\")\n \n \n pred = tf.add(tf.multiply(X, W), b)\n \n # Mean squared error\n cost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples)\n # Gradient descent\n optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)\n \n# print(pred.shape)\n \n # Initializing the variables\n init = tf.global_variables_initializer()\n \n print(\"Training...\")\n \n # Launch the graph\n with tf.Session() as sess:\n sess.run(init)\n \n # Fit all training data\n for epoch in range(training_epochs):\n for (x, y) in zip(train_X, train_Y):\n sess.run(optimizer, feed_dict={X: x, Y: y})\n \n #Display logs per epoch step\n if (epoch+1) % display_step == 0:\n c = sess.run(cost, feed_dict={X: train_X, Y:train_Y})\n print(\"Epoch:\", '%04d' % (epoch+1), \"cost=\", \"{:.9f}\".format(c), \\\n \"W=\", sess.run(W), \"b=\", sess.run(b))\n \n print( \"Optimization Finished!\")\n training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y})\n print (\"Training cost=\", training_cost, \"W=\", sess.run(W), \"b=\",\n sess.run(b), '\\n')\n \n #Graphic display\n fig=plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k')\n plt.ylim(0, 1.05)\n plt.plot(train_X, train_Y, 'ro', label='Original data')\n# plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')\n plt.legend()\n plt.show()\n \n \n \n fig=plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k')\n plt.ylim(1, 105)\n plt.plot(train_X, train_Y, 'ro', label='Original data')\n# plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')\n plt.legend()\n plt.show()\n \n fig=plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k')\n plt.ylim(100, 1000000)\n plt.plot(train_X, train_Y, 'ro', label='Original data')\n# plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')\n plt.legend()\n plt.show()\n\n\n\n\ndef perfectSquare(n):\n print(n)\n return n == int(math.sqrt(n)) * int(math.sqrt(n))\n\ndef inFibonacci(n):\n phi = 0.5 + 0.5 * math.sqrt(5.0)\n a = phi * n\n return n == 0 or abs(round(a) - a) < 1.0 / n\n\n\n\ndef generateEquations(count, SIZE, eq):\n i = 0\n OPseed = []\n NUMseed = []\n \n while i < 3:\n OPseed.insert(len(OPseed), random.randint(0, 9999999))\n i += 1\n i = 0\n \n while i < 4:\n NUMseed.insert(len(NUMseed), random.uniform(0, 9999))\n i += 1\n# print(NUMseed)\n \n# eq = arrayInit(SIZE)\n \n eq = fitEquation(NUMseed[0], NUMseed[1], NUMseed[2],\n NUMseed[3], OPseed, eq, count)\n \n\ndef arrayInit(xsize, ysize):\n eq = [[\"\" for x in range(xsize)] for y in range(ysize)]\n return eq\n\ndef fitEquation(a, b, c, d, OPseed, eq, count):\n \n opIndex = 0\n specialOP = \"SpecialOP\"\n \n for x in OPseed:\n opIndex += 2\n choice = x%4\n \n operator = \" Err Op\"\n \n if choice == 0:\n operator = \"*\"\n elif choice == 1:\n operator = \"/\"\n elif choice == 2:\n operator = \"+\"\n elif choice == 3:\n operator = \"-\"\n \n eq[count][opIndex] = operator\n \n eq[count][8] = ')'\n \n opIndex = 0\n \n temp = OPseed[1] % 25\n \n\n squareBool = (temp == 0)\n sinBool = (temp == 2)\n cosBool = (temp == 4)\n tanBool = (temp == 6)\n\n if squareBool:\n specialOP = OPCODE[4]\n \n elif sinBool:\n specialOP = OPCODE[2]\n \n elif cosBool:\n specialOP = OPCODE[3]\n \n elif tanBool:\n specialOP = OPCODE[4]\n \n else:\n specialOP = OPCODE[0]\n eq[count][8] = ''\n\n \n eq[count][0] = specialOP\n \n eq[count][1] = a\n eq[count][3] = b\n eq[count][5] = c\n eq[count][7] = d\n \n Equations.append(eq[count])\n \n# print(\"Sending to fill answer:\")\n# print(eq[count])\n \n# Solutions = fillSolution(eq, count)\n fillSolution(eq, count)\n \ndef fillSolution(x, count):\n \n\n# print(eq) \n tempEq = x[count]\n# print(tempEq)\n \n# print(\"\\n\")\n# print(\"Index: \" + str(count))\n# print('Equation handed for fill: ')\n# print(tempEq)\n\n tempEq = removeEmptyFromArray(tempEq)\n \n for var in tempEq:\n# print(var)\n if var == '*':\n tempEq = multiplication(var, tempEq)\n \n for var in tempEq:\n# print(var)\n if var == '/':\n tempEq = division(var, tempEq)\n \n for var in tempEq:\n# print(var)\n if var == '+':\n tempEq = addition(var, tempEq)\n \n for var in tempEq:\n# print(var)\n if var == '-':\n tempEq = subtraction(var, tempEq)\n \n# print(tempEq)\n x[count] = tempEq\n \n if(len(tempEq) > 1):\n \n \n if tempEq[0] == OPCODE[1]:\n tempEq[1] = cmath.sqrt(tempEq[1])\n \n elif tempEq[0] == OPCODE[2]:\n tempEq[1] = math.sin(tempEq[1])\n \n elif tempEq[0] == OPCODE[3]:\n tempEq[1] = math.cos(tempEq[1])\n \n elif tempEq[0] == OPCODE[4]:\n tempEq[1] = math.tan(tempEq[1])\n\n else:\n print(\"ERROR IN SPECIAL OPS SOLUTIONS\")\n \n tempEq[0] = ''\n tempEq[2] = ''\n tempEq = removeEmptyFromArray(tempEq)\n \n x[count] = tempEq\n Solutions.append(tempEq)\n\n \n# print('End Fill Solution \\n')\n# print(tempEq)\n \n return x\n\ndef multiplication(var, tempEq):\n \n idx = tempEq.index('*')\n# print(tempEq[idx-1])\n# print(tempEq[idx+1])\n\n mul = tempEq[idx-1] * tempEq[idx+1]\n tempEq[idx-1] = mul\n tempEq[idx] = ''\n tempEq[idx+1] = ''\n tempEq = removeEmptyFromArray(tempEq)\n# print(\"Multiplied: \")\n# print(tempEq)\n return tempEq\n\ndef division(var, tempEq):\n \n idx = tempEq.index('/')\n# print(tempEq[idx-1])\n# print(tempEq[idx+1])\n\n div = tempEq[idx-1] / tempEq[idx+1]\n tempEq[idx-1] = div\n tempEq[idx] = ''\n tempEq[idx+1] = ''\n tempEq = removeEmptyFromArray(tempEq)\n# print(\"Divided: \")\n# print(tempEq)\n return tempEq\n\ndef addition(var, tempEq):\n \n idx = tempEq.index('+')\n# print(tempEq[idx-1])\n# print(tempEq[idx+1])\n\n add = tempEq[idx-1] + tempEq[idx+1]\n tempEq[idx-1] = add\n tempEq[idx] = ''\n tempEq[idx+1] = ''\n tempEq = removeEmptyFromArray(tempEq)\n# print(\"Added: \")\n# print(tempEq)\n return tempEq\n\ndef subtraction(var, tempEq):\n \n# print(tempEq)\n\n idx = tempEq.index('-')\n# print(tempEq[idx-1])\n# print(tempEq[idx+1])\n\n sub = tempEq[idx-1] - tempEq[idx+1]\n tempEq[idx-1] = sub\n tempEq[idx] = ''\n tempEq[idx+1] = ''\n tempEq = removeEmptyFromArray(tempEq)\n# print(\"Subtracted: \")\n# print(tempEq)\n return tempEq\n \ndef removeEmptyFromArray(array):\n \n tempArray = []\n for item in array:\n# print(item.index())\n if item != '':\n tempArray.append(item)\n \n# print(\"\\n\")\n# print(\"%%%%%%%%%%%%%\")\n# print(tempArray)\n return tempArray\n \nif __name__ == '__main__':\n main()\n \n\n \n \n \n \n \n \n \n \n \n \n \n ","sub_path":"Ops.py","file_name":"Ops.py","file_ext":"py","file_size_in_byte":10647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"105062924","text":"\"\"\"\nEven Fibonacci numbers\nhttps://projecteuler.net/problem=2\n\nAnswer: 4613732\nTime: 0.000023 seconds\n\"\"\"\n\nimport time\nstart = time.perf_counter()\n\n\nnum1 = 1\nnum2 = 1\ntotal = 0\n\nwhile num2 < 4000000:\n new_num = num1 + num2\n\n if new_num % 2 == 0:\n total += new_num\n\n num1 = num2\n num2 = new_num\n\n\nend = time.perf_counter()\nduration = format(end - start, 'f')\n\nprint(\"Answer: {}\".format(total))\nprint(\"Time: {} seconds\".format(duration))\n","sub_path":"002.py","file_name":"002.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"332896614","text":"INPUT = 5\n\n\ndef calc(nums):\n idx = 0\n while idx < len(nums):\n num = str(nums[idx])\n paramodes = []\n if len(num) <= 2:\n if int(num) == 99:\n return\n opcode = int(num[-1])\n else:\n opcode = int(num[-2:])\n if int(num) == 99:\n return\n for i in range(-3, -len(num) - 1, -1):\n paramodes.append(int(num[i]))\n\n idx = run_tests(nums, idx, paramodes, opcode)\n\n\ndef run_tests(nums, idx, paramodes, opcode):\n if opcode == 3 or opcode == 4:\n if opcode == 3:\n nums[nums[idx + 1]] = INPUT\n else:\n val = nums[nums[idx + 1]] \\\n if len(paramodes) < 1 or paramodes[0] == 0 else nums[idx + 1]\n print(val)\n return idx + 2\n else:\n first_num = nums[nums[idx + 1]] \\\n if len(paramodes) < 1 or paramodes[0] == 0 else nums[idx + 1]\n sec_num = nums[nums[idx + 2]] \\\n if len(paramodes) < 2 or paramodes[1] == 0 else nums[idx + 2]\n if opcode < 3:\n if opcode == 1:\n nums[nums[idx + 3]] = first_num + sec_num\n else:\n nums[nums[idx + 3]] = first_num * sec_num\n return idx + 4\n elif opcode < 7:\n if opcode == 5:\n return idx + 3 if first_num == 0 else sec_num\n else:\n return idx + 3 if first_num != 0 else sec_num\n else:\n if opcode == 7:\n nums[nums[idx + 3]] = 1 if first_num < sec_num else 0\n else:\n nums[nums[idx + 3]] = 1 if first_num == sec_num else 0\n return idx + 4\n\n\nif __name__ == \"__main__\":\n nums = []\n with open(\"../input/day5input\") as f:\n for line in f:\n nums = [int(num) for num in line.split(\",\")]\n\n calc(nums)\n","sub_path":"src/day5p2.py","file_name":"day5p2.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"619176922","text":"import common\n\ndef create_starting_value(f):\n '''Given an ASTVariableDeclaration corresponding to any field, creates code\n to store the starting value in $eax.\n If the field has an initialization value, then that is its starting value.\n Otherwise, it gets code to set the Java default value. '''\n\n init_code = []\n # If a field has a defined initialization value, we use that expression.\n # If not, get a default value.\n if f.expression is None:\n init_code = create_default_value(f.type_node.is_primitive,\n f.type_node.is_array)\n else:\n init_code = [\n f.expression.c_gen_code(),\n ]\n\n return init_code\n\ndef create_default_value(is_primitive, is_array):\n ''' Creates code to store a variable's default value in $eax.\n Default is 0 for primitives, and a null pointer for reference types. '''\n\n init_code = []\n if is_primitive and not is_array:\n init_code = [\n 'push 0',\n 'call _create_int',\n 'pop ebx ; pop to garbage',\n ]\n else:\n init_code = [\n 'mov eax, 0 ; null pointer',\n ]\n return init_code\n\nNAMES = {}\n","sub_path":"code_gen/asm/object.py","file_name":"object.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"127203406","text":"\"\"\" Main file of the simulation package \"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport math\r\nfrom scipy.integrate import odeint, cumtrapz, ode\r\nfrom scipy.optimize import fsolve, brentq\r\n\r\nfrom support_funs import GetCd, GetCl, Sigmoid, PropTFun, PropPowerFun, PropQFun, ICEEff, AC, \\\r\n PlantSizing\r\nfrom get_params import Density, GetParams\r\n \r\n \r\ndef dcos(x):\r\n return math.cos(math.radians(x))\r\n\r\n\r\ndef dsin(x):\r\n return math.sin(math.radians(x))\r\n\r\n\r\ndef dtan(x):\r\n return dsin(x) / dcos(x)\r\n\r\n\r\ndef datan(x1, x2):\r\n return math.degrees(math.atan2(x1, x2))\r\n\r\n\r\nclass simulate(object):\r\n def __init__(self, rng, plant=None, runSizing=True):\r\n self.plotMarkers = np.array([]); self.rng = rng * 1000\r\n self.runtime = 0.; self.integrator = 'odeint'\r\n self.steps = 0; self.time = 0.\r\n self.payloadDropped = False\r\n \r\n if not plant:\r\n _, self.PP = GetParams()\r\n else:\r\n self.PP = plant.copy()\r\n \r\n # size the powerplant, get updated dictionary to store in object\r\n if runSizing:\r\n self.PP = PlantSizing(self.PP)\r\n \r\n self.battChoice = int(self.PP['battChoice'])\r\n \r\n self.battCap = self.PP['battCapList'][self.battChoice]\r\n self.battSE = self.PP['battSEList'][self.battChoice]\r\n self.battMass = self.PP['battMassList'][self.battChoice]\r\n \r\n # zero fuel mass - everything but fuel is included here\r\n self.zfm = self.battMass + AC['emptyMass'] + AC['payloadMass']\r\n \r\n self.totalMass = AC['emptyMass'] + AC['payloadMass'] + self.PP['fullTankMass']\\\r\n + self.battMass + self.PP['EMMass'] + self.PP['ICEMass']\r\n\r\n # contains x1, x2, v1, v2 in four columns\r\n self.solution = False\r\n\r\n # vars for sigmoid schedules\r\n self.TFloor = 0.; self.pitchFloor = 0.\r\n self.TCeiling = 0.; self.pitchCeiling = 0.\r\n self.TStart = 0.; self.pitchStart = 0.\r\n self.TEnd = 0.; self.pitchEnd = 0.\r\n self.TShape = 'const'; self.pitchShape = 'const'\r\n\r\n # total amount of data, total time steps returned from ODE solver\r\n self.n = 0\r\n\r\n # initial values for ode solver\r\n self.y0 = np.zeros(4)\r\n\r\n \"\"\" data arrays \"\"\"\r\n\r\n # angles\r\n self.alpha = np.zeros(10**3)\r\n self.pitch = np.zeros(10**3)\r\n self.gamma = np.zeros(10**3)\r\n \r\n # kinematics\r\n self.x1 = np.zeros(10**3); self.x2 = np.zeros(10**3)\r\n self.v1 = np.zeros(10**3); self.v2 = np.zeros(10**3)\r\n self.a1 = np.zeros(10**3); self.a2 = np.zeros(10**3)\r\n \r\n \r\n # time that corresponds with each index\r\n self.timeArray = np.zeros(10**3)\r\n \r\n # thrust\r\n self.thrust = np.zeros(10**3)\r\n self.EMThrust = np.zeros(10**3)\r\n self.ICEThrust = np.zeros(10**3)\r\n\r\n # energy related\r\n self.totalE = np.zeros(10**3); self.fuelMass = np.zeros(10**3)\r\n self.fuelE = np.zeros(10**3); self.SOC = np.zeros(10**3)\r\n self.battE = np.zeros(10**3)\r\n\r\n # power related\r\n self.power = np.zeros(10**3) # total power coming out of the prop\r\n self.fuelP = np.zeros(10**3) # power consumed by ICE\r\n self.battP = np.zeros(10**3) # power consumed by EM\r\n self.ICEShaftP = np.zeros(10**3)\r\n self.EMShaftP = np.zeros(10**3)\r\n self.ICEPropP = np.zeros(10**3) # total power produced by the ICE connected propeller\r\n self.EMPropP = np.zeros(10**3) # total power produced by the EM connected propeller\r\n \r\n self.ICEEff = np.zeros(10**3) # ICE brake efficiency \r\n \r\n ### propeller related ###\r\n # -- EM Propeller -- # # -- ICE Propeller -- #\r\n self.EMrps = np.zeros(10**3); self.ICErps = np.zeros(10**3)\r\n self.EMJ = np.zeros(10**3); self.ICEJ = np.zeros(10**3)\r\n self.EMPropEff = np.zeros(10**3); self.ICEPropEff = np.zeros(10**3)\r\n \r\n self.EMTotEff = np.zeros(10**3)\r\n self.ICETotEff = np.zeros(10**3)\r\n self.rEM = np.zeros(10**3) # ratio of output power provided by EM\r\n \r\n # 0 - off, 1 - ICE only, 2 - ICE ideal and EM, 3 - EM max and ICE, 4 - excess\r\n self.RBOut = np.zeros(10**3)\r\n self.massCost = np.zeros(10**3)\r\n\r\n\r\n def Equations(self, t, y):\r\n \"\"\"Returns the equations of motion to be integrated by the\r\n ODE integrator.\"\"\"\r\n # y must be an array with elements x1 x2 v1 and v2 which is passed by the\r\n # ODE solver\r\n\r\n x1, x2, v1, v2 = y\r\n\r\n dydt = [0, 0, 0, 0]\r\n\r\n dydt[0] = v1\r\n \r\n dydt[1] = v2\r\n \r\n dydt[2] = (GetCoeffA(self.GetAlpha(t, v1, v2), self.GetGamma(v1, v2), x2)\r\n * (v1**2 + v2**2) + self.TSchedule(t) * dcos(self.PitchSchedule(t)))\\\r\n / self.totalMass\r\n \r\n dydt[3] = (GetCoeffB(self.GetAlpha(t, v1, v2), self.GetGamma(v1, v2), x2)\r\n * (v1**2 + v2**2) + self.TSchedule(t) * dsin(self.PitchSchedule(t)))\\\r\n / self.totalMass - AC['g']\r\n\r\n # reaction force implementation\r\n if GetCoeffB(self.GetAlpha(t, dydt[0], dydt[1]), self.GetGamma(v1, v2), x2) * (dydt[0]**2) \\\r\n < self.totalMass * AC['g'] and x2 == 0:\r\n dydt[3] = 0\r\n\r\n return dydt\r\n\r\n\r\n def GetGamma(self, v1, v2):\r\n return math.degrees(math.atan2(v2, v1))\r\n\r\n\r\n def GetAlpha(self, t, v1, v2):\r\n return self.PitchSchedule(t) - self.GetGamma(v1, v2)\r\n\r\n\r\n def TSchedule(self, t):\r\n \"\"\"Returns the required thrust output signal in Newtons.\"\"\"\r\n if self.TShape == 'const':\r\n return self.TCeiling\r\n\r\n elif self.TShape == 'sigmoid':\r\n return Sigmoid(t, self.TFloor, self.TCeiling,\r\n self.TStart, self.TEnd)\r\n\r\n\r\n def PitchSchedule(self, t):\r\n if self.pitchShape == 'const':\r\n return self.pitchCeiling\r\n\r\n elif self.pitchShape == 'sigmoid':\r\n return Sigmoid(t, self.pitchFloor, self.pitchCeiling,\r\n self.pitchStart, self.pitchEnd)\r\n\r\n else:\r\n raise ValueError('pitchShape variable named incorrectly')\r\n\r\n\r\n def PDemand(self):\r\n \"\"\"Power that must come out of the powerplant overall (returns in kW)\"\"\"\r\n return self.V() * self.thrust[self.n]\r\n\r\n\r\n \"\"\"f(v1, v2)\"\"\"\r\n def V(self):\r\n \"\"\"get the absolute value of the velocity in m/s\"\"\"\r\n V = math.sqrt(self.v1[self.n]**2 + self.v2[self.n]**2)\r\n return V\r\n\r\n\r\n def RunInterval(self):\r\n \"\"\"Runs the simulation, updates all the data. List of tasks completed:\r\n 1 - runs the ode solver (integrate.ode or integrate.odeint) and obtains\r\n the position and velocity values\r\n \r\n 2 - ensures the data arrays are long enough to store the incoming data\r\n \r\n 3 - store all the data in the arrays mentioned in 2.\r\n 3.1 - extract all the velocity and position data from the solution array\r\n obtained from numerical ode solver\r\n 3.2 - store the control inputs as they were in time (pitch and thrust),\r\n as well as the other relevant angles (gamma, alpha)\r\n 3.3 - calculate and store (using simulator methods) values for the power\r\n consumed by the ICE, EM and in total\r\n 3.4 - keep track of the size of the time-steps taken by storing the time\r\n associated with each index of the data arrays\r\n 3.5 - calculate and store the horizontal and vertical acceleration\r\n values (resultant acceleration) by differentiating velocity data\r\n 3.6 - calculate and store the energy needed by the EM and the ICE by\r\n integrating the power values from 3.3. Calculate and store the\r\n corresponding fuel mass and SOC\r\n \r\n 4 - keep track of the times at which this RunInterval() method was\r\n called to keep track of separate interval calls\r\n\r\n 5 - update misc values: the number of data that exists (n), the\r\n length of time that has been simulated (time) and set the initial\r\n data for the ODE solvers to the last data from this run\r\n\r\n 6 - Ensures the default setting for the thrust and pitch schedules is\r\n constant. This makes quickly changing the control inputs from\r\n the command line quicker.\r\n \"\"\"\r\n\r\n \r\n # check the time is running forward\r\n if self.runtime < 0:\r\n raise ValueError('RunInterval() is receiving a negative runtime'\r\n + ' of' + str(round(self.runtime, 2)))\r\n elif self.runtime == 0:\r\n raise ValueError('RunInterval() is receiving a runtime of zero')\r\n \r\n self.steps = int(self.steps)\r\n \r\n t = np.linspace(0, self.runtime, self.steps + 1)\r\n\r\n # make sure the timesteps is 2 or greater to allow the np.gradient to run\r\n if self.steps < 2:\r\n raise ValueError('RunInterval has been called by a function with'\r\n 'less than two steps per Interval')\r\n\r\n \"\"\" 1. get x1, x2, v1 and v2 by solving the equations of\r\n motion numerically \"\"\"\r\n \r\n if self.integrator == 'ode':\r\n # create empty 2d array to store the solution\r\n self.solution = np.zeros((self.steps, 4))\r\n \r\n # create ode object to compute values\r\n eq = ode(self.Equations).set_initial_value(self.y0).set_integrator('vode')\r\n \r\n # define time-step\r\n dt = self.runtime / self.steps\r\n \r\n for i in range(self.steps):\r\n self.solution[i, :] = eq.integrate(eq.t + dt)\r\n \r\n elif self.integrator == 'odeint':\r\n self.solution = odeint(self.Equations, self.y0, t, tfirst=True)\r\n\r\n # print('Solution length: ', len(self.solution[:, 0]), '\\n')\r\n\r\n \"\"\" 2. make sure that the list of zeros is long enough,\r\n append more if not. Numpy appending is slow, so this way it is kept\r\n to minimum \"\"\"\r\n if len(self.x1) <= self.n + len(self.solution[:, 0]) or self.steps > 10**3:\r\n self.x1 = np.append(self.x1, np.zeros(10**3))\r\n self.x2 = np.append(self.x2, np.zeros(10**3))\r\n self.v1 = np.append(self.v1, np.zeros(10**3))\r\n self.v2 = np.append(self.v2, np.zeros(10**3))\r\n self.a1 = np.append(self.a1, np.zeros(10**3))\r\n self.a2 = np.append(self.a2, np.zeros(10**3))\r\n \r\n self.timeArray = np.append(self.timeArray, np.zeros(10**3))\r\n \r\n self.alpha = np.append(self.alpha, np.zeros(10**3))\r\n self.pitch = np.append(self.pitch, np.zeros(10**3))\r\n self.gamma = np.append(self.gamma, np.zeros(10**3))\r\n \r\n self.thrust = np.append(self.thrust, np.zeros(10**3))\r\n self.ICEThrust = np.append(self.ICEThrust, np.zeros(10**3))\r\n self.EMThrust = np.append(self.EMThrust, np.zeros(10**3))\r\n\r\n self.power = np.append(self.power, np.zeros(10**3))\r\n self.fuelP = np.append(self.fuelP, np.zeros(10**3))\r\n self.battP = np.append(self.battP, np.zeros(10**3))\r\n self.ICEShaftP = np.append(self.ICEShaftP, np.zeros(10**3))\r\n self.EMShaftP = np.append(self.EMShaftP, np.zeros(10**3))\r\n self.ICEPropP = np.append(self.ICEPropP, np.zeros(10**3))\r\n self.EMPropP = np.append(self.EMPropP, np.zeros(10**3))\r\n\r\n self.SOC = np.append(self.SOC, np.zeros(10**3))\r\n self.fuelMass = np.append(self.fuelMass, np.zeros(10**3))\r\n self.fuelE = np.append(self.fuelE, np.zeros(10**3))\r\n self.battE = np.append(self.battE, np.zeros(10**3))\r\n self.totalE = np.append(self.totalE, np.zeros(10**3))\r\n \r\n self.EMrps = np.append(self.EMrps, np.zeros(10**3))\r\n self.ICErps = np.append(self.ICErps, np.zeros(10**3))\r\n self.ICEJ = np.append(self.ICEJ, np.zeros(10**3))\r\n self.EMJ = np.append(self.EMJ, np.zeros(10**3))\r\n self.EMPropEff = np.append(self.EMPropEff, np.zeros(10**3))\r\n self.ICEPropEff = np.append(self.ICEPropEff, np.zeros(10**3))\r\n \r\n self.EMTotEff = np.append(self.EMTotEff, np.zeros(10**3))\r\n self.ICETotEff = np.append(self.ICETotEff, np.zeros(10**3))\r\n self.rEM = np.append(self.rEM, np.zeros(10**3))\r\n self.RBOut = np.append(self.RBOut, np.zeros(10**3))\r\n \r\n self.massCost = np.append(self.massCost, np.zeros(10**3))\r\n self.ICEEff = np.append(self.ICEEff, np.zeros(10**3))\r\n \r\n \"\"\" 4. fill array for markers where odeint restarted\"\"\"\r\n self.plotMarkers = np.append(self.plotMarkers, int(self.n))\r\n\r\n\r\n \"\"\" 3. Loop to fill the data lists x1, x2, v1 etc.\"\"\"\r\n if self.n == 0:\r\n m = len(self.solution[:, 0])\r\n else:\r\n m = len(self.solution[:, 0]) - 1\r\n for i in range(m):\r\n if self.n - self.steps > 0:\r\n i += 1\r\n \r\n self.n += 1\r\n\r\n self.timeArray[self.n] = self.timeArray[self.n - 1] + self.runtime / self.steps\r\n\r\n \"\"\" 3.1 Set displacement and velocity values\"\"\"\r\n self.x1[self.n] = self.solution[i, 0]\r\n self.x2[self.n] = self.solution[i, 1]\r\n self.v1[self.n] = self.solution[i, 2]\r\n self.v2[self.n] = self.solution[i, 3]\r\n\r\n \"\"\" 3.2 fill thrust, alpha and pitch arrays\"\"\"\r\n self.thrust[self.n] = self.TSchedule(t[i])\r\n self.alpha[self.n] = self.GetAlpha(t[i], self.v1[self.n], self.v2[self.n])\r\n self.pitch[self.n] = self.PitchSchedule(t[i])\r\n self.gamma[self.n] = self.GetGamma(self.v1[self.n], self.v2[self.n])\r\n\r\n \"\"\" 3.3 RB controller to allocate the thrust \"\"\"\r\n self.AllocateThrust()\r\n \r\n \"\"\" 3.4 Find power related values \"\"\"\r\n \r\n # check if the thrust request exceeds the available thrust\r\n if self.RBOut[self.n] == 4:\r\n self.EMShaftP[self.n] = 10e5\r\n self.ICEShaftP[self.n] = 10e5\r\n \r\n else:\r\n self.EMShaftP[self.n] = PropPowerFun(v=self.V(), rps=self.EMrps[self.n],\r\n h=self.x2[self.n])\r\n self.ICEShaftP[self.n] = PropPowerFun(v=self.V(), rps=self.ICErps[self.n],\r\n h=self.x2[self.n])\r\n \r\n self.ICEPropP[self.n] = self.ICEThrust[self.n] * self.V()\r\n self.EMPropP[self.n] = self.EMThrust[self.n] * self.V()\r\n self.power[self.n] = self.PDemand()\r\n \r\n \r\n # if the propeller is not spinning, there cannot be a J value\r\n if self.ICErps[self.n] == 0:\r\n self.ICEJ[self.n] = np.nan\r\n ICETorque = 0\r\n else:\r\n self.ICEJ[self.n] = self.V() / (self.PP['D'] * self.ICErps[self.n])\r\n # needed later because ICEEff = f(Torque)\r\n ICETorque = PropQFun(self.V(), self.ICErps[self.n], self.x2[self.n])\r\n \r\n # if the propeller is not spinning, there cannot be a J value\r\n if self.EMrps[self.n] == 0:\r\n self.EMJ[self.n] == np.nan\r\n \r\n else:\r\n self.EMJ[self.n] = self.V() / (self.PP['D'] * self.EMrps[self.n])\r\n \r\n # prevent a call to the ICEEff function if excess torque is demanded from ICE\r\n if self.RBOut[self.n] == 4:\r\n self.ICEEff[self.n] = 0.01\r\n else:\r\n self.ICEEff[self.n] = ICEEff(self.ICErps[self.n], ICETorque)\r\n \r\n # find power drawn from battery and fuel tank\r\n self.battP[self.n] = self.EMShaftP[self.n] / self.PP['EMEff']\r\n self.fuelP[self.n] = self.ICEShaftP[self.n] / self.ICEEff[self.n]\r\n\r\n \r\n if self.x1[self.n] >= self.rng / 2 and not self.payloadDropped:\r\n self.DropPayload()\r\n self.payloadDropped = self.x1[self.n]\r\n # print('Payload Dropped at distance =', round(self.x1[self.n]/1000, 2), 'km',\r\n # 'and time =', self.timeArray[self.n], 's')\r\n\r\n s = self.n - m\r\n \"\"\" 3.5 find the accelerations\"\"\"\r\n # direct differentiation from the solution array\r\n self.a1[s:s + m] = np.gradient(self.solution[:m, 2])\r\n self.a2[s:s + m] = np.gradient(self.solution[:m, 3])\r\n\r\n\r\n \"\"\" 5. update number of simulation steps taken, the total time that has\r\n passed and the initial conditions for the ODE solver \"\"\"\r\n self.time = self.timeArray[self.n]\r\n self.oldy0 = self.y0\r\n self.y0[0] = self.solution[-1, 0]\r\n self.y0[1] = self.solution[-1, 1]\r\n self.y0[2] = self.solution[-1, 2]\r\n self.y0[3] = self.solution[-1, 3]\r\n \r\n # print('solution: ', self.solution[-1,:],'\\n')\r\n \r\n self.TShape = 'const'\r\n self.pitchShape = 'const'\r\n\r\n def CalculateE(self):\r\n e = self.n\r\n self.fuelE = cumtrapz(self.fuelP[0:e], self.timeArray[0:e],\r\n initial=self.fuelE[0])\r\n \r\n self.battE = cumtrapz(self.battP[0:e], self.timeArray[0:e],\r\n initial=self.battE[0])\r\n \r\n self.totalE = self.battE + self.fuelE\r\n\r\n self.SOC = (1 - self.battE / self.battCap)\r\n self.fuelMass = self.PP['fullTankMass'] - self.fuelE / self.PP['LCV']\r\n \r\n self.EMTotEff = self.EMPropP / (self.battP + 1e-5)\r\n self.ICETotEff = self.ICEPropP / (self.fuelP + 1e-5)\r\n self.rEM = self.EMPropP / (self.EMPropP + self.ICEPropP + 1e-5)\r\n \r\n self.rEM = self.EMThrust / (self.thrust + 1e-5)\r\n\r\n self.battMassCost = self.battE / self.battSE\r\n self.fuelMassCost = self.PP['fullTankMass'] - self.fuelMass\r\n self.massCost = self.battMassCost + self.fuelMassCost\r\n\r\n\r\n def AllocateThrust(self):\r\n v = self.V()\r\n h = self.x2[self.n]\r\n thrustRequest = self.thrust[self.n]\r\n \r\n idealICEThrust = PropTFun(v, self.PP['idealICErps'], h)\r\n \r\n maxICEThrust = PropTFun(v, self.PP['ICEMaprps'][-1], h)\r\n \r\n maxEMThrust = PropTFun(v, self.PP['maxEMrps'], h)\r\n \r\n # print('Requested Thrust =', thrustRequest)\r\n # print('Max EM thrust available=', maxEMThrust[0])\r\n # print('Max ICE thrust available=', maxICEThrust[0])\r\n \r\n # use a guess which would produce the ideal J for the prop eff\r\n rpsGuess = v / (self.PP['D'] * self.PP['optJ'])\r\n if rpsGuess < 10:\r\n rpsGuess = 10\r\n \r\n # warn if thrust cannot be given, then set the rpm to the necessary value\r\n # this will be filtered out later and converted to a disproportionately high energy cost\r\n if thrustRequest > maxICEThrust + maxEMThrust:\r\n print('\\nWARNING: THE THRUST REQUESTED IS NOT AVAILABLE.',\r\n thrustRequest, 'N were requested but only',\r\n maxICEThrust + maxEMThrust, 'are available')\r\n print('Current velocity:', self.V(), '\\n')\r\n \r\n excess = thrustRequest - maxICEThrust - maxEMThrust\r\n \r\n ICEThrust = maxICEThrust + excess / 2\r\n EMThrust = maxEMThrust + excess / 2\r\n try:\r\n ICErps = brentq(lambda rps: PropTFun(v, rps, h) - ICEThrust,\r\n self.PP['ICEMaprps'][0], self.PP['ICEMaprps'][-1] * 2)\r\n except ValueError:\r\n ICErps = self.PP['ICEMaprps'][-1]\r\n \r\n try:\r\n EMrps = brentq(lambda rps: PropTFun(v, rps, h) - EMThrust,\r\n 0, self.PP['maxEMrps'] * 2)\r\n except ValueError:\r\n EMrps = self.PP['maxEMrps']\r\n\r\n self.RBOut[self.n] = 4\r\n \r\n # use max EM thrust and lowest possible ICE thrust\r\n elif thrustRequest > idealICEThrust + maxEMThrust:\r\n EMThrust = maxEMThrust\r\n ICEThrust = thrustRequest - EMThrust\r\n \r\n EMrps = self.PP['maxEMrps']\r\n\r\n ICErps = brentq(lambda rps: PropTFun(v, rps, h) - ICEThrust,\r\n self.PP['ICEMaprps'][0], self.PP['ICEMaprps'][-1])\r\n self.RBOut[self.n] = 3\r\n \r\n # use ideal ICE thrust and the rest is EM power\r\n elif thrustRequest > idealICEThrust:\r\n ICEThrust = idealICEThrust\r\n EMThrust = thrustRequest - ICEThrust\r\n\r\n ICErps = self.PP['idealICErps']\r\n EMrps = brentq(lambda rps: PropTFun(v, rps, h) - EMThrust,\r\n 0, self.PP['maxEMrps'])\r\n\r\n self.RBOut[self.n] = 2\r\n \r\n # use only ICE\r\n elif thrustRequest <= idealICEThrust and thrustRequest > 0:\r\n ICEThrust = thrustRequest\r\n EMThrust = 0\r\n \r\n EMrps = 0\r\n \r\n # if the thrust is tiny, set it to zero\r\n if PropTFun(v, 1, h) - ICEThrust > 0:\r\n ICEThrust = 0\r\n ICErps = 0\r\n \r\n self.RBOut[self.n] = 0\r\n \r\n else:\r\n ICErps = brentq(lambda rps: PropTFun(v, rps, h) - ICEThrust,\r\n 1, self.PP['ICEMaprps'][-1])\r\n \r\n self.RBOut[self.n] = 1\r\n \r\n # plant is off\r\n elif thrustRequest == 0:\r\n ICEThrust = 0\r\n EMThrust = 0\r\n \r\n EMrps = 0\r\n ICErps = 0\r\n self.RBOut[self.n] = 0\r\n \r\n self.EMrps[self.n] = EMrps\r\n self.ICErps[self.n] = ICErps\r\n self.EMThrust[self.n] = EMThrust\r\n self.ICEThrust[self.n] = ICEThrust\r\n \r\n # print('EMrps =', EMrps)\r\n # print('EMThrust =', EMThrust)\r\n # print('ICErps =', ICErps)\r\n # print('ICEThrust =', ICEThrust)\r\n \r\n # print('\\n Exiting RB \\n')\r\n \r\n \r\n def IdealTRange(self, *args):\r\n \"\"\" Returns the total (EM+ICE)thrust range at which the powerplant\r\n can run the ICE at ideal rps\"\"\"\r\n \r\n if len(args) == 0:\r\n v = self.V()\r\n h = self.x2[self.n]\r\n \r\n else:\r\n v = args[0]\r\n h = args[1]\r\n \r\n lower = PropTFun(v, self.PP['idealICErps'], h)[0]\r\n \r\n upper = (PropTFun(v, self.PP['maxEMrps'], h) + lower)[0]\r\n \r\n return lower, upper\r\n \r\n def DropPayload(self):\r\n self.zfm -= AC['payloadMass']\r\n self.totalMass -= AC['payloadMass']\r\n # print('Payload dropped at x1 = ', self.x1[self.n])\r\n\r\n\r\ndef GetCoeffA(alpha, gamma, h):\r\n \"\"\"\r\n Returns a coefficient for the (horizontal) equations of motion.Written out here to\r\n keep the EOMs shorter and neater. Should only be called the function which implements\r\n the EOMs for scipy.integrate.ode(int).\r\n\r\n Parameters\r\n ----------\r\n alpha : int or float\r\n Angle of attack.\r\n gamma : int or float\r\n Flight path angle.\r\n h : int or float\r\n Altitude.\r\n\r\n Raises\r\n ------\r\n ValueError\r\n When args of wrong type are passed\r\n\r\n Returns\r\n -------\r\n float\r\n Value of the coefficient.\r\n \"\"\"\r\n\r\n return -0.5 * Density(h) * AC['S'] \\\r\n * (GetCd(alpha, h) * dcos(gamma) + GetCl(alpha) * dsin(gamma))\r\n\r\n\r\ndef GetCoeffB(alpha, gamma, h):\r\n \"\"\"\r\n Returns a coefficient for the (vertical) equations of motion.Written out here to\r\n keep the EOMs shorter and neater. Should only be called the function which implements\r\n the EOMs for scipy.integrate.ode(int).\r\n\r\n Parameters\r\n ----------\r\n alpha : int or float\r\n Angle of attack.\r\n gamma : int or float\r\n Flight path angle.\r\n h : int or float\r\n Altitude.\r\n\r\n Raises\r\n ------\r\n ValueError\r\n When args of wrong type are passed\r\n\r\n Returns\r\n -------\r\n float\r\n Value of the coefficient.\r\n\r\n \"\"\"\r\n\r\n return (0.5 * Density(h) * AC['S'] * (GetCl(alpha) * dcos(gamma)\r\n - GetCd(alpha, h) * dsin(gamma)))\r\n","sub_path":"Program_Files/simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":25021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"586285924","text":"import logging as log\nimport cfnresponse\nimport boto3\nimport zipfile\nimport json\nimport hashlib\n\nlog.getLogger().setLevel(log.INFO)\n\ndef main(event, context):\n\n fqn = event['StackId'] + event['LogicalResourceId']\n physical_id = hashlib.md5(fqn.encode('utf-8')).hexdigest()\n log.info(physical_id)\n\n try:\n log.info('Input event: %s', event)\n\n bucket = event['ResourceProperties']['Bucket']\n key = event['ResourceProperties']['ObjectKey']\n\n # Retrieve artifact image details\n s3 = boto3.client('s3')\n s3.download_file(bucket, key, '/tmp/artifact.zip')\n with zipfile.ZipFile('/tmp/artifact.zip', 'r') as zip_ref:\n zip_ref.extractall('/tmp/artifacts')\n with open('/tmp/artifacts/imageDetail.json') as f:\n data = json.load(f)\n imageUri = data['ImageURI']\n\n\n attributes = {\n 'Response': imageUri\n }\n\n cfnresponse.send(event, context, cfnresponse.SUCCESS, attributes, physical_id)\n except Exception as e:\n log.exception(e)\n # cfnresponse's error message is always \"see CloudWatch\"\n cfnresponse.send(event, context, cfnresponse.FAILED, {}, physical_id)","sub_path":"installers/aws-eks-cdk/lib/handlers/artifactImageId/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"149782469","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Graph module.\"\"\"\n\n# package(s) related to time, space and id\nimport json\nimport logging\nimport uuid\nimport os\n\n# you need these dependencies (you can get these from anaconda)\n# package(s) related to the simulation\nimport simpy\nimport networkx as nx\n\n# spatial libraries\nimport pyproj\nimport shapely.geometry\n\n# matplotlib\nimport math\nimport matplotlib.pyplot as plt\n\nlogger = logging.getLogger(__name__)\n\n\nclass Graph:\n \"\"\"General networkx object\n\n Initialize a nx.Graph() element\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.graph = nx.Graph()\n self.graph_info = nx.info(self.graph)\n\n def from_shape(self, file_location, shapefile, simplify=True, strict=True):\n \"\"\"Generate nx.Graph() from shapefile\n \n file_location: location on server of the shapefile\n shapefile: name of the shapefile (including .shp)\n \"\"\"\n from osgeo import ogr, osr\n\n # Create graph\n self.graph = nx.read_shp(\n os.path.join(file_location, shapefile), simplify=simplify, strict=strict\n )\n self.graph_info = nx.info(self.graph)\n\n # Get spatial reference\n driver = ogr.GetDriverByName(\"ESRI Shapefile\")\n dataset = driver.Open(os.path.join(file_location, shapefile))\n self.SpatialRef = dataset.GetLayer().GetSpatialRef()\n\n def transform_projection(self, to_EPSG):\n from osgeo import ogr, osr\n\n outSpatialRef = osr.SpatialReference()\n outSpatialRef.ImportFromEPSG(to_EPSG)\n\n # Transform the coordinates\n transform = osr.CoordinateTransformation(self.SpatialRef, outSpatialRef)\n\n return transform\n\n def change_projection(self, transform, point):\n from osgeo import ogr, osr\n\n point = ogr.CreateGeometryFromWkt(str(point))\n\n point.Transform(transform)\n point.ExportToWkt()\n\n return point.GetX(), point.GetY()\n\n def create_graph_new_projection(self, to_EPSG=4326):\n new_graph = nx.Graph()\n transform = self.transform_projection(to_EPSG)\n\n # Required to prevent loop-in-loop\n nodes_dict = {}\n\n # Add original nodes and edges to new graph\n for i, node in enumerate(self.graph.nodes(data=True)):\n coordinates = self.change_projection(\n transform,\n shapely.geometry.Point(\n list(self.graph.nodes)[i][0], list(self.graph.nodes)[i][1]\n ),\n )\n name = \"({:f}, {:f})\".format(coordinates[0], coordinates[1])\n geometry = shapely.geometry.Point(coordinates[0], coordinates[1])\n\n nodes_dict[list(self.graph.nodes)[i]] = name\n new_graph.add_node(\n name, name=name, Position=coordinates, geometry=geometry, Old=node[1]\n )\n\n for edge in self.graph.edges(data=True):\n node_1 = nodes_dict[edge[0]]\n node_2 = nodes_dict[edge[1]]\n\n new_graph.add_edge(node_1, node_2, Info=edge[2])\n\n new_graph = new_graph.to_directed()\n\n if nx.info(new_graph) != self.graph_info:\n self.graph = new_graph\n self.graph_info = nx.info(new_graph)\n else:\n print(\"Conversion did not create an exact similar graph\")\n\n print(\"\")\n print(\"Original graph\")\n print(self.graph_info)\n\n print(\"\")\n print(\"New graph\")\n print(nx.info(new_graph))\n\n self.graph = new_graph\n self.graph_info = nx.info(new_graph)\n\n def add_resources(self, edges, resources, environment):\n for i, edge in enumerate(edges):\n self.graph.edges[edge][\"Resources\"] = simpy.Resource(\n environment, capacity=resources[i]\n )\n\n def plot(\n self,\n size=[10, 10],\n with_labels=False,\n node_size=0.5,\n font_size=2,\n width=0.2,\n arrowsize=3,\n ):\n plt.figure(figsize=size)\n\n # If graph has positional attributes\n try:\n nx.draw(\n self.graph,\n nx.get_node_attributes(self.graph, \"Position\"),\n with_labels=with_labels,\n node_size=node_size,\n font_size=font_size,\n width=width,\n arrowsize=arrowsize,\n )\n # If graph does not have any positional information\n except:\n nx.draw(self.graph)\n\n plt.show()\n","sub_path":"opentnsim/graph_module.py","file_name":"graph_module.py","file_ext":"py","file_size_in_byte":4529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"283406221","text":"# Copyright 2016 Mirantis, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom stacklight_tests.helpers import helpers\nfrom stacklight_tests import settings\n\nname = 'ceilometer-redis'\nplugin_path = settings.CEILOMETER_REDIS_PLUGIN_PATH\nversion = helpers.get_plugin_version(plugin_path)\ndefault_options = {}\nbase_nodes = {\n 'slave-01': ['controller', 'mongo'],\n 'slave-02': ['controller', 'mongo'],\n 'slave-03': ['controller', 'mongo'],\n 'slave-04': ['compute', 'cinder'],\n 'slave-05': ['compute', 'cinder']\n}\npolling_interval = 600\n","sub_path":"stacklight_tests/ceilometer_redis/plugin_settings.py","file_name":"plugin_settings.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"110776528","text":"from matplotlib import pyplot as plt\r\nfrom Ex_1.Neurons import simulate_with_func, AELIF, LIF, ELIF\r\n\r\n\r\ndef plot_mv_ms(mv, time_list, name=\"\", top=None, bottom=None):\r\n plt.plot(time_list, mv)\r\n plt.ylim(top=top, bottom=bottom)\r\n plt.ylabel('Membrane Potential (mV)')\r\n plt.xlabel('Time (ms)')\r\n if name!=\"\": name=\" for \"+name\r\n name=\"Voltage-Current\"+name\r\n plt.title(name)\r\n plt.savefig(name)\r\n plt.show()\r\n\r\n\r\ndef plot_current(current, time_list, name=\"\"):\r\n plt.plot(time_list, current)\r\n plt.ylabel('Input current (pA)')\r\n plt.xlabel('Time (ms)')\r\n if name!=\"\": name=\" for \"+name\r\n name=\"Time-Current\"+name\r\n plt.title(name)\r\n plt.savefig(name)\r\n plt.show()\r\n\r\n\r\ndef plot_internal_current(current, time_list, name=1):\r\n plt.plot(time_list, current)\r\n plt.ylabel('Adaption current (pA)')\r\n plt.xlabel('Time (ms)')\r\n if name!=1: name=\" for \"+name\r\n name=\"Time-Adaption Current\"+name\r\n plt.title(name)\r\n # plt.savefig(name)\r\n plt.show()\r\n\r\n\r\ndef get_freq_vs_current(type, *args, **kwargs):\r\n current_list = [i for i in range(1000, 8000, 50)]\r\n freq_list = []\r\n for const_I in current_list:\r\n print(\"checking with current=\"+str(const_I))\r\n U_over_t, _, current = simulate_with_func(\r\n type, 10000, lambda x: const_I, *args, **kwargs)\r\n freq_list.append(len([0 for a in U_over_t if a > 0]) / 10000.0)\r\n\r\n plt.plot(current_list, freq_list)\r\n plt.ylabel('Frequency (KHz)')\r\n plt.xlabel('Input Current')\r\n plt.show()\r\n\r\n\r\ndef random_smooth_array(l):\r\n from numpy import random, array, convolve, ones, linspace\r\n x=linspace(0, 1000, num=l*10)\r\n y = 0\r\n result = []\r\n for _ in x:\r\n result.append(y)\r\n y += random.normal(scale=1)\r\n r_x=10\r\n random_array=convolve(array(result), ones((r_x,)) / r_x)[(r_x - 1):]\r\n return lambda x: abs(random_array[int(x*10)])*150\r\n\r\n\r\ndef limited_sin(time_steps):\r\n from math import sin\r\n from random import random\r\n\r\n rand_array = random_smooth_array(time_steps)\r\n\r\n a=[]\r\n for t in range(time_steps):\r\n x=t/time_steps*22+0.001\r\n a.append(2*sin(x)/x+sin(x*0.8)+1.5+rand_array(t)/50000)\r\n return lambda i: a[int(i)]*900\r\n\r\n\r\nif __name__ == \"__main__\":\r\n dt=0.03125; runtime = 100\r\n\r\n # **************************************************\r\n # config = [\"LIF\",\"dt=dt, R=10, tau=8, theta=-45, U_rest=-79, U_reset=-65, U_spike=5\"]\r\n config = [\"AELIF\",\"dt=dt, R=10, tau=8, theta=-40, U_rest=-70, U_reset=-65, U_spike=5,\"\r\n \"ref_period=2, ref_time=0, theta_rh=-45, delta_t=2, a=0.01, b=500, tau_k=100\"]\r\n # config = [\"AELIF\",\"dt=dt, R=10, tau=8, theta=-50, U_rest=-70, U_reset=-65, U_spike=10,\"\r\n # \"ref_period=0, ref_time=0, theta_rh=-58, delta_t=1, a=0.01, b=500, tau_k=100\"]\r\n # config = [\"ELIF\",\"dt=dt, R=10, tau=8, theta=-40, U_rest=-70, U_reset=-65, U_spike=5,\"\r\n # \"ref_period=2, ref_time=0, theta_rh=-45, delta_t=2\"]\r\n\r\n # **************************************************\r\n # *****freq*****\r\n # eval(\"get_freq_vs_current(type=\" + config[0] +\",\"+ config[1]+\")\")\r\n\r\n # **************************************************\r\n # *****with current*****\r\n time_list=[i*dt for i in range(int(runtime//dt))]\r\n\r\n # func=random_smooth_array(len(time_list))\r\n\r\n func=lambda x: (int(10<=x<=20)*2000+int(30<=x<=40)*5000+int(50<=x<=60)*7000)\r\n\r\n # func=lambda x: int(10<=x)*3000\r\n\r\n # from numpy import sin;func=lambda x: 4000*(sin(x)+0.9)\r\n\r\n # **************************************************\r\n U_over_t, inter_curr, current = eval(\"simulate_with_func(type=\" + config[0] +\r\n \", run_time=runtime, curr_func=func,\" + config[1] + \")\")\r\n func_used=\" (constant current 2)\"\r\n plot_mv_ms(U_over_t, time_list, name=config[0]+func_used, top=-35, bottom=-80)\r\n plot_internal_current(inter_curr, time_list, name=config[0]+func_used)\r\n plot_current(current, time_list, name=config[0]+func_used)\r\n","sub_path":"Hossein Mohammadi - 96222096/Project 2/source code (ex_2 needs ex_1 too)/Ex_1/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":4031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"421232831","text":"import string\n#Read in a string\ns = str(open(\"input/input00.txt\").read())\nl = len(s)\n\n#Calculate total possible substrings and subtrings that start with a vowel\nTotal = sum([l- i for i in range(l)])\nKscore = sum([l-i if s[i] in ['A','E','I','O','U'] else 0 for i in range(l)])\n\n#If it's not a draw, print the winners score (fraction of total)\nif Kscore != Total / 2:\n print('Kevin ' + str(Kscore) if Kscore > Total - Kscore else 'Stuart ' + str(Total - Kscore) )\nelse:\n print('Draw')","sub_path":"Minion Game/Minion Game.py","file_name":"Minion Game.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"425873264","text":"import arcade\n\narcade.open_window(600,600, \"Star Wars Art\")\narcade.set_background_color(arcade.color.STAR_COMMAND_BLUE)\narcade.start_render()\narcade.draw_rectangle_filled(300, 300, 100, 100, arcade.color.BLUSH)\narcade.draw_point(300, 300, arcade.color.BLUE_SAPPHIRE, 10)\narcade.draw_line(300, 400, 300, 200, arcade.color.BLACK, 2)\narcade.draw_circle_outline(300, 300, 200, arcade.color.WISTERIA, 3)\narcade.draw_circle_filled(300, 300, 3, arcade.color.WISTERIA)\narcade.draw_ellipse_filled(300, 100, 30, 15, arcade.color.AMBER)\npoint_list = ((0, 300),\n (300, 600),\n (600, 300),\n (300, 0))\narcade.draw_polygon_outline(point_list, arcade.color.SPANISH_VIOLET, 3)\npoint_list = ((300, 600),\n (310, 550),\n (290, 550))\narcade.draw_polygon_filled(point_list, arcade.color.SPANISH_VIOLET)\narcade.draw_text(\"never YEET never\", 10, 10, arcade.color.YELLOW, 20)\narcade.finish_render()\narcade.run()","sub_path":"Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"250123307","text":"# python 使用 find 命令搜索目标文件\n\nimport subprocess\n\ndef find(find_dir, filename):\n find_shell = f'find {find_dir} -name {filename} | grep -v target | sort -r'\n response = subprocess.run(\n find_shell, shell=True, capture_output=True, text=True)\n pom_paths = []\n if response.returncode == 0:\n res = response.stdout\n pom_paths = res.strip().split(\"\\n\")\n else:\n print(response.stderr)\n return pom_paths\n","sub_path":"find_file.py","file_name":"find_file.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"477087530","text":"from django.conf.urls import patterns, include, url\nfrom .views import ListarDependencia, RegistrarDependencia, EditarDependencia, BorrarDependencia\nfrom django.contrib.auth.decorators import login_required\n\n\n\"\"\"\n Urls para ingresar a la aplicacion dependencias, permitiendo visualizar los registros, crearlos, editarlos y borrarlos.\n\"\"\"\nurlpatterns = patterns('',\n url(r'^$', login_required(ListarDependencia.as_view(template_name=\"configuracion/dependencia/listar.html\"),\n login_url='/'), name='listar_dependencia'),\n url(r'^registrardependencia/$', login_required(RegistrarDependencia.as_view(template_name=\"configuracion/dependencia/dependencia.html\"),\n login_url='/'), name='registrar_dependencia'),\n url(r'^editardependencia/(?P\\d+)/$', login_required(EditarDependencia.as_view(template_name=\"configuracion/dependencia/modificar.html\"),\n login_url='/'), name='editar_dependencia'),\n url(r'^borrardependencia/(?P\\d+)/$', login_required(BorrarDependencia.as_view(template_name=\"configuracion/dependencia/borrar.html\"),\n login_url='/'), name='borrar_dependencia'),\n )\n","sub_path":"apps/configuracion/dependencias/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"312789972","text":"import csv\nfrom numpy.linalg import norm\nfrom scipy import *\nfrom pylab import plot, show, legend,xlim,ylim,savefig,title,xlabel,ylabel,clf, loglog\nfrom numpy import ones\nimport os\n\n\nwdir = \"../../../../../data/raw/solslopelargerSWWE60s/o2/\"\nsdir = \"../../../../../data/postprocessing/solslopeNN/o2/60s/\"\n\nif not os.path.exists(sdir):\n os.makedirs(sdir)\n\nxbeg = 140\ngap = 1\nxend = 180\ng = 9.81\n \n#time = 0.0995978291745\nfilen = 400*500\n#filen = 1\n\ns = wdir + \"outlast.txt\"\nwith open(s,'r') as file1:\n readfile = csv.reader(file1, delimiter = ',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n \n h = []\n bed = []\n u = []\n he = []\n ue = []\n x = []\n ht = []\n ut = []\n j = -1\n for row in readfile: \n if (j >= 0):\n \n \n dx =float(row[0])\n dt =float(row[1])\n t =float(row[2])\n x.append(float(row[3]))\n h.append(float(row[4]))\n u.append(float(row[5]))\n bed.append(float(row[6]))\n\n \n \n \n j = j + 1\n\nxbegi = int((xbeg - x[0])/dx) \nxendi = int((xend - x[0])/dx) \nh = array(h[xbegi:xendi:gap])\nb = array(bed[xbegi:xendi:gap])\nx = array(x[xbegi:xendi:gap])\nu = array(u[xbegi:xendi:gap])\n\n\nn = len(x)\ns = sdir + \"NSWWstage.dat\"\nwith open(s,'w') as file1:\n for i in range(n):\n s =\"%3.8f%5s%1.15f\\n\" %(x[i] ,\" \",h[i] + b[i])\n file1.write(s)\n \n\"\"\"\ns = sdir + \"h.dat\"\nwith open(s,'w') as file1:\n for i in range(n):\n s =\"%3.8f%5s%1.15f\\n\" %(x[i],\" \",h[i])\n file1.write(s)\ns = sdir + \"u.dat\"\nwith open(s,'w') as file2:\n for i in range(n):\n s =\"%3.8f%5s%1.15f\\n\" %(x[i],\" \",u[i])\n file2.write(s)\n\ns = sdir + \"bed.dat\"\nwith open(s,'w') as file1:\n for i in range(n):\n s =\"%3.8f%5s%1.15f\\n\" %(x[i],\" \",b[i])\n file1.write(s)\n\"\"\" ","sub_path":"CODE/postprocessing/readplot/SimpleFix/SolitonupslopeSWWE.py","file_name":"SolitonupslopeSWWE.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"448611507","text":"import json\nimport requests\nimport argparse\n\nparser = argparse.ArgumentParser(\n description=\"Upload submission from submit.cancergenetrust.org\")\nparser.add_argument('file', nargs='?', default=\"submission.json\",\n help=\"Path to json file to submit\")\nargs = parser.parse_args()\n\nwith open(args.file) as f:\n submission = json.loads(f.read())\nsubmission[\"clinical\"][\"CGT Public ID\"] = submission[\"patientId\"]\n\nr = requests.post(\"http://localhost:5000/v0/submissions?publish=true\",\n files=[(\"files[]\",\n (\"foundationone.json\",\n json.dumps(submission[\"genomic\"], sort_keys=True)))],\n data=submission[\"clinical\"])\nprint(r.text)\nassert(r.status_code == requests.codes.ok)\n","sub_path":"submit.py","file_name":"submit.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"101421104","text":"from django.shortcuts import render,redirect\nfrom blog.models import Posts\nfrom blog.forms import CommentForm,PostForm\n# Create your views here.\ndef index(requests):\n post=Posts.objects.all()\n return render(requests,'blog/frontpage.html',{'posts':post})\n\ndef post_detail(requests,slug):\n post=Posts.objects.get(slug=slug)\n if requests.method=='POST':\n form=CommentForm(requests.POST)\n if form.is_valid():\n comment=form.save(commit=False)\n comment.post=post\n comment.save()\n\n return redirect('post_detail',slug=post.slug)\n else:\n form=CommentForm()\n return render(requests, 'blog/post_detail.html', {'post': post,'form': form})\n\ndef write(request):\n post=Posts.objects.all()\n if request.method == 'POST':\n form = PostForm(request.POST)\n if form.is_valid():\n #blog=form.save(commit=True)\n #blog.save()\n form.save()\n\n else:\n form=PostForm()\n return render(request,\"blog/blog_write.html\",{'post': post,'form': form})","sub_path":"one_text_away/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"205177402","text":"from app.lib.helpers import fetch, uninstall\nfrom app.models.pokemon import Pokemon\nfrom app.models.cache import Cache\nfrom app.models.pokedex import Pokedex\n\nimport click\n\n__cache__ = Cache({\n 'data_name': 'pokedex',\n 'data_class': Pokedex\n})\n\n@click.command()\n@click.option('-s', '--search', type=str, prompt='Pokemon to search', help='The pokemon name or id you are looking for.')\ndef main(search: str):\n pokedex = __cache__.get('pokedex')\n cached_pokemon = pokedex.search(search)\n if cached_pokemon is not None:\n print(cached_pokemon)\n else:\n data = fetch(f'/pokemon/{search}')\n pokemon = Pokemon(data) \n data = fetch(data['location_area_encounters'].split('v2')[1])\n pokemon.locations = Pokemon.kanto(data, pokedex)\n pokedex.index(pokemon)\n __cache__.update()\n print(pokemon)\n\nif __name__ == '__main__':\n main()\n","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"523652632","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2019 BuildGroup Data Services Inc.\n\nimport logging\n\nfrom caravaggio_rest_api.haystack.backends.utils import CaravaggioSearchPaginator\nfrom datetime import datetime\n\nfrom dateutil.parser import parse as date_parse\nfrom davinci_crawling.example.bovespa.api.serializers import BovespaCompanySerializerV1\n\nfrom solrq import Q, Range, ANY, Value\n\nfrom davinci_crawling.example.bovespa import BOVESPA_CRAWLER\nfrom davinci_crawling.example.bovespa.crawling_parts.process_file import process_file\nfrom .models import BovespaCompanyFile, FILE_STATUS_NOT_PROCESSED, FILE_STATUS_ERROR\n\nfrom davinci_crawling.crawler import Crawler\nfrom davinci_crawling.io import put_checkpoint_data, get_checkpoint_data, delete_all\nfrom davinci_crawling.time import mk_datetime\nfrom .crawling_parts.crawl_listed_companies import crawl_listed_companies\nfrom .crawling_parts.crawl_companies_files import crawl_companies_files\nfrom .crawling_parts.download_file import download_file\n\nBOVESPA_FILE_CTL = BOVESPA_CRAWLER\nLAST_EXECUTION_DATE_CTL_FIELD = \"last_execution_date\"\nLAST_UPDATE_COMPANIES_LISTING_CTL_FIELD = \"last_update_companies_listing\"\nLAST_UPDATE_COMPANIES_FILES_CTL_FIELD = \"last_update_companies_files\"\nPROCESSED_COMPANIES_FILES_CTL_FIELD = \"processed_companies_files\"\nCOMPANIES_FILES_WITH_ERRORS_CTL_FIELD = \"companies_files_w_errors\"\n\n_logger = logging.getLogger(\"davinci_crawler_{}\".format(BOVESPA_CRAWLER))\n\n\ndef get_from_date(options, checkpoint_data):\n # Let's decide from which point in time we want to get the new\n # delivered company files\n from_date = options.get(\"last_execution_date\", None)\n\n from_date = checkpoint_data.get(LAST_EXECUTION_DATE_CTL_FIELD, from_date)\n\n # Check if the user is forcing a different date\n if options.get(\"from_date\", None):\n from_date = options.get(\"from_date\")\n\n if isinstance(from_date, str):\n from_date = date_parse(from_date)\n\n # Check if the user is forcing to crawl everything again\n from_the_beginning = options.get(\"from_the_beginning\", False)\n if from_the_beginning:\n from_date = None\n\n _logger.debug(\"From date: {}\".format(\"{0:%Y-%m-%d}\".format(from_date) if from_date else \"BEGINNING\"))\n\n return from_date\n\n\ndef get_to_date(options):\n \"\"\"\n Mounts the to_date if the user specifies it on the options, this will parse\n the date to date format if it is a string.\n Args:\n options: the options object with all the options that the user added\n on command line.\n Returns: the parsed date or None if the date was not specified.\n \"\"\"\n # Check if the user is forcing a to date\n to_date = options.get(\"to_date\", None)\n\n if isinstance(to_date, str):\n to_date = date_parse(to_date)\n\n _logger.debug(\"To date: {}\".format(\"{0:%Y-%m-%d}\".format(to_date) if to_date else \"END\"))\n\n return to_date\n\n\ndef process_listed_companies(options, checkpoint_data, current_execution_date):\n no_update = options.get(\"no_update_companies_listing\", False)\n\n # We do not want to crawl the companies listing\n if no_update:\n return\n\n # Parallel processing - workers\n workers_num = options.get(\"workers_num\", 10)\n\n update_elapsetime = options.get(\"companies_listing_update_elapsetime\", None)\n\n last_update = checkpoint_data.get(LAST_UPDATE_COMPANIES_LISTING_CTL_FIELD, None)\n\n do_crawl = (\n True\n if last_update is None\n or update_elapsetime is None\n or (last_update - current_execution_date).days > update_elapsetime\n else False\n )\n\n if do_crawl:\n crawl_listed_companies(options, workers_num=workers_num)\n\n\ndef get_not_processed_files(options, producer):\n filter = ~Q(file_url=Range(ANY, ANY)) | Q(status=FILE_STATUS_NOT_PROCESSED)\n\n if options.get(\"include_companies\", None):\n filter = Q(ccvm=Value(\"({})\".format(\" \".join(options.get(\"include_companies\", []))), safe=True)) & (filter)\n\n _logger.debug(\"Loading from database the files to be crawled...\")\n paginator = (\n CaravaggioSearchPaginator(query_string=str(filter), limit=1000, max_limit=1000)\n .models(BovespaCompanyFile)\n .select(\"ccvm\", \"doc_type\", \"fiscal_date\", \"version\")\n )\n\n while paginator.has_next():\n _logger.debug(\"{0}/{1} files loaded from database...\".format(paginator.get_loaded_docs(), paginator.get_hits()))\n paginator.next()\n for d in paginator.get_results():\n params = {\"ccvm\": d.ccvm, \"doc_type\": d.doc_type, \"fiscal_date\": d.fiscal_date, \"version\": d.version}\n producer.add_crawl_params(params, options)\n\n # return [file for file in\n # CaravaggioSearchQuerySet().models(BovespaCompanyFile).\n # raw_search(str(filter)).\n # values_list(\"ccvm\", \"doc_type\", \"fiscal_date\", \"version\")]\n\n\ndef process_companies_files(options, checkpoint_data, current_execution_date, from_date, to_date, producer):\n\n no_update = options.get(\"no_update_companies_files\", False)\n\n # We do not want to crawl the companies listing\n if no_update:\n get_not_processed_files(options, producer)\n return\n\n update_elapsetime = options.get(\"companies_files_update_elapsetime\", None)\n\n last_update = checkpoint_data.get(LAST_UPDATE_COMPANIES_FILES_CTL_FIELD, None)\n\n do_crawl = (\n True\n if last_update is None\n or update_elapsetime is None\n or (last_update - current_execution_date).days > update_elapsetime\n else False\n )\n\n if do_crawl:\n # Parallel processing - workers\n workers_num = options.get(\"workers_num\", 10)\n\n # Include companies only\n include_companies = options.get(\"include_companies\", None)\n\n # Get the list of files to be processed\n company_files, company_files_w_errors = crawl_companies_files(\n options,\n producer,\n workers_num=workers_num,\n include_companies=include_companies,\n from_date=from_date,\n to_date=to_date,\n )\n\n # processed_files = []\n # if company_files and len(company_files) > 0:\n # if PROCESSED_COMPANIES_FILES_CTL_FIELD in checkpoint_data:\n # processed_files = checkpoint_data[\n # PROCESSED_COMPANIES_FILES_CTL_FIELD]\n # processed_files.extend(company_files)\n # checkpoint_data[PROCESSED_COMPANIES_FILES_CTL_FIELD] = \\\n # processed_files\n\n files_with_errors = []\n if company_files_w_errors and len(company_files_w_errors) > 0:\n if COMPANIES_FILES_WITH_ERRORS_CTL_FIELD in checkpoint_data:\n files_with_errors = checkpoint_data[COMPANIES_FILES_WITH_ERRORS_CTL_FIELD]\n files_with_errors.extend(company_files_w_errors)\n checkpoint_data[COMPANIES_FILES_WITH_ERRORS_CTL_FIELD] = files_with_errors\n\n # Let's find all the company files without file_url (not downloaded\n # and processed yet) or not processed (status)\n # get_not_processed_files(options, producer)\n\n\nclass BovespaCrawler(Crawler):\n\n __crawler_name__ = BOVESPA_CRAWLER\n\n __serializer_class__ = BovespaCompanySerializerV1\n\n def add_arguments(self, parser):\n # Process files from an specific date\n self._parser.add_argument(\n \"--from-the-beginning\",\n required=False,\n action=\"store_true\",\n dest=\"from_the_beginning\",\n default=None,\n help=\"Crawl all the company files.\"\n \"It is a way to short-circuit the global last/current dates.\"\n \" Ex. '2007-09-03T20:56:35.450686Z\",\n )\n # Process files from an specific date\n self._parser.add_argument(\n \"--from-date\",\n required=False,\n action=\"store\",\n dest=\"from_date\",\n default=None,\n type=mk_datetime,\n help=\"The date from which we want to crawl all the company files.\"\n \"It is a way to short-circuit the global last/current dates.\"\n \" Ex. '2007-09-03T20:56:35.450686Z\",\n )\n # Process files until an specific date\n self._parser.add_argument(\n \"--to-date\",\n required=False,\n action=\"store\",\n dest=\"to_date\",\n default=None,\n type=mk_datetime,\n help=\"The date to which we want to crawl all the company files.\",\n )\n # Crawl only the companies where the name starts with these initials\n self._parser.add_argument(\n \"--crawling-initials\",\n required=False,\n action=\"store\",\n dest=\"crawling_initials\",\n default=None,\n nargs=\"*\",\n help=\"If we want to specify the initial letter of the companies\" \"to crawl (ex A B C)\",\n )\n # Do not update the companies listing from Bovespa\n self._parser.add_argument(\n \"--no-update-companies-listing\",\n required=False,\n action=\"store_true\",\n dest=\"no_update_companies_listing\",\n help=\"If we do not want to update the listed companies crawling\"\n \" the listing from Bovespa. We should update the list once\"\n \" a month\"\n \" Ex. --no-update-companies-listing\",\n )\n # Days between companies listing updates\n self._parser.add_argument(\n \"--companies-listing-update-elapsetime\",\n required=False,\n type=int,\n action=\"store\",\n default=30,\n dest=\"companies_listing_update_elapsetime\",\n help=\"The elapse time in days between updates of the \" \"companies listing\" \" Ex. 30\",\n )\n # Do not update the company files that were already persisted in the\n # database\n self._parser.add_argument(\n \"--no-update-companies-files\",\n required=False,\n action=\"store_true\",\n dest=\"no_update_companies_files\",\n help=\"If we want to update the file contents in the database \"\n \" although the file was already downloaded in the past.\"\n \" Ex. --no-update-companies-files\",\n )\n # Days between companies files updates\n self._parser.add_argument(\n \"--companies-files-update-elapsetime\",\n required=False,\n type=int,\n action=\"store\",\n default=30,\n dest=\"companies_files_update_elapsetime\",\n help=\"The elapse time in days between updates of the \" \"companies files.\" \" Ex. 30\",\n )\n # Do not update the companies listing from Bovespa\n self._parser.add_argument(\n \"--force-download\",\n required=False,\n action=\"store_true\",\n dest=\"force_download\",\n help=\"If we want to force the download of the file from \"\n \" bovespa and update the permanent and local caches.\"\n \" Ex. --force-download\",\n )\n self._parser.add_argument(\n \"--include-companies\",\n action=\"store\",\n nargs=\"*\",\n required=False,\n dest=\"include_companies\",\n help=\"If we want to focus only on a specific companies.\" \"(ex: 35 94 1384\",\n )\n\n def crawl_params(self, producer, **options):\n now = options.get(\"current_execution_date\", datetime.utcnow())\n\n # Check if there is an internal checkpoint, use it instead of the\n # date send by the crawler system\n checkpoint_data = get_checkpoint_data(BOVESPA_CRAWLER, BOVESPA_FILE_CTL, default={})\n from_date = get_from_date(options, checkpoint_data)\n to_date = get_to_date(options)\n\n process_listed_companies(options, checkpoint_data, now)\n\n process_companies_files(options, checkpoint_data, now, from_date, to_date, producer)\n\n # Let's signal that we have processed the latest files (til 'now')\n # To process the new ones the last time we run the process\n put_checkpoint_data(BOVESPA_CRAWLER, BOVESPA_FILE_CTL, checkpoint_data)\n\n def crawl(self, task_id, crawling_params, options):\n _logger.info(\"Processing company file [{}]\".format(crawling_params))\n\n try:\n # Download the files from the source and save them into the local\n # and permanent storage for further processing.\n # It extract the files into a working folder and return the list of\n # files that can be processed\n local_file, working_local_file, files_to_process = download_file(options, **crawling_params)\n\n # Open the files and process the content to generate the\n # BovespaCompanyNumbers with all the financial data of the company\n process_file(options, files_to_process, **crawling_params)\n\n # Remove cached files\n delete_all(options, local_file)\n delete_all(options, working_local_file)\n except Exception:\n _logger.exception(f\"Unable to process crawling task {task_id}\" f\" with params {crawling_params}\")\n\n # Signal the error in the BovespaCompanyFile\n BovespaCompanyFile.objects(**crawling_params).if_exists().update(status=FILE_STATUS_ERROR)\n\n raise\n\n return \"Processing company file [{}]\".format(crawling_params)\n","sub_path":"src/davinci_crawling/example/bovespa/crawlers.py","file_name":"crawlers.py","file_ext":"py","file_size_in_byte":13334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"453993589","text":"#!/usr/bin/env python\n# 从IDE3D_process.py改名为Script_process_wild.py\n# 在92服务器上\n# 使用EG3D和Deep3DFaceRecon_pytorch,处理自制图像,生成相机参数的脚本\n# 把输入图像jpg和png放入--indir中\n# conda activate ide3d-new\n# python /data2/wyf/code/GitTest/ACMMM2023/Script_process_wild.py --indir=/data2/wyf/input/Humanoid/img\n# 生成的dataset.json在/data2/wyf/code/IDE-3D/dataset_preprocessing/ffhq/Deep3DFaceRecon_pytorch/checkpoints/pretrained/results/img/epoch_20_000000中\nimport os\nimport sys\nimport json\nimport argparse\nimport numpy as np\nrun_path = '/data2/wyf/code/IDE-3D/dataset_preprocessing/ffhq'\n# run_path = '/data2/wyf/code/Deep3DFaceRecon_pytorch'\nsys.path.append(run_path)\nrun_flag = True # 是否执行脚本\nGPU = 6\nos.chdir(run_path)\nprint(f'cd {run_path}')\nprint('~~~处理自制图像,生成相机参数的脚本~~~')\nparser = argparse.ArgumentParser()\nparser.add_argument('--indir', type=str, required=True)\nargs = parser.parse_args()\nprint('··········自制图像输入地址为', args.indir)\nout_folder = args.indir.split('/')[-2] if args.indir.endswith('/') else args.indir.split('/')[-1]\nout_folder = 'img' # 这里有点bug,先不管了\nprint('··········自制图像输出地址地址为', out_folder)\nprint('··········第一步,使用MTCNN检测人脸图像5个特征点')\ncommand = f'CUDA_VISIBLE_DEVICES={GPU} python batch_mtcnn.py --in_root ' + args.indir\nprint(command)\nif run_flag:\n os.system(command)\nprint('··········第二步,使用Deep3DFaceRecon_pytorch重建人脸图像')\nos.chdir('Deep3DFaceRecon_pytorch')\nprint('cd Deep3DFaceRecon_pytorch')\ncommand = f'CUDA_VISIBLE_DEVICES={GPU} python test.py --img_folder=' + args.indir + ' --gpu_ids=0 --name=pretrained --epoch=20'\nprint(command)\nif run_flag:\n os.system(command)\nos.chdir('..')\nprint('cd ..')\nprint('··········第三步,转换相机位姿格式')\ncommand = f'CUDA_VISIBLE_DEVICES={GPU} python 3dface2idr_mat.py --in_root {run_path}/Deep3DFaceRecon_pytorch/checkpoints/pretrained/results/' + out_folder + '/epoch_20_000000'\nprint(command)\nif run_flag:\n os.system(command)\nprint('··········第四步,适配当前版本的相机位姿格式')\ncommand = f'CUDA_VISIBLE_DEVICES={GPU} python preprocess_cameras.py --source {run_path}/Deep3DFaceRecon_pytorch/checkpoints/pretrained/results/' + out_folder + '/epoch_20_000000 --mode orig'\nprint(command)\nif run_flag:\n os.system(command)\nprint('··········第五步,裁剪输入图像')\ncommand = f'CUDA_VISIBLE_DEVICES={GPU} python crop_images_in_the_wild.py --indir=' + args.indir\nprint(command)\nif run_flag:\n os.system(command)\nprint('··········第六步,相机位姿json转npy')\ndataset_path = f'{run_path}/Deep3DFaceRecon_pytorch/checkpoints/pretrained/results/' + out_folder + '/epoch_20_000000/dataset.json'\nprint('读取dataset.json在', dataset_path)\nwith open(dataset_path,'r',encoding='utf8') as fp:\n dataset_json = json.load(fp)\nfor i in range(len(dataset_json['labels'])):\n print('读到了', dataset_json['labels'][i][0])\n npy_path = f'{run_path}/Deep3DFaceRecon_pytorch/checkpoints/pretrained/results/' + out_folder + '/epoch_20_000000/' + dataset_json['labels'][i][0][0:-3] + 'npy'\n print('保存在', npy_path)\n np.save(npy_path, dataset_json['labels'][i][1])\ncameras_path = f'{run_path}/Deep3DFaceRecon_pytorch/checkpoints/pretrained/results/' + out_folder + '/epoch_20_000000/cameras.json'\n# print('读取cameras.json在', cameras_path)\n# with open(cameras_path,'r',encoding='utf8') as fp:\n# cameras_json = json.load(fp)\n# print('读到了', cameras_json)\n","sub_path":"ITPortrait/Script_process_wild.py","file_name":"Script_process_wild.py","file_ext":"py","file_size_in_byte":3678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"420943885","text":"from Vector import Vector\n\n# functions for finding the force vector between two points\n\n\n# type: (point, point) -> float\ndef gravity(point_one, point_two):\n g = .0000000000667408\n if (point_one.distance(point_two)) ** 2 == 0 or (point_one.mass == 0 or point_two.mass == 0):\n return Vector((0, 0, 0), 0)\n else:\n mag = (g * point_one.mass * point_two.mass) / (point_one.distance(point_two)) ** 2\n return Vector(point_one.direction(point_two), mag)\n\n\n# add positive and negative charges\ndef electric(point_one, point_two):\n k = 8987551787.3681764\n if (point_one.distance(point_two)) ** 2 == 0 or (point_one.charge == 0 or point_two.charge == 0):\n return Vector((0, 0, 0), 0)\n else:\n mag = (k * point_one.charge * point_two.charge) / (point_one.distance(point_two)) ** 2\n if (point_one.charge > 0 > point_two.charge) or (point_one.charge < 0 < point_two.charge):\n return Vector(point_one.direction(point_two), mag)\n elif (point_one.charge > 0 and point_two.charge > 0) or (point_one.charge < 0 and point_two.charge < 0):\n return Vector(point_one.direction(point_two), -mag)\n else:\n return Vector((0, 0, 0), 0)\n","sub_path":"Force.py","file_name":"Force.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"574716878","text":"import ShareYourSystem as SYS\n\n\n\nLilypondFile=SYS.LilypondFileClass().update(\n\t{\n\t\t'DirString':SYS.sys.modules['os'].getcwd(),\n\t\t'FileString':\"test\",\n\t\t'OutputExtensionString':\".svg\"\n\t})\nLilypondFile[\"LilypondString\"]=\"\\\\version \\\"2.18.2\\\"\\n{c g e g}\"\n\nprint(LilypondFile)","sub_path":"Sites/BaletMasque/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"560906272","text":"from setuptools import setup, find_packages\n\n\n# You can't just put `from pypandoc import convert` at the top of your\n# setup.py and then put `description=convert(\"README.md\", \"rst\")` in\n# your `setup()` invocation, because even if you list list `pypandoc`\n# in `setup_requires`, it won't be interpreted and installed until\n# after the keyword argument values of the `setup()` invocation have\n# been evaluated. Therefore, we define a `lazy_convert` class which\n# impersonates a string but doesn't actually import or use `pypandoc`\n# until the value of the string is needed. This defers the use of\n# `pypandoc` until after setuptools has figured out that it is needed\n# and made it available.\nclass lazy_convert(object):\n def __init__(self, *args, **kwargs):\n self.args = args\n self.kwargs = kwargs\n\n def __str__(self):\n from pypandoc import convert_file\n return str(convert_file(*self.args, **self.kwargs))\n\n def __repr__(self):\n return repr(str(self))\n\n def endswith(self, *args, **kwargs):\n return str(self).endswith(*args, **kwargs)\n\n def split(self, *args, **kwargs):\n return str(self).split(*args, **kwargs)\n\n def replace(self, *args, **kwargs):\n return str(self).replace(*args, **kwargs)\n\n\nsetup(\n name=\"coal_mine\",\n version='0.6.1',\n author='Quantopian Inc.',\n author_email='opensource@quantopian.com',\n description=\"Coal Mine - Periodic task execution monitor\",\n url='https://github.com/quantopian/coal-mine',\n long_description=lazy_convert('README.md', 'rst'),\n license='Apache 2.0',\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: System Administrators',\n 'License :: OSI Approved :: Apache Software License',\n 'Natural Language :: English',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3 :: Only',\n 'Topic :: Internet :: WWW/HTTP :: WSGI :: Server',\n 'Topic :: System :: Monitoring',\n 'Topic :: System :: Systems Administration',\n ],\n packages=find_packages(),\n setup_requires=['pypandoc'],\n python_requires='>=3.2',\n install_requires=open('requirements.txt').read(),\n entry_points={\n 'console_scripts': [\n \"coal-mine = coal_mine.server:main\",\n \"cmcli = coal_mine.cli:main\"\n ]\n },\n zip_safe=True,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"607530544","text":"import board\nimport neopixel\nimport time\nimport math\n\ndef horizontal_scroll(pixels,i,coords,max_dim,gradient):\n\ti = coords[0] + i\n\tif i > max_dim[0]:\n\t\ti = i - max_dim[0]\n\tpx = gradient[0]*(i)\n\tif px > 255:\n\t\tpx = 255\n\tpixels.fill((px, 255-px, 0))\n\ndef vertical_scroll(pixels,i,coords,max_dim,gradient):\n\ti = coords[1] + i\n\tif i > max_dim[1]:\n\t\ti = i - max_dim[1]\n\tpx = gradient[1]*(i)\n\tif px > 255:\n\t\tpx = 255\n\tpixels.fill((px, 255-px, 0))\n\n\t\n\n\n","sub_path":"HWGroup/pixelPi/routines.py","file_name":"routines.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"141824944","text":"from lib.graph import create_min_tree\n\n\ndef get_depth(node):\n depth = 0\n while node is not None:\n node = node.parent\n depth += 1\n return depth\n\n\ndef go_up(node, delta):\n while delta > 0 and node is not None:\n node = node.parent\n delta -= 1\n return node\n\n\ndef common_ancestor(n1, n2):\n delta = get_depth(n1) - get_depth(n2)\n if delta < 0:\n shallower = n1\n deeper = n2\n deeper = go_up(deeper, abs(delta))\n elif delta > 0:\n shallower = n2\n deeper = n1\n deeper = go_up(deeper, abs(delta))\n else:\n shallower = n1\n deeper = n2\n\n while shallower != deeper and shallower is not None and deeper is not None:\n shallower = shallower.parent\n deeper = deeper.parent\n\n return None if None in (shallower, deeper) else shallower\n\n\nif __name__ == '__main__':\n root = create_min_tree([i for i in range(1, 10)])\n p = root.left.left\n q = root.left.right.right\n print(common_ancestor(p, q))\n","sub_path":"chapter_4/8_first_common_ancestor/with_links_to_parents.py","file_name":"with_links_to_parents.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"107425696","text":"\r\n# IMPORT EXTERNAL LIBRARIES\r\nimport os\r\nimport tensorflow as tf\r\nimport numpy as np\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\nfrom time import sleep\r\nfrom random import randint\r\nimport random\r\nimport pickle\r\n\r\n#### ADD #####\r\n# IMPORT AGENT LIB\r\nfrom MLWatcher.agent import MonitoringAgent\r\n\r\nWORKING_DIR = os.path.dirname(os.path.abspath(__file__))\r\nMODEL_DIR = os.path.join(WORKING_DIR, \"MODEL_MULTICLASS\")\r\nMODEL_W_DIR = os.path.join(WORKING_DIR, \"MODEL_MULTICLASS_WRONG\")\r\n\r\nif not os.path.exists(MODEL_DIR):\r\n os.mkdir(MODEL_DIR)\r\n\r\nif not os.path.exists(MODEL_W_DIR):\r\n os.mkdir(MODEL_W_DIR)\r\n\r\n##EDITABLE##\r\nTRAIN_PHASE = True\r\nWRONG_TRAIN = False\r\n##END EDITABLE##\r\n\r\nTRAIN_BATCH_SIZE = 128\r\nNUM_CLASSES = 10\r\nNUM_FEATURES = 784\r\nLEARNING_RATE = 1e-3\r\n\r\nTEST_BATCH_SIZE = 15\r\n\r\n\r\ndef weight_variable(shape, name):\r\n initial = tf.truncated_normal(shape, stddev=0.01)\r\n return tf.Variable(initial, name=name)\r\n\r\n\r\ndef bias_variable(shape, name):\r\n initial = tf.constant(0.0, shape=shape)\r\n return tf.Variable(initial, name=name)\r\n\r\n\r\ndef calculate_model(wrong_model=False):\r\n\r\n # Download the dataset\r\n mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\r\n\r\n # Define placeholders\r\n\r\n # correct labels\r\n y_ = tf.placeholder(tf.float32, shape=(None, NUM_CLASSES), name='y_')\r\n # input data\r\n x = tf.placeholder(tf.float32, shape=(None, NUM_FEATURES), name='x')\r\n\r\n # Build the net\r\n\r\n hidden_size1 = 500\r\n hidden_size2 = 100\r\n\r\n W_fc1 = weight_variable((NUM_FEATURES, hidden_size1), name='W_fct1')\r\n b_fc1 = bias_variable((1, hidden_size1), name='b_fct1')\r\n h_fc1 = tf.nn.relu(tf.matmul(x, W_fc1) + b_fc1)\r\n\r\n W_fc2 = weight_variable((hidden_size1, hidden_size2), name='W_fct2')\r\n b_fc2 = bias_variable((1, hidden_size2), name='b_fct2')\r\n h_fc2 = tf.nn.relu(tf.matmul(h_fc1, W_fc2) + b_fc2)\r\n\r\n W_fc3 = weight_variable((hidden_size2, NUM_CLASSES), name='W_fct3')\r\n b_fc3 = bias_variable((1, NUM_CLASSES), name='b_fct3')\r\n\r\n y = tf.nn.softmax(tf.matmul(h_fc2, W_fc3) + b_fc3, name='OP_TO_RESTORE')\r\n\r\n # define the loss function\r\n y_log = tf.log(y)\r\n cross_entropy = tf.reduce_sum(-1 * y_log * y_)\r\n\r\n # define Optimizer\r\n Optimizer = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(cross_entropy)\r\n\r\n correct_prediction = tf.equal(tf.argmax(y, axis=1), tf.argmax(y_, axis=1))\r\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, dtype=tf.float32))\r\n init = tf.global_variables_initializer()\r\n\r\n # Add ops to save and restore all the variables.\r\n saver = tf.train.Saver()\r\n\r\n with tf.Session() as sess:\r\n sess.run(init)\r\n for i in range(2500):\r\n input_images, correct_predictions = mnist.train.next_batch(TRAIN_BATCH_SIZE)\r\n input_images_test, correct_predictions_test = mnist.test.next_batch(TRAIN_BATCH_SIZE)\r\n\r\n if wrong_model == False:\r\n sess.run(Optimizer, feed_dict={x: input_images, y_: correct_predictions})\r\n else:\r\n # Train the 'wrong' model on altered images\r\n input_images_test_altered, correct_predictions_altered = modify_test_set(input_images,\r\n correct_predictions,\r\n modification='do_unbalanced_data',\r\n batch_size=TRAIN_BATCH_SIZE)\r\n sess.run(Optimizer, feed_dict={x: input_images_test_altered, y_: correct_predictions_altered})\r\n\r\n if i % 128 == 0:\r\n train_accuracy = sess.run(accuracy, feed_dict={x: input_images, y_: correct_predictions})\r\n print(\"step {}, training accuracy {}\".format(i, train_accuracy))\r\n test_accuracy = sess.run([accuracy], feed_dict={x: input_images_test, y_: correct_predictions_test})\r\n print(\"Validation accuracy: {}.\".format(test_accuracy))\r\n\r\n if wrong_model == False:\r\n saver.save(sess, MODEL_DIR+'/my_test_model_multiclass')\r\n else:\r\n saver.save(sess, MODEL_W_DIR + '/my_test_model_multiclass')\r\n\r\n\r\ndef modify_test_set(input_set, label_set, modification='brutally_inverse_pixels', batch_size=TEST_BATCH_SIZE):\r\n if modification == 'brutally_inverse_pixels':\r\n input_set_modified = np.array([1 - x for x in input_set])\r\n if modification == 'divide_brightness':\r\n input_set_modified = np.array([x * 0.50 for x in input_set])\r\n if modification == 'none':\r\n input_set_modified = input_set\r\n if modification == 'do_unbalanced_data':\r\n if random.random() >= 0.05:\r\n input_set_modified = input_set[np.array([np.argmax(x) not in [0, 2, 4, 6, 8] for x in label_set], dtype=bool), :]\r\n label_set_modified = label_set[np.array([np.argmax(x) not in [0, 2, 4, 6, 8] for x in label_set], dtype=bool), :]\r\n return input_set_modified, label_set_modified\r\n else:\r\n input_set_modified = input_set[np.array([np.argmax(x) not in [1, 3, 5, 7, 9] for x in label_set], dtype=bool), :]\r\n label_set_modified = label_set[np.array([np.argmax(x) not in [1, 3, 5, 7, 9] for x in label_set], dtype=bool), :]\r\n return input_set_modified, label_set_modified\r\n if modification == 'remove_high_greys':\r\n thresh = 0.9\r\n input_set_modified = np.array([[pixel if pixel < thresh else 0 for pixel in x] for x in input_set])\r\n if modification == '4_corner_black':\r\n n = 5\r\n input_set = np.copy(input_set)\r\n input_set_reshaped = np.reshape(input_set, (batch_size, 28, 28))\r\n input_set_reshaped[:, :n, :n] = 0\r\n input_set_reshaped[:, 28 - n:, :n] = 0\r\n input_set_reshaped[:, :n, 28 - n:] = 0\r\n input_set_reshaped[:, 28 - n:, 28 - n:] = 0\r\n input_set_modified = np.reshape(input_set_reshaped, (batch_size, 28 * 28))\r\n if modification == 'center_black':\r\n input_set = np.copy(input_set)\r\n input_set_reshaped = np.reshape(input_set, (batch_size, 28, 28))\r\n input_set_reshaped[:, 12:17, 12:17] = 0\r\n input_set_modified = np.reshape(input_set_reshaped, (batch_size, 28 * 28))\r\n if modification == 'translate':\r\n input_set = np.copy(input_set)\r\n input_set_reshaped = np.reshape(input_set, (batch_size, 28, 28))\r\n input_set_reshaped[:, 4:, :] = input_set_reshaped[:, :24, :]\r\n input_set_reshaped[:, :4, :] = 0\r\n input_set_modified = np.reshape(input_set_reshaped, (batch_size, 28 * 28))\r\n\r\n return input_set_modified\r\n\r\n\r\ndef do_predictions():\r\n\r\n # Load the dataset\r\n mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\r\n\r\n # Load the previously saved model and graph in sess\r\n sess = tf.Session()\r\n sess_W = tf.Session()\r\n # Let's load meta graph and restore input var x\r\n saver = tf.train.import_meta_graph(MODEL_DIR+'/my_test_model_multiclass.meta')\r\n saver_W = tf.train.import_meta_graph(MODEL_W_DIR+'/my_test_model_multiclass.meta')\r\n saver.restore(sess, tf.train.latest_checkpoint(MODEL_DIR))\r\n saver_W.restore(sess_W, tf.train.latest_checkpoint(MODEL_W_DIR))\r\n graph = tf.get_default_graph()\r\n x = graph.get_tensor_by_name(\"x:0\")\r\n\r\n # Predict batches of data\r\n ##EDITABLE##\r\n I = 50\r\n J = 60\r\n STOP = 60\r\n agent = MonitoringAgent(frequency=1, max_buffer_size=100, n_classes=10, agent_id='MNIST_Multiclass', server_IP='127.0.0.1', server_port=8000)\r\n #agent = MonitoringAgent(frequency=1, max_buffer_size=100, agent_id='MNIST_Multiclass_wrong_inputs', server_IP='127.0.0.1', server_port=8000)\r\n #agent = MonitoringAgent(frequency=1, max_buffer_size=100, agent_id='MNIST_Multiclass_wrong_model', server_IP='127.0.0.1', server_port=8000)\r\n agent.run_local_server(n_sockets=5)\r\n ##END EDITABLE##\r\n\r\n while True:\r\n for i in range(STOP):\r\n batch_size = randint(1, 20)\r\n input_images_test, correct_predictions_test = mnist.test.next_batch(batch_size)\r\n input_images_test_altered = modify_test_set(input_images_test, correct_predictions_test, modification='none', batch_size=batch_size)\r\n #input_images_test_altered = modify_test_set(input_images_test, correct_predictions_test, modification='brutally_inverse_pixels', batch_size=batch_size)\r\n # input_images_test_altered = modify_test_set(input_images_test, correct_predictions_test, modification='divide_brightness', batch_size=batch_size)\r\n # input_images_test_altered, correct_predictions_test = modify_test_set(input_images_test, correct_predictions_test, modification='do_unbalanced_data', batch_size=batch_size)\r\n # input_images_test_altered = modify_test_set(input_images_test, correct_predictions_test, modification='remove_high_greys', batch_size=batch_size)\r\n # input_images_test_altered = modify_test_set(input_images_test, correct_predictions_test, modification='4_corner_black', batch_size=batch_size)\r\n # input_images_test_altered = modify_test_set(input_images_test, correct_predictions_test, modification='center_black', batch_size=batch_size)\r\n # input_images_test_altered = modify_test_set(input_images_test, correct_predictions_test, modification='translate', batch_size=batch_size)\r\n\r\n if i >= I and i <= J and not WRONG_TRAIN:\r\n input_images_test = input_images_test_altered\r\n\r\n # result of the softmax : predict_proba matrix of size (batch_size, num_classes)\r\n if i >= I and i <= J and WRONG_TRAIN:\r\n output_proba = sess_W.run('OP_TO_RESTORE:0', feed_dict={x: input_images_test})\r\n else:\r\n output_proba = sess.run('OP_TO_RESTORE:0', feed_dict={x: input_images_test})\r\n\r\n\r\n ##HERE IS THE HOOK\r\n agent.collect_data(predict_proba_matrix=output_proba, input_matrix=input_images_test, label_matrix=correct_predictions_test)\r\n #agent.collect_data(predict_proba_matrix=output_proba, label_matrix=correct_predictions_test)\r\n #agent.collect_data(predict_proba_matrix=output_proba, input_matrix=input_images_test)\r\n #agent.collect_data(predict_proba_matrix=output_proba)\r\n\r\n sleep_time = randint(1, 10)\r\n sleep(sleep_time)\r\n\r\n\r\ndef main():\r\n if TRAIN_PHASE:\r\n calculate_model(wrong_model=WRONG_TRAIN)\r\n else:\r\n do_predictions()\r\n\r\ndef save_pickle(result, pickle_name):\r\n \"\"\"Saves an object in pickle object file for future use\"\"\"\r\n with open(os.path.join(WORKING_DIR, pickle_name), 'wb') as file:\r\n pickle.dump(result, file)\r\n return True\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # execute only if run as a script\r\n main()\r\n","sub_path":"EXAMPLE/MNIST_example_TRAIN.py","file_name":"MNIST_example_TRAIN.py","file_ext":"py","file_size_in_byte":10820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"176293309","text":"import os, time, glob\n\ndef sort_data():\n numFiles = len([name for name in os.listdir('../VOC/')])\n done = 0\n \n with open('../data/cat.txt','r') as f:\n for line in f:\n name_label = line.split()\n imagefile = name_label[0] + '.jpg'\n label = name_label[1]\n \n if os.path.isfile('../VOC/' + imagefile): \n if label == '1':\n os.rename('../VOC/' + imagefile, \"../VOC_POSITIVES/\" + imagefile)\n elif label == '-1':\n os.rename('../VOC/' + imagefile, \"../VOC_NEGATIVES/\" + imagefile)\n \n if get_time() % 100 == 0:\n print('processed...' + str(done) + ' of ' + str(numFiles))\n \n done += 1\n \ndef count_negatives():\n print(len([name for name in os.listdir('../VOC_NEGATIVES/')]))\n \ndef count_cat_data():\n print(len([name for name in glob.glob('../CAT_DATASET/*.jpg')]))\n \ndef get_time():\n return int(round(time.time() * 1000))\n\ncount_cat_data()\n","sub_path":"sort_voc_data.py","file_name":"sort_voc_data.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"561980750","text":"import json\nimport os\nimport random\nimport unittest\nfrom datetime import datetime\ntry:\n from unittest import mock\nexcept ImportError:\n import mock\n\nfrom six import PY2\nimport pandas as pd\nimport re\n\nimport great_expectations as ge\nfrom great_expectations.dataset import PandasDataset, MetaPandasDataset\nfrom great_expectations.data_asset.data_asset import (\n _calc_validation_statistics,\n ValidationStatistics,\n)\nfrom .test_utils import assertDeepAlmostEqual\n\n\ndef isprime(n):\n # https://stackoverflow.com/questions/18833759/python-prime-number-checker\n '''check if integer n is a prime'''\n\n # make sure n is a positive integer\n n = abs(int(n))\n\n # 0 and 1 are not primes\n if n < 2:\n return False\n\n # 2 is the only even prime number\n if n == 2:\n return True\n\n # all other even numbers are not primes\n if not n & 1:\n return False\n\n # range starts with 3 and only needs to go up\n # the square root of n for all odd numbers\n for x in range(3, int(n**0.5) + 1, 2):\n if n % x == 0:\n return False\n\n return True\n\n\nclass CustomPandasDataset(PandasDataset):\n\n @MetaPandasDataset.column_map_expectation\n def expect_column_values_to_be_prime(self, column):\n return column.map(isprime)\n\n @MetaPandasDataset.expectation([\"column\", \"mostly\"])\n def expect_column_values_to_equal_1(self, column, mostly=None):\n not_null = self[column].notnull()\n\n result = self[column][not_null] == 1\n unexpected_values = list(self[column][not_null][result == False])\n\n if mostly:\n # Prevent division-by-zero errors\n if len(not_null) == 0:\n return {\n 'success': True,\n 'result': {\n 'unexpected_list': unexpected_values,\n 'unexpected_index_list': self.index[result],\n }\n }\n\n percent_equaling_1 = float(sum(result))/len(not_null)\n return {\n \"success\": percent_equaling_1 >= mostly,\n 'result': {\n \"unexpected_list\": unexpected_values[:20],\n \"unexpected_index_list\": list(self.index[result == False])[:20],\n }\n }\n else:\n return {\n \"success\": len(unexpected_values) == 0,\n 'result': {\n \"unexpected_list\": unexpected_values[:20],\n \"unexpected_index_list\": list(self.index[result == False])[:20],\n }\n }\n\n\nclass TestCustomClass(unittest.TestCase):\n\n def test_custom_class(self):\n script_path = os.path.dirname(os.path.realpath(__file__))\n df = ge.read_csv(\n script_path+'/test_sets/Titanic.csv',\n dataset_class=CustomPandasDataset\n )\n df.set_default_expectation_argument(\"result_format\", \"COMPLETE\")\n self.assertEqual(\n df.expect_column_values_to_be_prime(\n 'Age')['result']['unexpected_list'],\n [30.0, 25.0, 0.92000000000000004, 63.0, 39.0, 58.0, 50.0, 24.0, 36.0, 26.0, 25.0, 25.0, 28.0, 45.0, 39.0,\n 30.0, 58.0, 45.0, 22.0, 48.0, 44.0, 60.0, 45.0, 58.0, 36.0, 33.0, 36.0, 36.0, 14.0, 49.0, 36.0, 46.0, 27.0,\n 27.0, 26.0, 64.0, 39.0, 55.0, 70.0, 69.0, 36.0, 39.0, 38.0, 27.0, 27.0, 4.0, 27.0, 50.0, 48.0, 49.0, 48.0,\n 39.0, 36.0, 30.0, 24.0, 28.0, 64.0, 60.0, 49.0, 44.0, 22.0, 60.0, 48.0, 35.0, 22.0, 45.0, 49.0, 54.0, 38.0,\n 58.0, 45.0, 46.0, 25.0, 21.0, 48.0, 49.0, 45.0, 36.0, 55.0, 52.0, 24.0, 16.0, 44.0, 51.0, 42.0, 35.0, 35.0,\n 38.0, 35.0, 50.0, 49.0, 46.0, 58.0, 42.0, 40.0, 42.0, 55.0, 50.0, 16.0, 21.0, 30.0, 15.0, 30.0, 46.0, 54.0,\n 36.0, 28.0, 65.0, 33.0, 44.0, 55.0, 36.0, 58.0, 64.0, 64.0, 22.0, 28.0, 22.0, 18.0, 52.0, 46.0, 56.0, 33.0,\n 27.0, 55.0, 54.0, 48.0, 18.0, 21.0, 34.0, 40.0, 36.0, 50.0, 39.0, 56.0, 28.0, 56.0, 56.0, 24.0, 18.0, 24.0,\n 45.0, 40.0, 6.0, 57.0, 32.0, 62.0, 54.0, 52.0, 62.0, 63.0, 46.0, 52.0, 39.0, 18.0, 48.0, 49.0, 39.0, 46.0,\n 64.0, 60.0, 60.0, 55.0, 54.0, 21.0, 57.0, 45.0, 50.0, 50.0, 27.0, 20.0, 51.0, 21.0, 36.0, 40.0, 32.0, 33.0,\n 30.0, 28.0, 18.0, 34.0, 32.0, 57.0, 18.0, 36.0, 28.0, 51.0, 32.0, 28.0, 36.0, 4.0, 1.0, 12.0, 34.0, 26.0,\n 27.0, 15.0, 45.0, 40.0, 20.0, 25.0, 36.0, 25.0, 42.0, 26.0, 26.0, 0.82999999999999996, 54.0, 44.0, 52.0,\n 30.0, 30.0, 27.0, 24.0, 35.0, 8.0, 22.0, 30.0, 20.0, 21.0, 49.0, 8.0, 28.0, 18.0, 28.0, 22.0, 25.0, 18.0,\n 32.0, 18.0, 42.0, 34.0, 8.0, 21.0, 38.0, 38.0, 35.0, 35.0, 38.0, 24.0, 16.0, 26.0, 45.0, 24.0, 21.0, 22.0,\n 34.0, 30.0, 50.0, 30.0, 1.0, 44.0, 28.0, 6.0, 30.0, 45.0, 24.0, 24.0, 49.0, 48.0, 34.0, 32.0, 21.0, 18.0,\n 21.0, 52.0, 42.0, 36.0, 21.0, 33.0, 34.0, 22.0, 45.0, 30.0, 26.0, 34.0, 26.0, 22.0, 1.0, 25.0, 48.0, 57.0,\n 27.0, 30.0, 20.0, 45.0, 46.0, 30.0, 48.0, 54.0, 64.0, 32.0, 18.0, 32.0, 26.0, 20.0, 39.0, 22.0, 24.0, 28.0,\n 50.0, 20.0, 40.0, 42.0, 21.0, 32.0, 34.0, 33.0, 8.0, 36.0, 34.0, 30.0, 28.0, 0.80000000000000004, 25.0,\n 50.0, 21.0, 25.0, 18.0, 20.0, 30.0, 30.0, 35.0, 22.0, 25.0, 25.0, 14.0, 50.0, 22.0, 27.0, 27.0, 30.0, 22.0,\n 35.0, 30.0, 28.0, 12.0, 40.0, 36.0, 28.0, 32.0, 4.0, 36.0, 33.0, 32.0, 26.0, 30.0, 24.0, 18.0, 42.0, 16.0,\n 35.0, 16.0, 25.0, 18.0, 20.0, 30.0, 26.0, 40.0, 24.0, 18.0, 0.82999999999999996, 20.0, 25.0, 35.0, 32.0,\n 20.0, 39.0, 39.0, 6.0, 38.0, 9.0, 26.0, 4.0, 20.0, 26.0, 25.0, 18.0, 24.0, 35.0, 40.0, 38.0, 9.0, 45.0,\n 27.0, 20.0, 32.0, 33.0, 18.0, 40.0, 26.0, 15.0, 45.0, 18.0, 27.0, 22.0, 26.0, 22.0, 20.0, 32.0, 21.0, 18.0,\n 26.0, 6.0, 9.0, 40.0, 32.0, 26.0, 18.0, 20.0, 22.0, 22.0, 35.0, 21.0, 20.0, 18.0, 18.0, 38.0, 30.0, 21.0,\n 21.0, 21.0, 24.0, 33.0, 33.0, 28.0, 16.0, 28.0, 24.0, 21.0, 32.0, 26.0, 18.0, 20.0, 24.0, 24.0, 36.0, 30.0,\n 22.0, 35.0, 27.0, 30.0, 36.0, 9.0, 44.0, 45.0, 22.0, 30.0, 34.0, 28.0, 0.33000000000000002, 27.0, 25.0,\n 24.0, 22.0, 21.0, 26.0, 33.0, 1.0, 0.17000000000000001, 25.0, 36.0, 36.0, 30.0, 26.0, 65.0, 42.0, 32.0,\n 30.0, 24.0, 24.0, 24.0, 22.0, 18.0, 16.0, 45.0, 21.0, 18.0, 9.0, 48.0, 16.0, 25.0, 38.0, 22.0, 16.0, 33.0,\n 9.0, 38.0, 40.0, 14.0, 16.0, 9.0, 10.0, 6.0, 40.0, 32.0, 20.0, 28.0, 24.0, 28.0, 24.0, 20.0, 45.0, 26.0,\n 21.0, 27.0, 18.0, 26.0, 22.0, 28.0, 22.0, 27.0, 42.0, 27.0, 25.0, 27.0, 20.0, 48.0, 34.0, 22.0, 33.0, 32.0,\n 26.0, 49.0, 1.0, 33.0, 4.0, 24.0, 32.0, 27.0, 21.0, 32.0, 20.0, 21.0, 30.0, 21.0, 22.0, 4.0, 39.0, 20.0,\n 21.0, 44.0, 42.0, 21.0, 24.0, 25.0, 22.0, 22.0, 39.0, 26.0, 4.0, 22.0, 26.0, 1.5, 36.0, 18.0, 25.0, 22.0,\n 20.0, 26.0, 22.0, 32.0, 21.0, 21.0, 36.0, 39.0, 25.0, 45.0, 36.0, 30.0, 20.0, 21.0, 1.5, 25.0, 18.0, 63.0,\n 18.0, 15.0, 28.0, 36.0, 28.0, 10.0, 36.0, 30.0, 22.0, 14.0, 22.0, 51.0, 18.0, 45.0, 28.0, 21.0, 27.0, 36.0,\n 27.0, 15.0, 27.0, 26.0, 22.0, 24.0]\n )\n\n primes = [3, 5, 7, 11, 13, 17, 23, 31]\n df[\"primes\"] = df.Age.map(lambda x: random.choice(primes))\n self.assertEqual(\n df.expect_column_values_to_be_prime(\n \"primes\")['result']['unexpected_list'],\n []\n )\n\n def test_custom_expectation(self):\n df = CustomPandasDataset({'x': [1, 1, 1, 1, 2]})\n df.set_default_expectation_argument(\"result_format\", \"COMPLETE\")\n\n out = df.expect_column_values_to_be_prime('x')\n t = {'out': {'unexpected_list': [1, 1, 1, 1], 'unexpected_index_list': [\n 0, 1, 2, 3], 'success': False}}\n self.assertEqual(t['out']['success'], out['success'])\n if 'unexpected_index_list' in t['out']:\n self.assertEqual(t['out']['unexpected_index_list'],\n out['result']['unexpected_index_list'])\n if 'unexpected_list' in t['out']:\n self.assertEqual(t['out']['unexpected_list'],\n out['result']['unexpected_list'])\n\n out = df.expect_column_values_to_equal_1('x', mostly=.8)\n print(out)\n t = {'out': {'unexpected_list': [\n 2], 'unexpected_index_list': [4], 'success': True}}\n self.assertEqual(t['out']['success'], out['success'])\n if 'unexpected_index_list' in t['out']:\n self.assertEqual(t['out']['unexpected_index_list'],\n out['result']['unexpected_index_list'])\n if 'unexpected_list' in t['out']:\n self.assertEqual(t['out']['unexpected_list'],\n out['result']['unexpected_list'])\n\n # Ensure that Custom Data Set classes can properly call non-overridden methods from their parent class\n def test_base_class_expectation(self):\n df = CustomPandasDataset({\n \"aaa\": [1, 2, 3, 4, 5],\n \"bbb\": [10, 20, 30, 40, 50],\n \"ccc\": [9, 10, 11, 12, 13],\n })\n\n self.assertEqual(\n df.expect_column_values_to_be_between(\n \"aaa\", min_value=1, max_value=5)['success'],\n True\n )\n\n\nclass TestValidation(unittest.TestCase):\n def test_validate(self):\n\n with open(\"./tests/test_sets/titanic_expectations.json\") as f:\n my_expectation_suite = json.load(f)\n\n my_df = ge.read_csv(\n \"./tests/test_sets/Titanic.csv\",\n expectation_suite=my_expectation_suite\n )\n my_df.set_default_expectation_argument(\"result_format\", \"COMPLETE\")\n\n with mock.patch(\"datetime.datetime\") as mock_datetime:\n mock_datetime.utcnow.return_value = datetime(1955, 11, 5)\n results = my_df.validate(catch_exceptions=False)\n\n with open('./tests/test_sets/titanic_expected_data_asset_validate_results.json') as f:\n expected_results = json.load(f)\n\n del results[\"meta\"][\"great_expectations.__version__\"]\n self.maxDiff = None\n\n # order is not guaranteed (or important in this case) but sorting is possible in PY2\n if PY2:\n results[\"results\"] = sorted(results[\"results\"])\n expected_results[\"results\"] = sorted(expected_results[\"results\"])\n\n assertDeepAlmostEqual(\n results,\n expected_results\n )\n\n # Now, change the results and ensure they are no longer equal\n results[0] = {}\n self.assertNotEqual(results,\n expected_results\n )\n\n # Finally, confirm that only_return_failures works\n # and does not affect the \"statistics\" field.\n with mock.patch(\"datetime.datetime\") as mock_datetime:\n mock_datetime.utcnow.return_value = datetime(1955, 11, 5)\n validation_results = my_df.validate(only_return_failures=True)\n del validation_results[\"meta\"][\"great_expectations.__version__\"]\n assertDeepAlmostEqual(\n validation_results,\n {\n \"meta\": {\n \"data_asset_name\": None,\n \"expectation_suite_name\": \"default\",\n \"run_id\": \"1955-11-05T000000Z\"\n },\n \"results\": [\n {\"expectation_config\": {\n \"expectation_type\": \"expect_column_values_to_be_in_set\",\n \"kwargs\": {\"column\": \"PClass\", \"value_set\": [\"1st\", \"2nd\", \"3rd\"]}\n },\n \"success\": False,\n \"exception_info\": {\"exception_message\": None,\n \"exception_traceback\": None,\n \"raised_exception\": False},\n \"result\": {\"partial_unexpected_index_list\": [456], \"unexpected_count\": 1, \"unexpected_list\": [\"*\"],\n \"unexpected_percent\": 0.07616146230007616, \"element_count\": 1313,\n \"missing_percent\": 0.0, \"partial_unexpected_counts\": [{\"count\": 1, \"value\": \"*\"}],\n \"partial_unexpected_list\": [\"*\"],\n \"unexpected_percent_nonmissing\": 0.07616146230007616, \"missing_count\": 0,\n \"unexpected_index_list\": [456]}}\n ],\n \"success\": expected_results[\"success\"], # unaffected\n \"statistics\": expected_results[\"statistics\"], # unaffected\n }\n )\n\n def test_validate_catch_non_existent_expectation(self):\n df = ge.dataset.PandasDataset({\n \"x\": [1, 2, 3, 4, 5]\n })\n\n validation_config_non_existent_expectation = {\n \"data_asset_name\": None,\n \"expectation_suite_name\": \"default\",\n \"meta\": {\n \"great_expectations.__version__\": ge.__version__\n },\n \"expectations\": [{\n \"expectation_type\": \"non_existent_expectation\",\n \"kwargs\": {\n \"column\": \"x\"\n }\n }]\n }\n results = df.validate(\n expectation_suite=validation_config_non_existent_expectation)['results']\n\n self.assertIn(\n \"object has no attribute 'non_existent_expectation'\",\n results[0]['exception_info']['exception_message']\n )\n\n def test_validate_catch_invalid_parameter(self):\n df = ge.dataset.PandasDataset({\n \"x\": [1, 2, 3, 4, 5]\n })\n\n validation_config_invalid_parameter = {\n \"data_asset_name\": None,\n \"expectation_suite_name\": \"default\",\n \"meta\": {\n \"great_expectations.__version__\": ge.__version__\n },\n \"expectations\": [{\n \"expectation_type\": \"expect_column_values_to_be_between\",\n \"kwargs\": {\n \"column\": \"x\",\n \"min_value\": 6,\n \"max_value\": 5\n }\n }]\n }\n\n results = df.validate(expectation_suite=validation_config_invalid_parameter)[\n 'results']\n print(results[0]['exception_info'])\n self.assertIn(\n \"min_value cannot be greater than max_value\",\n results[0]['exception_info']['exception_message']\n )\n\nclass TestValidationStatisticsCalculation(unittest.TestCase):\n def test_no_expectations(self):\n expectation_results = []\n actual = _calc_validation_statistics(expectation_results)\n\n # pay attention to these two\n self.assertEqual(actual.success_percent, None)\n self.assertEqual(actual.success, True)\n # the rest is boring\n self.assertEqual(actual.successful_expectations, 0)\n self.assertEqual(actual.evaluated_expectations, 0)\n self.assertEqual(actual.unsuccessful_expectations, 0)\n\n def test_no_succesful_expectations(self):\n expectation_results = [\n {\"success\": False},\n ]\n actual = _calc_validation_statistics(expectation_results)\n expected = ValidationStatistics(1, 0, 1, 0., False)\n assertDeepAlmostEqual(actual, expected)\n\n expectation_results = [\n {\"success\": False},\n {\"success\": False},\n {\"success\": False},\n ]\n actual = _calc_validation_statistics(expectation_results)\n expected = ValidationStatistics(3, 0, 3, 0., False)\n assertDeepAlmostEqual(actual, expected)\n\n def test_all_succesful_expectations(self):\n expectation_results = [\n {\"success\": True},\n ]\n actual = _calc_validation_statistics(expectation_results)\n expected = ValidationStatistics(1, 1, 0, 100.0, True)\n assertDeepAlmostEqual(actual, expected)\n\n expectation_results = [\n {\"success\": True},\n {\"success\": True},\n {\"success\": True},\n ]\n actual = _calc_validation_statistics(expectation_results)\n expected = ValidationStatistics(3, 3, 0, 100.0, True)\n assertDeepAlmostEqual(actual, expected)\n\n def test_mixed_expectations(self):\n expectation_results = [\n {\"success\": False},\n {\"success\": True},\n ]\n actual = _calc_validation_statistics(expectation_results)\n expected = ValidationStatistics(2, 1, 1, 50.0, False)\n assertDeepAlmostEqual(actual, expected)\n\n\nclass TestRepeatedAppendExpectation(unittest.TestCase):\n def test_validate(self):\n\n with open(\"./tests/test_sets/titanic_expectations.json\") as f:\n my_expectation_suite = json.load(f)\n\n my_df = ge.read_csv(\"./tests/test_sets/Titanic.csv\",\n profiler=ge.profile.ColumnsExistProfiler)\n\n self.assertEqual(\n len(my_df.get_expectation_suite()['expectations']),\n 7\n )\n\n # For column_expectations, _append_expectation should only replace expectations where the expetation_type AND the column match\n my_df.expect_column_to_exist(\"PClass\")\n self.assertEqual(\n len(my_df.get_expectation_suite()['expectations']),\n 7\n )\n\n\nclass TestIO(unittest.TestCase):\n\n def test_read_csv(self):\n script_path = os.path.dirname(os.path.realpath(__file__))\n df = ge.read_csv(\n script_path+'/test_sets/Titanic.csv',\n )\n\n def test_read_json(self):\n script_path = os.path.dirname(os.path.realpath(__file__))\n df = ge.read_json(\n script_path+'/test_sets/test_json_data_file.json',\n )\n\n df = ge.read_json(\n script_path+'/test_sets/nested_test_json_data_file.json',\n accessor_func=lambda x: x[\"data\"]\n )\n\n def test_read_excel(self):\n script_path = os.path.dirname(os.path.realpath(__file__))\n df = ge.read_excel(\n script_path+'/test_sets/Titanic_multi_sheet.xlsx',\n )\n assert df['Name'][0] == 'Allen, Miss Elisabeth Walton'\n assert isinstance(df, PandasDataset)\n\n # Note that pandas changed the parameter name from sheetname to sheet_name.\n # We will test with both options to ensure that the versions are correct.\n pandas_version = pd.__version__\n if re.match('0\\.2[012]\\.', pandas_version) is not None:\n dfs_dict = ge.read_excel(\n script_path+'/test_sets/Titanic_multi_sheet.xlsx',\n sheetname=None\n )\n\n else:\n dfs_dict = ge.read_excel(\n script_path+'/test_sets/Titanic_multi_sheet.xlsx',\n sheet_name=None\n )\n assert isinstance(dfs_dict, dict)\n assert list(dfs_dict.keys()) == ['Titanic_1', 'Titanic_2', 'Titanic_3']\n assert isinstance(dfs_dict['Titanic_1'], PandasDataset)\n assert dfs_dict['Titanic_1']['Name'][0] == 'Allen, Miss Elisabeth Walton'\n\n def test_read_table(self):\n script_path = os.path.dirname(os.path.realpath(__file__))\n df = ge.read_table(\n script_path+'/test_sets/Titanic.csv',\n sep=','\n )\n assert df['Name'][0] == 'Allen, Miss Elisabeth Walton'\n assert isinstance(df, PandasDataset)\n\n def test_read_parquet(self):\n \"\"\"\n This test is unusual, because on travis (but only on travis), we have observed problems importing pyarrow,\n which breaks this test (since it requires pyarrow available).\n\n The issue seems to be related to a binary compatibility issue with the installed/available version of numpy:\n pyarrow 0.10 requires numpy >= 1.14.\n\n Since pyarrow is not in our actual requirements, we are not going to adjust up the required numpy version.\n \"\"\"\n\n # Pass this test if the available version of pandas is less than 0.21.0, because prior\n # versions of pandas did not include the read_parquet function and the test doesn't apply\n pandas_version = re.match('(.+)\\.(.+)\\..+', pd.__version__)\n if pandas_version is None:\n raise ValueError(\"Unrecognized pandas version!\")\n else:\n pandas_version_major = int(pandas_version.group(1))\n pandas_version_minor = int(pandas_version.group(2))\n if (pandas_version_major == 0) and (pandas_version_minor < 21):\n return\n\n script_path = os.path.dirname(os.path.realpath(__file__))\n df = ge.read_parquet(\n script_path+'/test_sets/Titanic.parquet'\n )\n assert df['Name'][1] == 'Allen, Miss Elisabeth Walton'\n assert isinstance(df, PandasDataset)\n\n def test_read_pickle(self):\n script_path = os.path.dirname(os.path.realpath(__file__))\n df = ge.read_pickle(\n script_path+'/test_sets/Titanic.pkl',\n )\n assert df['Name'][0] == 'Allen, Miss Elisabeth Walton'\n assert isinstance(df, PandasDataset)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_great_expectations.py","file_name":"test_great_expectations.py","file_ext":"py","file_size_in_byte":21031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"336948308","text":"from keras.datasets import mnist\r\nfrom keras.layers import Dense, Activation\r\nfrom keras.models import Sequential\r\nfrom keras.utils import np_utils\r\nfrom keras.optimizers import RMSprop\r\n\r\n# download the mnist to the path '~/.keras/datasets/' if it is the first time to be called\r\n# X shape (60,000 28x28), y shape (10,000, )\r\n(X_train, y_train), (X_test, y_test) = mnist.load_data()\r\n\r\n# data pre-processing\r\nX_train = X_train.reshape(X_train.shape[0], -1) / 255. # normalize\r\nX_test = X_test.reshape(X_test.shape[0], -1) / 255. # normalize\r\ny_train = np_utils.to_categorical(y_train, num_classes=10)\r\ny_test = np_utils.to_categorical(y_test, num_classes=10)\r\n\r\nprint(X_train[1].shape)\r\nprint(X_train[1])\r\n\"\"\"\r\n(784,)\r\n\"\"\"\r\n\r\nprint(y_train[:3])\r\n\"\"\"\r\n[[ 0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]\r\n [ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\r\n [ 0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]]\r\n\"\"\"\r\n\r\nmodel = Sequential([\r\n Dense(32, input_dim=784),\r\n Activation('relu'),\r\n Dense(10),\r\n Activation('softmax'),\r\n])\r\n\r\nrmsprop = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)\r\nmodel.compile(optimizer=rmsprop, loss='categorical_crossentropy', metrics=['accuracy'])\r\n\r\n\r\n# 训练网络,用fit函数,导入数据,训练次数为20,每批处理32个\r\nmodel.fit(X_train,y_train, nb_epoch=20, batch_size=32)\r\n# 测试模型\r\nprint('\\nTesting ------------')\r\n# Evaluate the model with the metrics we defined earlier\r\nloss, accuracy = model.evaluate(X_test, y_test)\r\n\r\nprint('test loss: ', loss)\r\nprint('test accuracy: ', accuracy)\r\n","sub_path":"mnist_test.py","file_name":"mnist_test.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"49862707","text":"import torch\nfrom torch.utils.data import Dataset\n\nfrom .dataset import TwoFrameVideoSampler, final_image_transform\nfrom .model import initialize_model\nfrom .params import *\n\n\nclass PsuedoDataset(Dataset):\n def __init__(self, sampler):\n self.sampler = sampler\n self._open()\n\n def _open(self):\n self._iter = iter(self.sampler)\n\n def __len__(self):\n return len(self.sampler)\n\n def __getitem__(self, idx):\n try:\n return next(self._iter)\n except StopIteration:\n self._open()\n return next(self._iter)\n\n\ndef predict_speeds(video_path):\n video_sampler = PsuedoDataset(TwoFrameVideoSampler(video_path, transformer=final_image_transform))\n sampler = torch.utils.data.BatchSampler(torch.utils.data.SequentialSampler(video_sampler), batch_size=batch_size, drop_last=True)\n batched_video = torch.utils.data.DataLoader(video_sampler, batch_sampler=sampler)\n\n model, input_size = initialize_model(model_name, num_classes, feature_extract, use_pretrained=True)\n best_model_wts = torch.load('./best_model.pth')\n model.load_state_dict(best_model_wts)\n model.to(device)\n model.eval()\n\n for batch in batched_video:\n last_frame, current_frame = batch\n last_frame.to(device)\n current_frame.to(device)\n _speed = model(last_frame, current_frame)\n speed = _speed.tolist()\n print(speed)\n\n\ndef run_validation_routine():\n predict_speeds('./data/test.mp4')\n","sub_path":"dashspeed/label_video.py","file_name":"label_video.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"116498239","text":"import os\nimport time\nimport sys\n\ndef main(setting_time):\n # timer\n while True:\n cur_time = time.strftime(\"%H:%M\", time.localtime())\n\n print(\"cur_time: \", cur_time)\n print(\"setting time: \", setting_time)\n\n if cur_time == setting_time:\n os.system(\"/home/yingchenguan/project/code/start.py\")\n print(\"have prcessed\")\n\n time.sleep(15)\n print(\"waiting........\")\n\nif __name__ == \"__main__\":\n print(\"please enter a time for processing data (24 hour clock) ie. 13:50\")\n setting_time = input()\n\n try:\n time.strptime(setting_time, \"%H:%M\") # 判定是否是一个合法的时间\n upload_time = setting_time.strip()\n print(\"the processing time has setted at\", upload_time)\n except:\n print(\"the time is illegal, the default time is 00:00\")\n upload_time = \"00:00\"\n\n main(upload_time)","sub_path":"Project/Code/google cloud/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"456388323","text":"from flask import Flask, jsonify, request, render_template\nimport requests\n\napp = Flask(__name__, template_folder='templates')\n\nvariables_list = ['tipoEgreso' , 'tipoElemento' , 'proveedor', 'formaPago', 'aprobacion', 'realizarPago']\n\n\n@app.route('/compras', methods=['GET'])\ndef get_compras():\n all_compras = requests.get('http://localhost:5000/compras').json()\n return render_template('index.html', compras=all_compras)\n\n\n@app.route('/compras', methods=['POST'])\ndef create_compra():\n compra = dict(request.values)\n compra['tipoEgreso'] = compra['tipoEgreso']\n compra['tipoElemento'] = compra['tipoElemento']\n compra['proveedor'] = compra['proveedor']\n compra['formaPago'] = compra['formaPago']\n compra['aprobacion'] = compra['aprobacion']\n compra['realizarPago'] = compra['realizarPago']\n requests.post('http://localhost:5000/compras', json=compra)\n return(get_compras())\n\n#app.run(port=8000, debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"228563970","text":"# Copyright 2018 Intel, Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport json\nimport mock\nimport testtools\n\nfrom sushy import exceptions\n\nfrom rsd_lib.resources.v2_4.storage_service import storage_service\nfrom rsd_lib.resources.v2_4.storage_service import volume\n\n\nclass StorageServiceTestCase(testtools.TestCase):\n\n def setUp(self):\n super(StorageServiceTestCase, self).setUp()\n self.conn = mock.Mock()\n with open('rsd_lib/tests/unit/json_samples/v2_4/storage_service.json',\n 'r') as f:\n self.conn.get.return_value.json.return_value = json.loads(f.read())\n\n self.storage_service_inst = storage_service.StorageService(\n self.conn, '/redfish/v1/StorageServices/NVMeoE1',\n redfish_version='1.0.2')\n\n def test__parse_attributes(self):\n self.storage_service_inst._parse_attributes()\n self.assertEqual('1.0.2', self.storage_service_inst.redfish_version)\n self.assertEqual('Storage Service description',\n self.storage_service_inst.description)\n self.assertEqual('NVMeoE1', self.storage_service_inst.identity)\n self.assertEqual('Storage Service', self.storage_service_inst.name)\n self.assertEqual('Enabled', self.storage_service_inst.status.state)\n self.assertEqual('OK', self.storage_service_inst.status.health)\n self.assertEqual('OK', self.storage_service_inst.status.health_rollup)\n\n def test__get_volume_collection_path(self):\n expected = '/redfish/v1/StorageServices/1/Volumes'\n result = self.storage_service_inst._get_volume_collection_path()\n self.assertEqual(expected, result)\n\n def test__get_volume_collection_path_missing_processors_attr(self):\n self.storage_service_inst._json.pop('Volumes')\n self.assertRaisesRegex(\n exceptions.MissingAttributeError, 'attribute Volumes',\n self.storage_service_inst._get_volume_collection_path)\n\n def test_volumes(self):\n # | GIVEN |\n self.conn.get.return_value.json.reset_mock()\n with open('rsd_lib/tests/unit/json_samples/v2_4/'\n 'volume_collection.json', 'r') as f:\n self.conn.get.return_value.json.return_value = json.loads(f.read())\n # | WHEN |\n actual_volumes = self.storage_service_inst.volumes\n # | THEN |\n self.assertIsInstance(actual_volumes,\n volume.VolumeCollection)\n self.conn.get.return_value.json.assert_called_once_with()\n\n # reset mock\n self.conn.get.return_value.json.reset_mock()\n # | WHEN & THEN |\n # tests for same object on invoking subsequently\n self.assertIs(actual_volumes,\n self.storage_service_inst.volumes)\n self.conn.get.return_value.json.assert_not_called()\n\n def test_volumes_on_refresh(self):\n # | GIVEN |\n with open('rsd_lib/tests/unit/json_samples/v2_4/'\n 'volume_collection.json', 'r') as f:\n self.conn.get.return_value.json.return_value = json.loads(f.read())\n # | WHEN & THEN |\n self.assertIsInstance(self.storage_service_inst.volumes,\n volume.VolumeCollection)\n\n # On refreshing the storage service instance...\n with open('rsd_lib/tests/unit/json_samples/v2_4/'\n 'storage_service.json', 'r') as f:\n self.conn.get.return_value.json.return_value = json.loads(f.read())\n\n self.storage_service_inst.invalidate()\n self.storage_service_inst.refresh(force=False)\n\n # | GIVEN |\n with open('rsd_lib/tests/unit/json_samples/v2_4/'\n 'volume_collection.json', 'r') as f:\n self.conn.get.return_value.json.return_value = json.loads(f.read())\n # | WHEN & THEN |\n self.assertIsInstance(self.storage_service_inst.volumes,\n volume.VolumeCollection)\n\n\nclass StorageServiceCollectionTestCase(testtools.TestCase):\n\n def setUp(self):\n super(StorageServiceCollectionTestCase, self).setUp()\n self.conn = mock.Mock()\n with open('rsd_lib/tests/unit/json_samples/v2_4/'\n 'storage_service_collection.json', 'r') as f:\n self.conn.get.return_value.json.return_value = json.loads(f.read())\n self.storage_service_col = storage_service.StorageServiceCollection(\n self.conn, '/redfish/v1/StorageServices', redfish_version='1.0.2')\n\n def test__parse_attributes(self):\n self.storage_service_col._parse_attributes()\n self.assertEqual('1.0.2', self.storage_service_col.redfish_version)\n self.assertEqual('Storage Services Collection',\n self.storage_service_col.name)\n self.assertEqual(('/redfish/v1/StorageServices/NVMeoE1',),\n self.storage_service_col.members_identities)\n\n @mock.patch.object(storage_service, 'StorageService', autospec=True)\n def test_get_member(self, mock_storage_service):\n self.storage_service_col.get_member(\n '/redfish/v1/StorageServices/NVMeoE1')\n mock_storage_service.assert_called_once_with(\n self.storage_service_col._conn,\n '/redfish/v1/StorageServices/NVMeoE1',\n redfish_version=self.storage_service_col.redfish_version)\n\n @mock.patch.object(storage_service, 'StorageService', autospec=True)\n def test_get_members(self, mock_storage_service):\n members = self.storage_service_col.get_members()\n mock_storage_service.assert_called_once_with(\n self.storage_service_col._conn,\n '/redfish/v1/StorageServices/NVMeoE1',\n redfish_version=self.storage_service_col.redfish_version)\n self.assertIsInstance(members, list)\n self.assertEqual(1, len(members))\n","sub_path":"rsd_lib/tests/unit/resources/v2_4/storage_service/test_storage_service.py","file_name":"test_storage_service.py","file_ext":"py","file_size_in_byte":6389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"483710552","text":"# pip install websocket-client\nimport sys\nimport websocket\n\nnostderr = len(sys.argv) >= 2 and sys.argv[1] == \"suppress_std_err\"\nprint(\"Suppressing stderr: \" + str(nostderr))\n\ntry:\n ws = websocket.WebSocket()\n ws.connect(\"ws://localhost:4444\", timeout=3)\n print(ws.recv())\n ws.close(timeout=3)\nexcept Exception as exception:\n if(nostderr):\n print(exception)\n else:\n raise exception","sub_path":"verify_conn.py","file_name":"verify_conn.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"1601614","text":"from enum import Enum\n\nclass SetUserProfileAllInfoReturnCodeEnum(Enum):\n SUCCESS=(0, \"success\")\n CUSTID_WRONG=(1, \"custid不正确\")\n ADDRESS_WRONG=(5,\"cust_address设置不成功(区域id不存在)\")\n SEX_WRONG=(6, \"cust_sex设置不成功 内容只能为0 或者1\")\n BIRTHDAY_LONG=(7,\"cust_birthday日期格式不正确\")\n JOB_LONG=(8,\"cust_job长度超限 40\")\n\n\n","sub_path":"data/set_user_profile_all_info_returncode_enum.py","file_name":"set_user_profile_all_info_returncode_enum.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"266411542","text":"from django.forms import inlineformset_factory\nfrom django.shortcuts import render, redirect\nfrom django.template import loader\nfrom.models import Produit,Commande,Customer,Order\nfrom.forms import FournisseurForm,ProduitForm,CreateUserForm,OrderForm,CustomerForm\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth import get_user_model\nfrom.filters import OrderFilter,CommandFilter\nfrom .decorators import unauthenticated_user,allowed_users\nfrom django.contrib.auth.models import Group\n# Create your views here.\nfrom django.http import HttpResponse, HttpResponseRedirect\n\n\n\ndef index1(request):\n list = Produit.objects.all()\n return render(request, 'vitrine2.html', {'list': list})\n\n@login_required(login_url='login')\n@allowed_users(allowed_roles=['admin'])\ndef fournisseurPage(request):\n if request.method == \"POST\":\n\n form=ProduitForm(request.POST,request.FILES)\n if form.is_valid():\n form.save()\n return redirect('index1')\n else:\n\n form = ProduitForm()\n return render(request,'majProduits.html',{'form':form})\n@login_required(login_url='login')\ndef index(request):\n listC=Commande.objects.all()\n myFilter=CommandFilter(request.GET, queryset=listC)\n listC=myFilter.qs\n context={'listC':listC,'myFilter':myFilter}\n return render(request,'commande.html',context)\n@login_required(login_url='login')\n@allowed_users(allowed_roles=['customer'])\ndef userPage(request):\n\tcontext={}\n\treturn render(request, 'user.html', context)\n\ndef loginn(request):\n if request.user.is_authenticated:\n return redirect('index1')\n else:\n if request.method == 'POST':\n username = request.POST.get('username')\n password = request.POST.get('password')\n user = authenticate(request, username=username, password=password)\n if user is not None:\n login(request,user)\n return redirect('index1')\n else:\n messages.info(request, 'Username OR password is incorrect')\n\n context = {}\n return render(request, 'login.html', context)\ndef logoutUser(request):\n logout(request)\n return redirect('login')\n@unauthenticated_user\ndef register(request):\n form = CreateUserForm()\n if request.method == 'POST':\n form = CreateUserForm(request.POST)\n if form.is_valid():\n user = form.save()\n username = form.cleaned_data.get('username')\n\n group = Group.objects.get(name='customer')\n user.groups.add(group)\n Customer.objects.create(\n user=user,\n name=user.username,\n )\n\n messages.success(request, 'Account was created for ' + username)\n\n return redirect('login')\n\n context = {'form': form}\n return render(request, 'register.html', context)\n@login_required(login_url='login')\ndef updateOrder(request, pk):\n\n\torder = Order.objects.get(id=pk)\n\tform = OrderForm(instance=order)\n\n\tif request.method == 'POST':\n\t\tform = OrderForm(request.POST, instance=order)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\treturn redirect('/')\n\n\tcontext = {'form':form}\n\treturn render(request, 'Commandform.html', context)\n@login_required(login_url='login')\ndef deleteOrder(request, pk):\n\torder = Order.objects.get(id=pk)\n\tif request.method == \"POST\":\n\t\torder.delete()\n\t\treturn redirect('/')\n\n\tcontext = {'item':order}\n\treturn render(request, 'delete.html', context)\n\n@login_required(login_url='login')\n@allowed_users(allowed_roles=['customer'])\ndef accountSettings(request):\n\tcustomer = request.user.customer\n\tform = CustomerForm(instance=customer)\n\n\tif request.method == 'POST':\n\t\tform = CustomerForm(request.POST, request.FILES,instance=customer)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\n\n\tcontext = {'form':form}\n\treturn render(request, 'settings2.html', context)\n\n@login_required(login_url='login')\n@allowed_users(allowed_roles=['admin'])\ndef dashbord(request):\n orders = Order.objects.all()\n customers = Customer.objects.all()\n myFilter = OrderFilter(request.GET, queryset=orders)\n orders = myFilter.qs\n\n total_customers = customers.count()\n\n total_orders = orders.count()\n delivered = orders.filter(status='Delivered').count()\n pending = orders.filter(status='Pending').count()\n\n context = {'orders': orders, 'customers': customers,\n 'total_orders': total_orders, 'delivered': delivered,\n 'pending': pending,'myFilter':myFilter}\n\n return render(request, 'dashboard.html', context)\n@login_required(login_url='login')\n@allowed_users(allowed_roles=['admin'])\ndef customer(request, pk_test):\n\tcustomer = Customer.objects.get(id=pk_test)\n\n\torders = customer.order_set.all()\n\torder_count = orders.count()\n\tcontext = {'customer':customer, 'orders':orders, 'order_count':order_count}\n\treturn render(request, 'user.html',context)\n\ndef createOrder(request, pk):\n\tOrderFormSet = inlineformset_factory(Customer, Order, fields=('product', 'status'), extra=10 )\n\tcustomer = Customer.objects.get(id=pk)\n\tformset = OrderFormSet(queryset=Order.objects.none(),instance=customer)\n\tif request.method == 'POST':\n\n\t\tform = OrderForm(request.POST)\n\t\tformset = OrderFormSet(request.POST, instance=customer)\n\t\tif formset.is_valid():\n\t\t\tformset.save()\n\t\t\treturn redirect('/')\n\n\tcontext = {'form':formset}\n\treturn render(request, 'order_form.html', context)\n\n\ndef viewproduct(request,pk):\n products=Produit.objects.get(id=pk)\n context = {'products': products}\n return render(request,'productview.html',context)\n\n\n\n","sub_path":"magasin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"325389239","text":"from golem import actions\n\nfrom projects.golem_gui.pages import common\nfrom projects.golem_gui.pages import api\n\n\ndescription = 'Verify a correct message is displayed when the page does not exist'\n\n\ndef setup(data):\n common.access_golem(data.env.url, data.env.admin)\n api.project.using_project('page_builder')\n\n\ndef test_access_page_does_not_exist(data):\n actions.navigate(data.env.url + 'project/'+data.project+'/page/not_existent')\n actions.assert_page_contains_text('The page not_existent does not exist')\n","sub_path":"projects/golem_gui/tests/page_builder/access_page_does_not_exist.py","file_name":"access_page_does_not_exist.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"267512416","text":"from scrapy.contrib.downloadermiddleware.useragent import UserAgentMiddleware\r\nimport random\r\n\r\nbasedir = 'F:/Windows/Document/pycharm/proxy/result/alive_ip.txt'\r\n\r\nclass ProxyMiddleware(object):\r\n\tdef process_request(self,request,spider):\r\n\t\tlines = open(basedir,'r').readlines()\r\n\t\tproxy = random.choice(lines)\r\n\t\trequest.meta['proxy'] = \"http://{}\".format(proxy)","sub_path":"shici/shici/middlewares/proxyMiddleWares.py","file_name":"proxyMiddleWares.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"348952546","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\n@File : 345. 反转字符串中的元音字母.py\n@Time : 2019/11/06 16:17:52\n@Author : 吉祥鸟\n@Contact : jixnhu@qq.com \n'''\n\n\"\"\"\n编写一个函数,以字符串作为输入,反转该字符串中的元音字母。\n\n示例 1:\n输入: \"hello\"\n输出: \"holle\"\n\n示例 2:\n输入: \"leetcode\"\n输出: \"leotcede\"\n\n说明:\n元音字母不包含字母\"y\"。\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/reverse-vowels-of-a-string\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\n思路:\n略微有点繁琐\n\n1. 将输入的字符串另存转换为一个列表\n2. 获取到全部的元音字母的位置,将其存到一个列表中\n3. 调换位置\n4. 将列表转换为字符输出\n\"\"\"\n\nclass Solution(object):\n def reverseVowels(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n yuan=[\"a\",\"e\",\"i\",\"o\",\"u\",\"A\",\"E\",\"I\",\"O\",\"U\"]\n s1=list(s)\n num_list=[]\n for zz,i in enumerate(s):\n if i in yuan:\n num_list.append(zz)\n yuan1=0\n yuan2=len(num_list)-1\n while yuan1 < yuan2:\n s1[int(num_list[yuan2])],s1[int(num_list[yuan1])]=s[int(num_list[yuan1])],s[int(num_list[yuan2])]\n yuan1+=1\n yuan2-=1\n return \"\".join(s1)\n\nif __name__ == \"__main__\":\n a = \"leetcode\"\n print(Solution().reverseVowels(a))\n","sub_path":"345. 反转字符串中的元音字母.py","file_name":"345. 反转字符串中的元音字母.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"642107714","text":"from django.http import HttpResponse\nfrom django.shortcuts import render\nimport requests\nfrom .models import Api_data\n\n#List of Crypto Required\nall_curr = ['bitcoin',\"ethereum\",\"litecoin\",\"cardano\",\"polkadot\",\"dogecoin\",'stellar',\"chainlink\",\"binance-coin\",\"tether\"]\n\ndef home(request):\n data = get_crypto_data()\n return render(request, \"index.html\", {'results':data})\n\n\n\n# return the data received from api as json object\ndef get_crypto_data():\n data_list = []\n api_url = \"https://api.coincap.io/v2/assets/\"\n \n for curr in all_curr:\n try:\n data = requests.get(api_url+\"/\"+curr).json()\n data_list.append(data['data'])\n except Exception as e:\n print(e)\n data_list.append(data['data'])\n return data_list\n","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"102736830","text":"from collections import deque\n\ndef eval_expr(stack):\n res = stack.pop()\n\nclass Solution:\n def decodeString(self, s):\n\n # Solution 1 - Using a Stack\n # O(n) Time, O(n) Space\n\n # The idea is to keep track of the string and number we've seen so far.\n # Once we encounter a '[' we save the current string and number on the stack.\n # when we encounter a ']' expand the current string using curr string * curr num\n # and set it to the previous string + the expanded current string.\n\n # stack, curr_num, curr_str = [], 0, ''\n # for c in s:\n # if c.isdigit():\n # curr_num = curr_num * 10 + int(c)\n # elif c == '[':\n # stack.append(curr_str)\n # stack.append(curr_num)\n # curr_num, curr_str = 0, ''\n # elif c == ']':\n # curr_num = stack.pop()\n # prev_str = stack.pop()\n # curr_str = prev_str + curr_str * curr_num\n # curr_num = 0\n # else:\n # curr_str += c\n # return curr_str\n\n\n # Solution 2 - Stack\n # O(n) Time, O(n) Space\n\n # This approach is more intuitive and slightly more efficient than that\n # presented in Solution 1.\n\n # We push the elements of the tokens of the encoded string one by one\n # onto the stack until we encounter a closing bracket ']'.\n # We then we pop the elements from the stack one by one and evaluate\n # tokens one by one from the stack and concatenate them together, until\n # we encounter the corresponding open bracket '['.\n # We pop the open bracket and the number before it. This allows us to expnad\n # the substring and place the result back on the stack.\n\n i, n, stack = 0, len(s), []\n\n while i < n:\n if s[i].isdigit():\n j = i\n while j < n and s[j].isdigit():\n j += 1\n num = int(s[i:j])\n stack.append(num)\n i = j\n elif s[i].isalpha():\n j = i\n while j < n and s[j].isalpha():\n j += 1\n substr = s[i:j]\n stack.append(substr)\n i = j\n elif s[i] == ']': # Eval until we reach the corresponding '['\n queue = deque()\n while stack[-1] != '[':\n queue.appendleft(stack.pop())\n substr = ''.join(queue)\n stack.pop() # Remove '['\n num = stack.pop()\n stack.append(num * substr)\n i += 1\n else: # '[' put on the stack\n stack.append(s[i])\n i += 1\n\n return ''.join(stack)\n\n","sub_path":"0394-Decode-String/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"436353785","text":"import torch\nimport torch.nn as nn\nfrom datasets import *\nimport argparse\nfrom utils.vocapi_evaluator import VOCAPIEvaluator\n\nparser = argparse.ArgumentParser(description='Detection zoon')\nparser.add_argument('-v', '--version', default='yolo', help='Support:yolo, fcos')\nparser.add_argument('-d', '--dataset', default='voc', help='voc, coco-val, coco-test.')\nparser.add_argument('--trained_model',\n type=str,\n default='weights/final.pth',\n help='Trained state_dict file path to open')\nparser.add_argument('-size', '--input_size', default=416, type=int, help='input_size')\nparser.add_argument('--cuda', action='store_true', default=False, help='Use cuda')\n\nargs = parser.parse_args()\n\n\ndef evaluate(model, device, input_size, transform, dataset):\n if dataset == 'voc':\n evaluator = VOCAPIEvaluator(data_root=VOC_ROOT,\n img_size=input_size,\n device=device,\n transform=transform,\n labelmap=VOC_CLASSES,\n display=True)\n else:\n print('Unknow dataset. Only voc now')\n exit(0)\n evaluator.evaluate(model)\n\n\nif __name__ == '__main__':\n if args.cuda and torch.cuda.is_available():\n print('use cuda')\n torch.backends.cudnn.benchmark = True\n device = torch.device(\"cuda\")\n else:\n device = torch.device(\"cpu\")\n\n # dataset\n if args.dataset == 'voc':\n print('Eval on voc ...')\n NUM_CLASSES = 20\n else:\n print('Unknow dataset. Only voc now')\n exit(0)\n\n # input size\n input_size = args.input_size\n\n # build model\n model_cfg = train_cfg\n if args.version == 'yolo':\n from models.yolov1 import myYOLO\n model = myYOLO(device,\n input_size=model_cfg['min_dim']['yolo'][0],\n num_classes=NUM_CLASSES,\n trainable=False)\n # Get transform\n from datasets import YOLOBaseTransform as BaseTransform\n transform = BaseTransform(model_cfg['min_dim']['yolo'][0])\n elif args.version == 'fcos':\n from models.tinyfcos import FCOS\n model = FCOS(device,\n input_size=model_cfg['min_dim']['fcos'],\n num_classes=NUM_CLASSES,\n trainable=False)\n from datasets import FCOSBaseTransform as BaseTransform\n transform = BaseTransform(model_cfg['min_dim']['fcos'])\n else:\n print('We only support yolo and fcos for now.')\n exit()\n\n # load net\n model.load_state_dict(torch.load(args.trained_model, map_location=device))\n model.eval()\n print('Finished loading model!')\n model = model.to(device)\n\n # evaluation\n with torch.no_grad():\n evaluate(model, device, input_size, transform, args.dataset)\n","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"526884586","text":"import json\nimport re\nimport time\n\nfrom tweepy.streaming import StreamListener\nfrom html.parser import HTMLParser\nfrom unidecode import unidecode\n\nfrom sentiment_analyzer import sentiment, text_blob_sentiment\nfrom tweet_cleanser import prepare_tweet_json\nfrom es_datastore import write_to_es\n\n# Twitter's results just give us back the tweet, but don't tell us which keyword it was found with\n# so, we have to use a keyword dictionary to search the tweet and match it back up to the party\nparty_tags = dict()\n#BJP tags\nparty_tags['modi'] = 'Bharatiya Janata Party'\nparty_tags['namo'] = 'Bharatiya Janata Party'\nparty_tags['namo'] = 'Bharatiya Janata Party'\nparty_tags['phirekbaarmodisarkar'] = 'Bharatiya Janata Party'\nparty_tags['bharatiyajanataparty'] = 'Bharatiya Janata Party'\nparty_tags['bjp'] = 'Bharatiya Janata Party'\nparty_tags['nationaldemocraticalliance'] = 'Bharatiya Janata Party'\nparty_tags['nda'] = 'Bharatiya Janata Party'\nparty_tags['vajpayee'] = 'Bharatiya Janata Party'\n#congress tags\nparty_tags['indiannationalcongress'] = 'Indian National Congress'\nparty_tags['incindia'] = 'Indian National Congress'\nparty_tags['gandhi'] = 'Indian National Congress'\nparty_tags['rahulgandhi'] = 'Indian National Congress'\nparty_tags['soniagandhi'] = 'Indian National Congress'\nparty_tags['sonia'] = 'Indian National Congress'\nparty_tags['priyankagandhi'] = 'Indian National Congress'\nparty_tags['rahulgandhiforpm'] = 'Indian National Congress'\nparty_tags['inc'] = 'Indian National Congress'\nparty_tags['congress'] = 'Indian National Congress'\nparty_tags['amethi'] = 'Indian National Congress'\n\ndef clean_tweet(tweet):\n return ' '.join(re.sub(\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t])|(\\w+:\\/\\/\\S+)\", \" \", tweet).split())\n\n#build the class used to process tweets to check for feeds\nclass twitter_streaming(StreamListener):\n\n def on_data(self, data):\n print('inside on data')\n all_data = json.loads(HTMLParser().unescape(data))\n #https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/tweet-object\n #https://gist.github.com/hrp/900964\n if 'text' in all_data:\n #1\n tweet = all_data['text']\n tweet = unidecode(tweet)\n #2\n tweetID = all_data['id_str']\n #3\n source = all_data['source']\n source = unidecode(source)\n #4\n if all_data['place']:\n country = all_data['place']['country']\n country = unidecode(country)\n #5\n country_code = all_data['place']['country_code']\n country_code = unidecode(country_code)\n #6\n full_name = all_data['place']['full_name']\n full_name = unidecode(full_name)\n #7\n name = all_data['place']['name']\n name = unidecode(name)\n #8\n place_type = all_data['place']['place_type']\n place_type = unidecode(place_type)\n #9\n else:\n country = country_code = full_name = name = place_type = \"0\"\n\n quote_count = all_data['quote_count']\n #10\n reply_count = all_data['reply_count']\n #11\n retweet_count = all_data['retweet_count']\n #12\n favorite_count = all_data['favorite_count']\n #13\n screen_name = all_data['user']['screen_name']\n screen_name = unidecode(screen_name)\n #13\n followers_count = all_data['user']['followers_count']\n #14\n friends_count = all_data['user']['friends_count']\n #15\n verified = all_data['user']['verified']\n #print(\"verified value is:\", verified)\n #type(verified)\n\n\n\n #tweetNoPunctuation = regex.sub('', tweet)\n tweetNoPunctuation = clean_tweet(tweet)\n #we want to make sure while compiling tweets, we do not include the oens that are retweeted\n if not all_data['retweeted'] and not tweet.startswith('RT') and 't.co' not in tweet:\n sentiment_value, confidence = sentiment(tweetNoPunctuation)\n #print(tweet, sentiment_value, confidence) #print output\n\n #value manipulations\n if (sentiment_value.lower() == \"neg\"):\n num_sentiment=0\n else:\n num_sentiment=1\n\n blob_senti = text_blob_sentiment(tweetNoPunctuation)\n\n if (verified == True):\n verified_bit = 1\n else:\n verified_bit = 0\n\n found = False\n party = \"\"\n for word in tweetNoPunctuation.split(\" \"):\n if word.lower() in party_tags.keys():\n party_name = party_tags[word.lower()]\n #print(\"Found keyword: \", word, \" belongs to party: \", party_name)\n found = True\n break\n\n if found:\n created_at = time.strftime('%Y-%m-%d %H:%M:%S')\n newID = (int)(all_data['id'])\n #twitter JSON is being parsed with queries below and using sentiment module, we are assigning confidence values\n # tweetID, party_name, dateTime, tweet, source,country, country_code, full_name, name, place_type,\\\n # reply_count, retweet_count, favorite_count, result, confidence,num_sentiment\n tweet_data = (tweetID ,party_name, created_at, tweet,screen_name,followers_count,friends_count,\\\n verified_bit, source,country, country_code,full_name,name, place_type,\\\n reply_count, retweet_count, favorite_count, sentiment_value.lower(), confidence, num_sentiment)\n\n data_to_dump = prepare_tweet_json([tweetID ,party_name, created_at, tweet,screen_name,\n source,country, country_code,full_name, place_type,\\\n sentiment_value.lower(), num_sentiment, confidence, followers_count, blob_senti])\n write_to_es(data_to_dump)\n print(data_to_dump)\n\n # Write a row to the CSV file. I use encode UTF-8\n # csvWriter.writerow([tweetID ,party_name, created_at, tweet,screen_name,followers_count,friends_count,\\\n # verified_bit, source,country, country_code,full_name,name, place_type,\\\n # reply_count, retweet_count, favorite_count, sentiment_value.lower(), confidence, num_sentiment])\n\n # c.execute(add_tweet, tweet_data)\n # conn.commit()\n else:\n print('unrelated tweet found')\n else:\n print('retweeted data found')\n else:\n print('no text field found')\n\n #error handling, since tweepy tends to time out with twitter with out any reason closing the connection from their side\n def on_limit(self, track):\n print('Limit hit! Track = %s' % track)\n return True\n\n def on_error(self, status):\n print(status)\n\n def on_disconnect(self, notice):\n print(notice)\n\n return True","sub_path":"code/py_code/twitter_stream_handler.py","file_name":"twitter_stream_handler.py","file_ext":"py","file_size_in_byte":7425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"365407502","text":"\"\"\"empty message\n\nRevision ID: 399d119c664\nRevises: 4763536ec15\nCreate Date: 2015-12-28 11:58:38.694137\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '399d119c664'\ndown_revision = '4763536ec15'\n\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column('models', sa.Column('fullMetaData', postgresql.JSON(), nullable=True))\n op.add_column('models', sa.Column('modelSpec', postgresql.JSON(), nullable=True))\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('models', 'modelSpec')\n op.drop_column('models', 'fullMetaData')\n ### end Alembic commands ###\n","sub_path":"migrations/versions/399d119c664_.py","file_name":"399d119c664_.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"544090953","text":"# ECE 459 Assignment 4 90th Percentile Script\n# Credit: Kevin Yang ( k46yang@edu.uwaterloo.ca )\n# with additional credits to Google & Stack Overflow\n\nimport numpy as np\nimport csv\nfrom glob import glob\n\nfilenames = glob(\"results.csv\")\n# results_{timestamp}_n={n}_a={a}_j={j}_l={l}_m={m}_b={b}_g={g}_.csv\n\noutput_file_name = \"experimental_results.csv\"\n\nwith open(output_file_name, \"w+\") as output_csv:\n writer = csv.writer(output_csv, delimiter=\",\")\n writer.writerow(['n', 'a', 'j', 'l', 'm', 'b', 'g', 'p90'])\n\n for filename in filenames:\n attributes = list()\n filename_metadata = filename.split(\"_\")[2:9]\n for attr in filename_metadata:\n attributes.append(int(attr.split(\"=\")[1]))\n\n with open(filename) as csvfile:\n reader = csv.reader(csvfile, delimiter=\",\")\n arr = list()\n for row in reader:\n arr.append(float(row[4]))\n percentile_90 = np.percentile(np.array(arr), 90)\n writer.writerow(attributes + [percentile_90])\n","sub_path":"Assignment 4 - Profiling and Load Balancing/option-2/calculate_percentile.py","file_name":"calculate_percentile.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"251517963","text":"#\n# Copyright (c) 2019 Baidu.com, Inc. All Rights Reserved\n#\n\"\"\"\nTools.\n\nAuthors: zhaochaochao(zhaochaochao@baidu.com)\nDate: 2019/11/7 上午9:24\n\"\"\"\nimport urllib.request as req\n\n\ndef set_proxy():\n \"\"\"Set http https ftp proxy. The proxy ip and port is yours proxy. I use\n Bandwagon as proxy. Many pictures can't access if not set proxy.\n\n Returns:\n\n \"\"\"\n handler = req.ProxyHandler({'http': '127.0.0.1:1080',\n 'https': '127.0.0.1:1080',\n 'ftp': '127.0.0.1:1080'})\n opener = req.build_opener(handler)\n req.install_opener(opener)\n","sub_path":"tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"332412982","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nfrom starlette.requests import Request\nfrom starlette.responses import JSONResponse\n\n\nclass CustomException(Exception):\n \"\"\"\n 自定义异常类\n \"\"\"\n\n def __init__(self, name: str):\n self.name = name\n\n\nasync def custom_exception_handler(request: Request, exc: CustomException):\n return JSONResponse(\n status_code=418,\n content={\"message\": f\"Oops! {exc.name} did something. There goes a rainbow...\"},\n )\n","sub_path":"server/api/errors/custom.py","file_name":"custom.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"86436264","text":"#!/usr/bin/env python\n\nd1 = dict()\nda = {} # short cut for da = dict()\n\nd2 = dict()\n\nx = open('DATA/alice.txt')\nprint(type(d1), type(x))\n\nprint(d1.keys())\n\nclass Being:\n pass\n\nclass Companion:\n pass\n\nclass Pet(Companion):\n def cuddle(self):\n print(\"cuddling...\")\n\nclass Animal(Being):\n\n def breathe(self, how):\n self.reproduce()\n print(f\"breathing {how}...\")\n\n def reproduce(self):\n pass\n\nclass Dog(Animal, Pet):\n stuff = ['a', 'b', 'c']\n\n def __init__(self, name, breed=\"NONE\"):\n self.name = name\n self.breed = breed\n\n def bark(self):\n print(\"woof! woof!\")\n\n @property # getter property\n def name(self):\n return self._name\n\n @name.setter # setter property\n def name(self, new_name):\n if isinstance(new_name, str):\n self._name = new_name\n else:\n raise TypeError(\"Dog name must be a string\")\n\n @property\n def breed(self):\n return self._breed\n\n @breed.setter\n def breed(self, value):\n self._breed = value\n\n @property\n def info(self):\n return(f\"{self.breed}/{self.name}\")\n\n\n def __str__(self):\n class_name = type(self).__name__\n return \"{}({}, {})\".format(class_name, self.name, self.breed)\n\n def __add__(self, other):\n return 42\n\n def __len__(self):\n return 1000\n\n # instance method\n def foo(self): # dog1.foo() ONLY\n print(Dog.stuff)\n print(self.stuff)\n print(\"foo foo foo\")\n\n @classmethod\n def bar(cls): # dog1.bar() OR Dog.bar()\n print(cls.stuff)\n print(\"bar bar\")\n\n @staticmethod\n def blah(): # Dog.blah() ONLY\n print(\"blah\")\n\ndog1 = Dog(\"Andy\")\ndog2 = Dog(\"Poppy\", 'cockapoo')\n\nresult = dog1 + dog2\nprint(\"result is\", result)\nprint(\"length is\", len(dog2))\n\n\ndog1.bark()\ndog2.bark()\ndog1.breathe(\"deeply\")\ndog2.cuddle()\ndog2.breathe(\"shallowly\")\n\nprint(Dog.mro())\n\n\nprint(type(dog2))\nprint(type(dog2).__name__)\n\nprint(dog2.name) # NOT dog2.name()\nprint(dog1.name)\nprint(type(dog1.name))\n\ndog2.name = \"Lucky\"\n\nprint(dog2.name)\n\ndog3 = Dog(\"Bob\", 'Landseer')\n\ntry:\n dog3.name = 1.234\nexcept TypeError as err:\n print(err)\n\nprint(dog3.name)\n\ndog1.breed = 'mixed'\n\nprint(dog1.breed)\n\n\ndog3.bark()\nDog.bark(dog3)\n\ndog2.name = \"Poppy\"\nprint(dog3)\nprint(dog1.info)\nprint(dog2.info)\n\n# x = 5\n# Dog.breathe(x, 'noisily')\n\na = \"wombat\"\n\nprint(str.upper(a))\nprint(a.upper())\n\n\n\nx = 5\nx = int(5)\n\nclass BarfBagBase:\n pass\n\ndef barf_bag():\n pass\n\nfrom knight import Knight\n\nk1 = Knight('Arthur')\nk2 = Knight(\"Lancelot\")\n\nprint(k1.title, k2.quest)\n\n","sub_path":"simple_class_examples.py","file_name":"simple_class_examples.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"377918492","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Document',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('pmid', models.CharField(max_length=128, unique=True, null=True)),\n ('name', models.CharField(max_length=128)),\n ('url', models.URLField()),\n ('pool', models.IntegerField(default=1)),\n ('pub_date', models.CharField(max_length=128)),\n ('abstract', models.CharField(max_length=4086, null=True, blank=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Query',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('text', models.CharField(max_length=1024)),\n ('author', models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Review',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(unique=True, max_length=128)),\n ('creation_date', models.DateTimeField(auto_now_add=True)),\n ('creator_id', models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='UserProfile',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('picture', models.ImageField(upload_to=b'profile_images', blank=True)),\n ('website', models.URLField(blank=True)),\n ('position', models.CharField(max_length=32, blank=True)),\n ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='query',\n name='review',\n field=models.ForeignKey(blank=True, to='medsysrev.Review', null=True),\n preserve_default=True,\n ),\n ]\n","sub_path":"sysrev/medsysrev/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"50298631","text":"# Copyright 2017 Google Inc. / Arup\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\n# Modified from the Python sample for connecting to Google Cloud IoT Core\r\n# Original source: https://github.com/GoogleCloudPlatform/python-docs-samples/\r\n# blob/master/iot/api-client/mqtt_example/cloudiot_mqtt_example.py\r\n\r\n# Subscribe/Callback Docs https://eclipse.org/paho/clients/python/docs/\r\n\r\nfrom navigation import StateModule\r\nfrom datetime import datetime, timedelta\r\nimport jwt\r\nimport json\r\nimport paho.mqtt.client as mqtt\r\nfrom config import GCLOUD_CONFIG\r\nfrom helpers import sensor_data\r\n\r\n\r\nclass GoogleIoTModule(StateModule):\r\n client = None\r\n\r\n def __init__(self, controller):\r\n super(GoogleIoTModule, self).__init__(controller)\r\n controller.add_event_handler(\"sensor-publish\", self.publish_sensor)\r\n controller.add_event_handler(\"kiln-publish\", self.publish_kiln)\r\n self.mqtt_topic = '/devices/{}/events'.format(\r\n GCLOUD_CONFIG['device_id'])\r\n self.connect()\r\n\r\n def on_message(self, userdata, message):\r\n print(userdata, message)\r\n\r\n def connect(self):\r\n try:\r\n args = GCLOUD_CONFIG\r\n self.client = mqtt.Client(\r\n client_id=(\r\n 'projects/{}/locations/{}/registries/{}/devices/{}'.format(\r\n args['project_id'],\r\n args['cloud_region'],\r\n args['registry_id'],\r\n args['device_id'])))\r\n\r\n self.client.username_pw_set(\r\n username='unused',\r\n password=self.create_jwt(\r\n args['project_id'],\r\n args['private_key_file'],\r\n args['algorithm']))\r\n\r\n self.client.tls_set(ca_certs=args['ca_certs'])\r\n\r\n self.client.on_message = self.on_message\r\n self.client.subscribe('/devices/{}/events/commands'.format(\r\n GCLOUD_CONFIG['device_id'], 1))\r\n\r\n self.client.connect(\r\n args['mqtt_bridge_hostname'],\r\n args['mqtt_bridge_port'])\r\n\r\n self.client.loop_start()\r\n\r\n except Exception as e:\r\n print(\"Error connecting to GCloud:\")\r\n print(e)\r\n\r\n def publish_sensor(self, data):\r\n data = sensor_data(\r\n self.controller,\r\n data.uid,\r\n str(data.value),\r\n {\"type\": data.brick_tag, }, )\r\n try:\r\n blob = json.dumps(data)\r\n self.client.publish(self.mqtt_topic + '/sensor', blob, qos=1)\r\n # print(\"published to googleiot\", blob)\r\n except Exception as e:\r\n print(\"Error publishing to GCloud:\")\r\n print(e)\r\n\r\n def publish_kiln(self, data):\r\n try:\r\n blob = json.dumps(data)\r\n self.client.publish(self.mqtt_topic + '/kiln', blob, qos=1)\r\n # print(\"published to googleiot\", blob)\r\n except Exception as e:\r\n print(\"Error publishing to GCloud:\")\r\n print(e)\r\n\r\n def create_jwt(self, project_id, private_key_file, algorithm):\r\n token = {\r\n 'iat': datetime.utcnow(),\r\n 'exp': datetime.utcnow() + timedelta(minutes=60),\r\n 'aud': project_id\r\n }\r\n\r\n with open(private_key_file, 'r') as f:\r\n private_key = f.read()\r\n\r\n return jwt.encode(token, private_key, algorithm=algorithm)\r\n","sub_path":"deskcontrol/modules/googleiot.py","file_name":"googleiot.py","file_ext":"py","file_size_in_byte":3980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"369554969","text":"from django.forms import ModelForm\nfrom .models import Post\n\n\nclass PostForm(ModelForm):\n class Meta:\n model=Post\n fields=('text', 'group')\n labels = {\n 'text': 'Текст',\n 'group': 'Группа'\n }\n help_texts = {\n 'text': 'Введите текст вашего поста',\n 'group': 'Выберите группу для публикации'\n }\n","sub_path":"posts/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"84854892","text":"import unittest\n\nimport sys, os\nsys.path.insert(0, os.path.join(os.path.dirname(__file__), \"../\"))\n\nfrom src.writer import PlainTextWriter, CSVWriter, HTMLTextWriter, JsonWriter\nfrom src.personalData import PersonalData\n\nclass FormatFactoryTest(unittest.TestCase):\n\tdef setUp(self):\n\t\tself.txtWriter = PlainTextWriter()\n\t\tself.htmlWriter = HTMLTextWriter()\n\t\tself.csvWriter = CSVWriter()\n\t\tself.jsonWriter = JsonWriter()\n\t\tself.noData = []\n\t\tself.singleData = [PersonalData(\"Lucy\", \"1010 Water Street \", \"6047150000\")]\n\t\tself.multipleData = [PersonalData(\"Mike\", \"1210 Haro St\", \"6047151111\"), PersonalData(\"Lily\", \"798 Davie Street \", \"6047152222\")]\n\t\tself.blankData = [PersonalData(\"\", \"\", \"\")]\n\n\tdef test_CsvWriter_writes_no_data(self):\n\t\toutput = self.csvWriter.write(self.noData)\n\t\texpectedOutput = self.buildCsvOutput(\"\")\n\t\tself.assertEqual(expectedOutput, output)\n\n\tdef test_CsvWriter_writes_single_data(self):\n\t\toutput = self.csvWriter.write(self.singleData)\n\t\trows = \"Lucy,1010 Water Street ,6047150000\\n\"\n\t\texpectedOutput = self.buildCsvOutput(rows)\n\t\tself.assertEqual(expectedOutput, output)\n\n\tdef test_CsvWriter_writes_multiple_data(self):\n\t\toutput = self.csvWriter.write(self.multipleData)\n\t\trows = \"Mike,1210 Haro St,6047151111\\n\" \\\n\t\t\t \"Lily,798 Davie Street ,6047152222\\n\"\n\t\texpectedOutput = self.buildCsvOutput(rows)\n\t\tself.assertEqual(expectedOutput, output)\n\n\tdef test_CsvWriter_writes_blank_data(self):\n\t\toutput = self.csvWriter.write(self.blankData)\n\t\trows = \",,\\n\"\n\t\texpectedOutput = self.buildCsvOutput(rows)\n\t\tself.assertEqual(expectedOutput, output)\n\n\tdef buildCsvOutput(self, rows):\n\t\treturn \"name,address,phone number\\n\" + rows\n\n\tdef test_JsonWriter_writes_no_data(self):\n\t\toutput = self.jsonWriter.write(self.noData)\n\t\tself.assertEqual(None, output)\n\n\tdef test_JsonWriter_writes_single_data(self):\n\t\toutput = self.jsonWriter.write(self.singleData)\n\t\texpectedOutput = \"{\\n\" \\\n\t\t\t\t\t\t \" \\\"personal_data\\\": [\\n\" \\\n\t\t\t\t\t\t \" {\\n\" \\\n\t\t\t\t\t\t \" \\\"address\\\": \\\"1010 Water Street \\\",\\n\" \\\n\t\t\t\t\t\t \" \\\"name\\\": \\\"Lucy\\\",\\n\" \\\n\t\t\t\t\t\t \" \\\"phone_number\\\": \\\"6047150000\\\"\\n\" \\\n\t\t\t\t\t\t \" }\\n\" \\\n\t\t\t\t\t\t \" ]\\n\" \\\n\t\t\t\t\t\t \"}\"\n\t\tself.assertEqual(expectedOutput, output)\n\n\tdef test_JsonWriter_writes_multiple_data(self):\n\t\toutput = self.jsonWriter.write(self.multipleData)\n\t\texpectedOutput = \"{\\n\" \\\n\t\t\t\t\t\t \" \\\"personal_data\\\": [\\n\" \\\n\t\t\t\t\t\t \" {\\n\" \\\n\t\t\t\t\t\t \" \\\"address\\\": \\\"1210 Haro St\\\",\\n\" \\\n\t\t\t\t\t\t \" \\\"name\\\": \\\"Mike\\\",\\n\" \\\n\t\t\t\t\t\t \" \\\"phone_number\\\": \\\"6047151111\\\"\\n\" \\\n\t\t\t\t\t\t \" },\\n\" \\\n\t\t\t\t\t\t \" {\\n\" \\\n\t\t\t\t\t\t \" \\\"address\\\": \\\"798 Davie Street \\\",\\n\" \\\n\t\t\t\t\t\t \" \\\"name\\\": \\\"Lily\\\",\\n\" \\\n\t\t\t\t\t\t \" \\\"phone_number\\\": \\\"6047152222\\\"\\n\" \\\n\t\t\t\t\t\t \" }\\n\" \\\n\t\t\t\t\t\t \" ]\\n\" \\\n\t\t\t\t\t\t \"}\"\n\t\tself.assertEqual(expectedOutput, output)\n\n\tdef test_JsonWriter_writes_blank_data(self):\n\t\toutput = self.jsonWriter.write(self.blankData)\n\t\texpectedOutput = \"{\\n\" \\\n\t\t\t\t\t\t \" \\\"personal_data\\\": [\\n\" \\\n\t\t\t\t\t\t \" {\\n\" \\\n\t\t\t\t\t\t \" \\\"address\\\": \\\"\\\",\\n\" \\\n\t\t\t\t\t\t \" \\\"name\\\": \\\"\\\",\\n\" \\\n\t\t\t\t\t\t \" \\\"phone_number\\\": \\\"\\\"\\n\" \\\n\t\t\t\t\t\t \" }\\n\" \\\n\t\t\t\t\t\t \" ]\\n\" \\\n\t\t\t\t\t\t \"}\"\n\t\tself.assertEqual(expectedOutput, output)\n\n\tdef test_TxtWriter_writes_no_data(self):\n\t\toutput = self.txtWriter.write(self.noData)\n\t\texpectedOutput = '========================================\\n'\n\t\tself.assertEqual(expectedOutput, output)\n\n\tdef test_TxtWriter_writes_single_data(self):\n\t\toutput = self.txtWriter.write(self.singleData)\n\t\texpectedOutput = \"========================================\\n\" \\\n\t\t\t\t\t\t \"Name=Lucy\\n\" \\\n\t\t\t\t\t\t \"Address=1010 Water Street \\n\" \\\n\t\t\t\t\t\t \"Phone Number=6047150000\\n\" \\\n\t\t\t\t\t\t \"========================================\\n\"\n\t\tself.assertEqual(expectedOutput, output)\n\n\tdef test_TxtWriter_writes_multiple_data(self):\n\t\toutput = self.txtWriter.write(self.multipleData)\n\t\texpectedOutput = \"========================================\\n\" \\\n\t\t\t\t\t\t \"Name=Mike\\n\" \\\n\t\t\t\t\t\t \"Address=1210 Haro St\\n\" \\\n\t\t\t\t\t\t \"Phone Number=6047151111\\n\" \\\n\t\t\t\t\t\t \"========================================\\n\" \\\n\t\t\t\t\t\t \"Name=Lily\\n\" \\\n\t\t\t\t\t\t \"Address=798 Davie Street \\n\" \\\n\t\t\t\t\t\t \"Phone Number=6047152222\\n\" \\\n\t\t\t\t\t\t \"========================================\\n\"\n\t\tself.assertEqual(expectedOutput, output)\n\n\tdef test_TxtWriter_writes_blank_data(self):\n\t\toutput = self.txtWriter.write(self.blankData)\n\t\texpectedOutput = \"========================================\\n\" \\\n\t\t\t\t\t\t \"Name=\\n\" \\\n\t\t\t\t\t\t \"Address=\\n\" \\\n\t\t\t\t\t\t \"Phone Number=\\n\" \\\n\t\t\t\t\t\t \"========================================\\n\"\n\t\tself.assertEqual(expectedOutput, output)\n\n\tdef test_HtmlWriter_writes_no_data(self):\n\t\toutput = self.htmlWriter.write(self.noData)\n\t\texpectedOutput = self.buildHtmlOutput(\"\")\n\t\tself.assertEqual(expectedOutput, output)\n\n\tdef test_HtmlWriter_writes_single_data(self):\n\t\toutput = self.htmlWriter.write(self.singleData)\n\t\trows = \"Lucy1010 Water Street 6047150000\"\n\t\texpectedOutput = self.buildHtmlOutput(rows)\n\t\tself.assertEqual(expectedOutput, output)\n\n\tdef test_HtmlWriter_writes_multiple_data(self):\n\t\toutput = self.htmlWriter.write(self.multipleData)\n\t\trows = \"Mike1210 Haro St6047151111\" \\\n\t\t\t \"Lily798 Davie Street 6047152222\"\n\t\texpectedOutput = self.buildHtmlOutput(rows)\n\t\tself.assertEqual(expectedOutput, output)\n\n\tdef test_HtmlWriter_writes_blank_data(self):\n\t\toutput = self.htmlWriter.write(self.blankData)\n\t\trows = \"\"\n\t\texpectedOutput = self.buildHtmlOutput(rows)\n\t\tself.assertEqual(expectedOutput, output)\n\n\tdef buildHtmlOutput(self, rows):\n\t\toutput = \"\" \\\n\t\t\t\t\t\"\"\n\t\toutput += rows\n\t\toutput += \"
NameAddressPhone Number
\"\n\t\treturn output\n\nif __name__ == '__main__':\n\tunittest.main()\n","sub_path":"unit_test/test_writer.py","file_name":"test_writer.py","file_ext":"py","file_size_in_byte":6293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"259434682","text":"########### IMPORTING THE REQURIED LIBRARIES ###########\n\nfrom __future__ import print_function\nfrom bs4 import BeautifulSoup as soup\nfrom random import choice\nfrom terminaltables import AsciiTable\nfrom .proxy import _proxy\nfrom .utils import *\nimport requests\n\n######## DECLARING THE CLASS FOR GETTING COVID-19 DATA ########\n\nclass Corona:\n\tproxy = _proxy()\n\n\t######## GETTING THE HTML PAGE THROUGH GET REQUEST ########\n\n\tdef getPageResponse( self, url ):\n\t\tpage = None\n\t\ttry:\n\t\t resp = requests.get( url, timeout = MAX_TIMEOUT )\n\t\t page = soup( resp.text, 'lxml' ) \n\t\texcept requests.ConnectionError:\n\t\t\tprint( \"\\n###### STARTING RANDOM PROXIES #######\\n\" );\n\t\t\tresp = self.proxy.loadDataByIPRotation( url )\n\t\t\tpage = soup( resp.text, 'lxml' )\n\n\t\treturn page\n\n\tdef extractCounts( self, page, choice = \"w\" ):\n\t\ttotal_cases = None\n\t\ttotal_deaths = None\n\t\ttotal_cured = None\n\n\t\tif( choice == \"w\" ):\n\t\t\ttotal_cases = page.findAll( \"div\", {\n\t\t\t\t\"id\": \"maincounter-wrap\"\n\t\t\t} )[ 0 ].div.text.strip()\n\n\t\t\ttotal_deaths = page.findAll( \"div\", {\n\t\t\t\t\"id\": \"maincounter-wrap\"\n\t\t\t} )[ 1 ].div.text.strip()\n\n\t\t\ttotal_cured = page.findAll( \"div\", {\n\t\t\t\t\"id\": \"maincounter-wrap\"\n\t\t\t} )[ 2 ].div.text.strip()\n\n\t\telif( choice == \"c\" ):\n\t\t\ttotal_cases = int( extractNumbers( page.findAll( \"div\",{\n\t\t\t\t\"class\": \"table-responsive\" \n\t\t\t} )[ 7 ].tbody.findAll( \"tr\" )[ -2 : -1 ][ 0 ].findAll( \"td\" )[ 1 ].text.strip() ) )\n\n\t\t\ttotal_cases += int( page.findAll( \"div\",{\n\t\t\t\t\"class\": \"table-responsive\" \n\t\t\t} )[ 7 ].tbody.findAll( \"tr\" )[ -2 : -1 ][ 0 ].findAll( \"td\" )[ 2 ].text.strip() )\n\n\t\t\ttotal_deaths = int( page.findAll( \"div\",{\n\t\t\t\t\"class\": \"table-responsive\" \n\t\t\t} )[ 7 ].tbody.findAll( \"tr\" )[ -2 : -1 ][ 0 ].findAll( \"td\" )[ 4 ].text.strip() )\n\n\t\t\ttotal_cured = int( page.findAll( \"div\",{\n\t\t\t\t\"class\": \"table-responsive\" \n\t\t\t} )[ 7 ].tbody.findAll( \"tr\" )[ -2 : -1 ][ 0 ].findAll( \"td\" )[ 3 ].text.strip() )\n\n\t\tcounts = AsciiTable( [ \n\t\t\t[ \"Total Cases\", \"Total Deaths\", \"Total Cured\" ],\n\t\t\t[ total_cases, total_deaths, total_cured ]\n\t\t] )\n\t\treturn counts\n\n\t########## EXTRACTING THE TABLE ###########\n\n\tdef extractTableData( self, page, choice = \"w\" ):\n\t\ttable = None\n\t\ttable_heading = None\n\t\ttable_content = None\n\n\t\tif choice == \"w\":\n\t\t\ttry:\n\t\t\t\ttable = page.find( \"table\",{\n\t\t\t\t \"id\": \"main_table_countries_today\" \n\t\t\t\t} )\n\n\t\t\t\t# table_heading = [ item.text.strip() for item in table.thead.tr if item != \"\\n\" ]\n\n\t\t\t\ttable_heading = [ \"Country\", \"Confirmed\\nCases\", \"New Cases\", \"Confirmed\\nDeaths\", \"New Deaths\", \"Recovered\", \"Active cases\", \"Serious/\\nCritical cases\" ];\n\n\t\t\t\ttable_content = []\n\t\t\t\tfor rows in table.tbody:\n\t\t\t\t data = [ item.text.strip() for item in rows if item != \"\\n\" ]\n\t\t\t\t if data:\n\t\t\t\t table_content.append( data[ : -2 ] )\n\n\t\t\t\ttable_content.insert( 0, table_heading )\n\t\t\t\ttable = AsciiTable( table_content )\n\t\t\texcept:\n\t\t\t\tprint( \"\\nSource page format has changed.\" )\n\t\t\t\texit();\n\n\t\telif choice == \"c\":\n\t\t\ttry:\n\t\t\t\ttable = page.findAll( \"div\",{\n\t\t\t\t\t\"class\": \"table-responsive\" \n\t\t\t\t} )[ 7 ]\n\n\t\t\t\t# table_heading = [ item.text.strip() for item in table.thead.tr if item != \"\\n\" ]\n\n\t\t\t\ttable_heading = [ \"Sl. No.\", \"States/\\nUnion Territories\", \"Confirmed cases\\n( Indian National )\", \"Confirmed cases\\n( Foreign National )\", \"Cured/Discharged/\\nMigrated\", \"Death\" ];\n\n\t\t\t\ttable_content = []\n\t\t\t\tfor rows in table.tbody:\n\t\t\t\t data = [ item.text.strip() for item in rows if item != \"\\n\" ]\n\t\t\t\t if data:\n\t\t\t\t table_content.append( data )\n\n\t\t\t\ttable_content.insert( 0, table_heading )\n\t\t\t\ttable = AsciiTable( table_content[ : -2 ] )\n\t\t\texcept:\n\t\t\t\tprint( \"\\nSource page format has changed.\" )\n\t\t\t\texit();\n\t\treturn table\n\n","sub_path":"coronastat/corona.py","file_name":"corona.py","file_ext":"py","file_size_in_byte":3647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"346699846","text":"import numpy as np\nclass Event():\n '''\n Store all of the particles in an event.\n '''\n def __init__(self, particle_list):\n self.particles = particle_list\n self.n_particles = len(self.particles)\n\n def get_ring_coordinates(self):\n '''\n Return the ring coordinates for this event as two numpy arrays:\n pTs and phis (in that order). \n '''\n pts, phis = [], [] \n for particle in self.particles: \n phis.append( particle.phi )\n pts.append( particle.pt )\n return np.array(pts), np.array(phis)\n\n def get_cylinder_coordinates(self):\n '''\n Return the cylinder coordinates for this event as three numpy arrays:\n pTs, phis and etas (in that order). \n '''\n pts, phis = self.get_ring_coordinates()\n etas = [x.eta for x in self.particles]\n return pts, phis, np.array(etas)\n\n\n","sub_path":"ExampleGenerator/Event.py","file_name":"Event.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"641571690","text":"import actionlib\nimport control_msgs.msg\nimport pr2_controllers_msgs.msg\nimport rospy\n\nfrom ...model import RotationalJoint\nfrom .move_base import ROSRobotMoveBaseInterface\n\n\nclass PR2ROSRobotInterface(ROSRobotMoveBaseInterface):\n\n \"\"\"pr2 robot interface.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super(PR2ROSRobotInterface, self).__init__(*args, **kwargs)\n\n self.gripper_states = dict(larm=None, rarm=None)\n rospy.Subscriber('/r_gripper_controller/state',\n pr2_controllers_msgs.msg.JointControllerState,\n lambda msg: self.pr2_gripper_state_callback(\n 'rarm', msg))\n rospy.Subscriber('/l_gripper_controller/state',\n pr2_controllers_msgs.msg.JointControllerState,\n lambda msg: self.pr2_gripper_state_callback(\n 'larm', msg))\n\n self.l_gripper_action = actionlib.SimpleActionClient(\n \"/l_gripper_controller/gripper_action\",\n pr2_controllers_msgs.msg.Pr2GripperCommandAction)\n self.r_gripper_action = actionlib.SimpleActionClient(\n \"/r_gripper_controller/gripper_action\",\n pr2_controllers_msgs.msg.Pr2GripperCommandAction)\n for action in [self.l_gripper_action, self.r_gripper_action]:\n if not (self.joint_action_enable and action.wait_for_server(\n rospy.Duration(3))):\n self.joint_action_enable = False\n rospy.logwarn(\n '{} is not respond, PR2ROSRobotInterface is disabled')\n break\n\n self.ignore_joint_list = ['laser_tilt_mount_joint', ]\n\n def wait_interpolation(self, controller_type=None, timeout=0):\n \"\"\"Overwrite wait_interpolation\n\n Overwrite for pr2 because some joint is still moving after joint-\n trajectory-action stops.\n\n Parameters\n ----------\n controller_type : None or string\n controller to be wait\n timeout : float\n max time of for waiting\n\n Returns\n -------\n return values are a list of is_interpolating for all controllers.\n if all interpolation has stopped, return True.\n\n \"\"\"\n super(PR2ROSRobotInterface, self).wait_interpolation(\n controller_type, timeout)\n while not rospy.is_shutdown():\n self.update_robot_state(wait_until_update=True)\n if all(map(lambda j: j.name in self.ignore_joint_list\n or abs(j.joint_velocity) < 0.05\n if isinstance(j, RotationalJoint) else\n abs(j.joint_velocity) < 0.001,\n self.robot.joint_list)):\n break\n # TODO(Fix return value)\n return True\n\n @property\n def larm_controller(self):\n return dict(\n controller_type='larm_controller',\n controller_action='l_arm_controller/follow_joint_trajectory',\n controller_state='l_arm_controller/state',\n action_type=control_msgs.msg.FollowJointTrajectoryAction,\n joint_names=['l_shoulder_pan_joint',\n 'l_shoulder_lift_joint',\n 'l_upper_arm_roll_joint',\n 'l_elbow_flex_joint',\n 'l_forearm_roll_joint',\n 'l_wrist_flex_joint',\n 'l_wrist_roll_joint'])\n\n @property\n def rarm_controller(self):\n return dict(\n controller_type='rarm_controller',\n controller_action='r_arm_controller/follow_joint_trajectory',\n controller_state='r_arm_controller/state',\n action_type=control_msgs.msg.FollowJointTrajectoryAction,\n joint_names=['r_shoulder_pan_joint',\n 'r_shoulder_lift_joint',\n 'r_upper_arm_roll_joint',\n 'r_elbow_flex_joint',\n 'r_forearm_roll_joint',\n 'r_wrist_flex_joint',\n 'r_wrist_roll_joint'])\n\n @property\n def head_controller(self):\n return dict(\n controller_type='head_controller',\n controller_action='head_traj_controller/follow_joint_trajectory',\n controller_state='head_traj_controller/state',\n action_type=control_msgs.msg.FollowJointTrajectoryAction,\n joint_names=['head_pan_joint', 'head_tilt_joint'])\n\n @property\n def torso_controller(self):\n return dict(\n controller_type='torso_controller',\n controller_action='torso_controller/follow_joint_trajectory',\n controller_state='torso_controller/state',\n action_type=control_msgs.msg.FollowJointTrajectoryAction,\n joint_names=['torso_lift_joint'])\n\n def move_gripper(self, arm, pos, effort=25,\n wait=True,\n ignore_stall=False):\n \"\"\"Move gripper function\n\n Parameters\n ----------\n arm : str\n can take 'larm', 'rarm', 'arms'\n pos : float\n position of gripper.\n if pos is 0.0, gripper closed.\n effort : float\n effort of grasp.\n wait : bool\n if wait is True, wait until gripper action ends.\n \"\"\"\n if arm == 'larm':\n action_clients = [self.l_gripper_action]\n elif arm == 'rarm':\n action_clients = [self.r_gripper_action]\n elif arm == 'arms':\n action_clients = [self.l_gripper_action,\n self.r_gripper_action]\n else:\n return\n for action_client in action_clients:\n goal = pr2_controllers_msgs.msg.Pr2GripperCommandActionGoal()\n goal.goal.command.position = pos\n goal.goal.command.max_effort = effort\n action_client.send_goal(goal.goal)\n results = []\n if wait:\n for action_client in action_clients:\n results.append(action_client.wait_for_result())\n return results\n\n def pr2_gripper_state_callback(self, arm, msg):\n self.gripper_states[arm] = msg\n\n def default_controller(self):\n \"\"\"Overriding default_controller.\n\n Returns\n -------\n List of limb controller : list\n \"\"\"\n return [self.larm_controller,\n self.rarm_controller,\n self.head_controller,\n self.torso_controller]\n","sub_path":"skrobot/interfaces/ros/pr2.py","file_name":"pr2.py","file_ext":"py","file_size_in_byte":6540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"338536851","text":"import web\nimport os.path # for template rendering relative pathing\nurls = (\n '/', 'index',\n '/noble', 'redeemer'\n\n )\n\napp = web.application(urls, globals())\napp = app.wsgifunc()\n\n\nroot = os.path.dirname(__file__)\nrender = web.template.render(os.path.join(root, 'templates/'),base='layout') #\nclass redeemer(object):\n def GET(self):\n greeting = 'hello'\n return render.index(greeting = greeting)\n\nclass index(object):\n def GET(self): #absent this return attribute name error\n return render.hello_form()\n def POST(self):\n form = web.input(name=\"Nobody\", greet=\"Hello\")\n greeting = \"%s, %s \" % (form.greet, form.name)\n return render.foo(greeting = greeting)\n\nif __name__ == \"__main__\": # absent this: AttributeError: 'function' object has no attribute 'run'\n app.run()\n\n","sub_path":"ex50lpthw/gothonweb/bin/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"626973651","text":"#!/usr/bin/env python\nfrom functools import singledispatch\n\n@singledispatch\ndef spam(arg):\n raise TypeError(\"spam() called with invalid arg type\")\n\n@spam.register\ndef wombat(arg: int):\n print(\"Got an int\")\n\n@spam.register(str)\ndef _(arg):\n print(\"Got a string\")\n\nspam(5)\nspam(\"foo\")\ntry:\n spam(1.2)\nexcept:\n print(\"oops\")\n","sub_path":"single_dispatch_simple.py","file_name":"single_dispatch_simple.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"485205673","text":"\"\"\"\nScript to connect to MySQL and add a record to the database\n\"\"\"\n\nimport os\nimport sys\nimport transaction\n\nfrom sqlalchemy import engine_from_config\n\nfrom pyramid.paster import (\n get_appsettings,\n setup_logging,\n )\n\nfrom pyramid.scripts.common import parse_vars\n\nfrom ..models import (\n Base,\n DBSession,\n)\nfrom ..models.person import Person\n\nusage_msg = \"\"\"usage: {cmd} config-uri [var=value]\n Example: {cmd} development.ini create_tables=True\n create_tables=True: create and populate DB tables\"\"\"\n\n\ndef usage(argv):\n cmd = os.path.basename(argv[0])\n print(usage_msg.format(cmd=cmd))\n sys.exit(1)\n\n\ndef main(argv=sys.argv):\n if len(argv) < 2:\n usage(argv)\n print(\"Running {} with {}\".format(os.path.basename(argv[0]), argv[1]))\n config_uri = argv[1]\n options = parse_vars(argv[2:])\n setup_logging(config_uri)\n settings = get_appsettings(config_uri, options=options)\n engine = engine_from_config(settings, 'sqlalchemy.')\n DBSession.configure(bind=engine)\n if options.get('create_tables'):\n Base.metadata.create_all(engine)\n with transaction.manager:\n model = Person(\n first_name=\"John\",\n middles=\"William\",\n last_name=\"Coltrane\",\n email=\"john.coltrane@gmail.com\",\n street=\"342 W 12th St Apt 3C\",\n city=\"New York\",\n state=\"NY\",\n country=\"USA\",\n post_code=\"10012\"\n )\n DBSession.add(model)\n print(\"Added Person '{model.name}'\".format(model=model))\n model = Person(\n first_name=\"Alfred\",\n middles=\"McCoy\",\n last_name=\"Tyner\",\n email=\"mccoy.tyner@gmail.com\",\n street=\"342 W 12th St 3D\",\n city=\"New York\",\n state=\"NY\",\n country=\"USA\",\n post_code=\"10012\"\n )\n DBSession.add(model)\n print(\"Added Person '{model.name}'\".format(model=model))\n","sub_path":"exercises/ticketmanor_webapp/ticketmanor/scripts/initializedb.py","file_name":"initializedb.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"367650108","text":"from sentence_implement import SentenceImplement\n\n\nclass Cmd:\n \"\"\"\n Command line witch get the text from the user and print the search result\n \"\"\"\n def __init__(self):\n self.__sentence_treatment = SentenceImplement()\n self.__sentence = \"\"\n\n def run_command(self, folder_path):\n print(\"Loading the files and preparing the program...\")\n self.__sentence_treatment.load_data(folder_path)\n print(\"The system is ready. Enter your text:\")\n while True:\n text = input()\n if text == '#':\n self.__sentence = \"\"\n print(\"Enter your text:\")\n continue\n self.__sentence += text\n try:\n value = self.__sentence_treatment.search(text, self.__sentence)\n if type(value) is str and value != \"\":\n print(value)\n print(self.__sentence, end='')\n elif not value:\n raise Exception(\"This sentence not found\")\n except Exception as error:\n print(error)\n print(\"Enter your text:\")\n self.__sentence = \"\"\n\n\n\n\n\n\n","sub_path":"cmd.py","file_name":"cmd.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"2266972","text":"\n\"\"\"\nЗадача 1.\nНапишите программу, которая запрашивает ввод двух значений.\nЕсли хотя бы одно из них не является числом, то должна выполняться конкатенация, т. е. соединение, строк.\nВ остальных случаях введенные числа суммируются.\n\"\"\"\nstring_one = input(\"Введите первую строку: \")\nstring_two = input(\"Введите вторую строку: \")\n\nif string_one.isdigit() is False or string_two.isdigit() is False:\n result = string_one + string_two\nelse:\n result = int(string_one) + int(string_two)\n\nprint(result)\n\n","sub_path":"Exc_7.py","file_name":"Exc_7.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"440155900","text":"x = [-5,-4,-3,2,3,4]\n\nmain =[]\npositive = []\nnegative = []\n\nfor i in x:\n if i>=0:\n positive.append(i)\n else:\n negative.append(i)\n\n\nfor i in negative:\n neg = i\n for i in range(len(positive)-2):\n num = positive[i]+positive[i+1]\n\n if neg + num == 0:\n main.append([neg,positive[i],positive[i+1]])\n\n\nprint(main)\n\n\n","sub_path":"threenum.py","file_name":"threenum.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"417340170","text":"'''\n@Description: \n@Version: 1.0\n@Autor: Henggao\n@Date: 2020-03-17 14:56:06\n@LastEditors: Henggao\n@LastEditTime: 2020-03-17 15:06:22\n'''\nimport pygal\n\nwm = pygal.maps.world.World()\nwm.title = \"Population of Countreis in North America\"\nwm.add('North America', {'ca': 24126000, 'us': 30934900, 'mx': 113423000})\n\nwm.render_to_file('na_populations.svg')\n","sub_path":"Pythonvisual/na_populations.py","file_name":"na_populations.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"415652185","text":"\"\"\"main module for Dungeon Game\n\"\"\"\nimport exceptions\n\nfrom game_logger import log_debug\nfrom game_logger import log_info\n\nimport terrain\nimport game\n\ndebug_mode = False\n\nlog_info(\"Welcome to the game!\")\n\ngame_session = None\n\nwhile True:\n\n log_info(\"Type \\\"new\\\" to start new game\")\n log_info(\"Type \\\"load\\\" to load saved game\")\n log_info(\"Type \\\"debug\\\" to enter debug mode\")\n\n try:\n command = input()\n\n if command == \"new\":\n\n try:\n\n scale = int(input(\"Enter map scale: \"))\n\n if (scale < 1):\n raise exceptions.TerrainGenerationError(scale)\n\n except exceptions.TerrainGenerationError as instance:\n log_info(instance)\n continue\n \n except ValueError:\n log_info(F\"Entered scale is not an integer: {scale}\")\n continue\n\n game_session = game.GameSession(3, 3, int(scale))\n log_debug(\"new game created\")\n break\n\n elif command == \"load\":\n\n game_session = game.GameSession(0, 0, 1)\n if game_session.load():\n break\n\n elif command == \"debug\":\n\n if debug_mode:\n log_info(\"Already in debug mode\")\n\n else:\n\n debug_mode = True\n log_info(\"Game is run in debug mode\")\n\n else:\n raise exceptions.MenuCommandError(command)\n\n except exceptions.MenuCommandError as instance:\n log_info(instance)\n\ntry:\n game_session.run()\n\nexcept AttributeError:\n log_info(\"Game was not initialized. Ending\")\n","sub_path":"Oleksandr_Kotov/9/main_loop.py","file_name":"main_loop.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"343531158","text":"import cv2\nimport numpy as np\n\n\ndef salt(img, n):\n for k in range(n):\n i = int(np.random.random() * img.shape[1]);\n j = int(np.random.random() * img.shape[0]);\n if img.ndim == 2:\n img[j, i] = 255\n elif img.ndim == 3:\n img[j, i, 0] = 255\n img[j, i, 1] = 255\n img[j, i, 2] = 255\n return img\n\n\nif __name__ == '__main__':\n img = cv2.imread(\"test.jpg\")\n # saltImage = salt(img, 500)\n\n # cv2.imshow(\"Salt\", saltImage)\n # grayImg = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n # print(grayImg.ndim)\n b = cv2.split(img)[0]\n g = cv2.split(img)[1]\n r = cv2.split(img)[2]\n cv2.imshow(\"b\", b)\n cv2.imshow(\"g\", g)\n cv2.imshow(\"r\", r)\n\n merged = cv2.merge([b,g,r])\n cv2.imshow(\"merged\", merged)\n\n\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n","sub_path":"cy_cv/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"194677928","text":"import time\r\nimport random\r\nimport os\r\nimport csv\r\n\r\n\r\nlist1 = [0, 1]\r\nlist2 = [0, 1]\r\n\r\n\r\nscore = 0\r\nnum1 = 0\r\nnum2 = 0\r\nproduct = 0\r\nlevel = 1\r\n\r\n\r\ndef times():\r\n num1 = (random.choice(list1))\r\n num2 = (random.choice(list2))\r\n product = num1 * num2\r\n answer = input(\"What is \" + str(num1) + \" x \" + str(num2) + \"?\\n\")\r\n if answer == str(product):\r\n print (\"\\nCorrect\\n\")\r\n global score\r\n score = score+1\r\n if score > 1:\r\n global level\r\n level= level+1\r\n # write to file at this point clarify column based on level\r\n\r\ndef divide():\r\n num1 = (random.choice(list1))\r\n num2 = (random.choice(list2))\r\n product = num1 * num2\r\n answer = input(\"What is \" + str(product) + \" / \" + str(num1) + \"?\\n\")\r\n if answer == str(num2):\r\n print (\"\\nCorrect\\n\")\r\n global score\r\n score = score+1\r\n \r\n\r\n\r\nprint (\"Welcome to the times table challenge\")\r\nname = input (\"What is your first name?\\n\")\r\nsurname = input (\"What is your last name?\\n\")\r\nyear = input(\"What year are you in?\\n(please type a number)\\n\")\r\n# Check whether file exists at this point\r\n# Create file csv? at this point (Date reference)\r\n# Add the name, year etc at this point to file\r\n\r\nif not os.path.isfile('C:\\\\Users\\\\scorefile.csv'):\r\n print (\"New score file being created...\\n\\n\")\r\n f = open('file.csv','w')\r\n a = (str(name) + \",\" + str(surname) + \",\" + str(year))\r\n f.write(str(a))\r\n f.close()\r\n \r\n \r\n\r\nif level == 1:\r\n print (\"Level - \" + str(level) + \"\\n\")\r\n score = 0\r\n for i in range(2):\r\n times()\r\n\r\nif level == 2:\r\n print (\"Level - \" + str(level) + \"\\n\")\r\n score = 0\r\n list1 = [3, 3]\r\n list2 = [3, 3]\r\n for i in range(2):\r\n times()\r\n\r\nif level == 3:\r\n print (\"Level - \" + str(level) + \"\\n\")\r\n score = 0\r\n list1 = [7]\r\n list2 = [7]\r\n for i in range(2):\r\n times()\r\n divide()\r\n times()\r\n\r\nif level == 4:\r\n print (\"Level - \" + str(level) + \"\\n\")\r\n score = 0\r\n list1 = [6]\r\n list2 = [6]\r\n for i in range(2):\r\n times()\r\n divide()\r\n times()\r\n divide()\r\n\r\n \r\nprint (\"Congratulations on completing the times table challenge\\n\")\r\nprint (\"You reached level...\\n\\n\")\r\nprint (str(level))\r\n","sub_path":"time table function.py","file_name":"time table function.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"475083982","text":"# -*- encoding: utf-8 -*-\n#\n# Copyright 2015-2016 Telefónica Investigación y Desarrollo, S.A.U\n#\n# This file is part of FI-WARE 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#\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, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# For those usages not covered by the Apache version 2.0 License please\n# contact with opensource@tid.es\n#\n\n# Import flask dependencies\nfrom flask import abort, Response\n\nfrom fiwareglancesync.app.settings.settings import logger_api\nfrom functools import wraps\nfrom fiwareglancesync.app.mod_auth.AuthorizationManager import AuthorizationManager\nimport requests\nimport json\nimport httplib\nfrom fiwareglancesync.app.settings.settings import KEYSTONE_URL, AUTH_API_V2, AUTH_API_V3, REGION_LIST_API_V3, \\\n ADM_USER, ADM_PASS, ADM_TENANT_ID, ADM_TENANT_NAME, USER_DOMAIN_NAME, X_AUTH_TOKEN_HEADER\n\n\nclass region():\n regions = []\n ERROR_MESSAGE = '''\n {\n \"error\": {\n \"message\": \"Bad region\",\n \"code\": \"%s\"\n }\n }\n ''' % str(httplib.BAD_REQUEST)\n\n def __init__(self):\n \"\"\"\n Contructor of the class region\n \"\"\"\n # Get the region list\n # GET http://cloud.lab.fiware.org:4730/v3/OS-EP-FILTER/endpoint_groups\n\n if not self.regions:\n keystone_url = KEYSTONE_URL + '/' + AUTH_API_V2\n\n a = AuthorizationManager(identity_url=keystone_url, api_version=AUTH_API_V2)\n\n # Get the Admin token to validate the access_token\n adm_token = a.get_auth_token(username=ADM_USER, password=ADM_PASS, tenant_id=ADM_TENANT_ID,\n tenant_name=ADM_TENANT_NAME,\n user_domain_name=USER_DOMAIN_NAME)\n\n s = requests.Session()\n s.headers.update({X_AUTH_TOKEN_HEADER: adm_token})\n\n keystone_url = KEYSTONE_URL + '/' + AUTH_API_V3 + '/' + REGION_LIST_API_V3\n response = s.get(keystone_url)\n\n r = json.loads(response.text)\n\n endpoint_groups = r['endpoint_groups']\n\n for i in range(0, len(endpoint_groups)):\n # If the specific endpoint_groups has not a filters, it is not a correct\n # region and we discard it.\n region_filter = endpoint_groups[i]['filters']\n if region_filter and 'region_id' in region_filter:\n self.regions.append(region_filter['region_id'])\n\n logger_api.debug(self.regions)\n\n def validate_region(self, region_name):\n \"\"\"\n Validate if region_name is a name that can be found\n in the Keystone component.\n :param region_name: The name of the region.\n :return: True if it is correct or false otherwise.\n \"\"\"\n return region_name in self.regions\n\n\ndef check_region(func):\n \"\"\"\n Decorator that checks that requested region is a real region\n that exists in keystone.\n\n Usage:\n @app.route(\"/\")\n @check_region\n def secured_root(token=None):\n pass\n\n :param func: Function to return the process\n :return: The call to the function .\n \"\"\"\n\n @wraps(func)\n def _wrap(*args, **kwargs):\n region_name = kwargs['regionid']\n\n region_management = region()\n\n logger_api.info(\"Checking region: {}...\".format(region_name))\n\n result = region_management.validate_region(region_name)\n\n if result:\n return func(*args, **kwargs)\n else:\n abort(httplib.BAD_REQUEST, \"Invalid region \"+region_name)\n\n return _wrap\n","sub_path":"fiwareglancesync/app/mod_auth/region_manager.py","file_name":"region_manager.py","file_ext":"py","file_size_in_byte":4006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"19128409","text":"import unittest\nfrom time import sleep\n\nfrom selenium import webdriver\n\n\nclass Login(unittest.TestCase):\n\n def setUp(self):\n self.driver = webdriver.Chrome()\n\n # 窗口最大化\n self.driver.maximize_window()\n self.msg = '海贼王'\n self.url = 'http://www.baidu.com'\n\n def testSearch(self):\n \"\"\"\n test body\n :return:\n \"\"\"\n # open browser\n self.driver.get(self.url)\n sleep(2)\n # click search input\n self.driver.find_element_by_id('kw').click()\n sleep(2)\n\n # input value\n self.driver.find_element_by_id('kw').send_keys(self.msg)\n sleep(2)\n self.driver.find_element_by_id('su').click()\n sleep(2)\n\n def tearDown(self):\n self.driver.close()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"Auto_tata/UItest_selenium/webUI.py","file_name":"webUI.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"33564588","text":"from bs4 import BeautifulSoup\nimport requests\nimport urllib.request\nimport random\n\n\nclass AmazonProduct:\n def __init__(self, address):\n self.price = \"\"\n self.model_number = \"\"\n self.address = address\n self.entry_list = []\n self.headers = [\n {'User-Agent': 'Mozilla/5.0 (Linux; Android 5.1.1; LG-H345 Build/LMY47V) AppleWebKit/537.36 ' +\n '(KHTML, like Gecko) Chrome/43.0.2357.78 Mobile Safari/537.36 OPR/30.0.1856.93524'},\n ]\n\n self.req = urllib.request.Request(self.address,\n data=None,\n headers=self.headers[(random.randint(0, len(self.headers) - 1))])\n\n self.data = urllib.request.urlopen(self.address).read()\n\n def retrieve_item_model(self):\n try:\n soup = BeautifulSoup(self.data, \"lxml\")\n for number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:\n for row in soup.find_all(id='productDetails_techSpec_section_' + str(number)):\n for tr in row.find_all('tr'):\n self.entry_list.append(tr.text.strip())\n\n for row in soup.find_all(id='productDetails_detailBullets_sections1'):\n for tr in row.find_all('tr'):\n self.entry_list.append(tr.text.strip())\n for x in self.entry_list:\n if \"Item model number\" in x:\n self.model_number = x[17:].strip()\n\n except AttributeError:\n self.model_number = None\n\n except requests.HTTPError as e:\n print(\"From Amazon\", e)\n\n def retrieve_item_price(self):\n if self.model_number is None:\n return\n soup = BeautifulSoup(self.data, \"lxml\")\n self.price = soup.find(id='priceblock_ourprice').text.strip()\n return\n","sub_path":"amazon_scraper/amazon_scraper.py","file_name":"amazon_scraper.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"646336330","text":"from copy import copy\n\nfrom django import forms\nfrom django.db.models import get_model\nfrom django.template.defaultfilters import slugify\nfrom django.utils.translation import ugettext_lazy as _\n\nFancyPage = get_model('fancypages', 'FancyPage')\nPageType = get_model('fancypages', 'PageType')\nPageGroup = get_model('fancypages', 'PageGroup')\n\nDATE_FORMAT = '%d-%m-%Y'\n\n\nclass PageFormMixin(object):\n FIELDS = [\n 'name',\n 'description',\n 'image',\n 'keywords',\n 'page_type',\n 'status',\n 'date_visible_start',\n 'date_visible_end',\n 'groups'\n ]\n\n def update_field_order(self):\n # we need to specify the key order here because 'description' and\n # 'image' are non-model fields that cause an error when added\n # to the metaclass field attribute below\n self.fields.keyOrder = self.FIELDS\n\n def set_field_choices(self):\n if 'page_type' in self.fields:\n self.fields['page_type'].queryset = PageType.objects.all()\n if 'groups' in self.fields:\n self.fields['groups'].queryset = \\\n PageGroup.objects.all()\n\n\nclass PageForm(PageFormMixin, forms.ModelForm):\n image = forms.ImageField(required=False)\n page_type = forms.ModelChoiceField(PageType.objects.none(), required=False)\n date_visible_start = forms.DateTimeField(\n widget=forms.DateInput(format=DATE_FORMAT),\n input_formats=[DATE_FORMAT],\n required=False\n )\n date_visible_end = forms.DateTimeField(\n widget=forms.DateInput(format=DATE_FORMAT),\n input_formats=[DATE_FORMAT],\n required=False\n )\n groups = forms.ModelMultipleChoiceField(\n PageGroup.objects.none(),\n widget=forms.CheckboxSelectMultiple(),\n required=False\n )\n\n def __init__(self, *args, **kwargs):\n super(PageForm, self).__init__(*args, **kwargs)\n self.set_field_choices()\n self.update_field_order()\n\n class Meta:\n model = FancyPage\n fields = PageFormMixin.FIELDS\n\n\nclass PageCreateForm(PageFormMixin, forms.ModelForm):\n image = forms.ImageField(required=False)\n page_type = forms.ModelChoiceField(PageType.objects.none(), required=False)\n date_visible_start = forms.DateTimeField(\n widget=forms.DateInput(format=DATE_FORMAT),\n input_formats=[DATE_FORMAT],\n required=False\n )\n date_visible_end = forms.DateTimeField(\n widget=forms.DateInput(format=DATE_FORMAT),\n input_formats=[DATE_FORMAT],\n required=False\n )\n groups = forms.ModelMultipleChoiceField(\n PageGroup.objects.none(),\n widget=forms.CheckboxSelectMultiple(),\n required=False\n )\n\n def __init__(self, *args, **kwargs):\n parent_id = kwargs.pop('parent_pk', None)\n super(PageCreateForm, self).__init__(*args, **kwargs)\n try:\n self.parent = FancyPage.objects.get(id=parent_id)\n except FancyPage.DoesNotExist:\n self.parent = None\n self.set_field_choices()\n self.update_field_order()\n\n def clean_name(self):\n name = self.cleaned_data.get('name')\n try:\n FancyPage.objects.get(slug=slugify(name))\n except FancyPage.DoesNotExist:\n pass\n else:\n raise forms.ValidationError(\n _(\"A page with this title already exists\")\n )\n return name\n\n def save(self, *args, **kwargs):\n page_kwargs = copy(self.cleaned_data)\n page_kwargs.pop('groups')\n if self.parent:\n return self.parent.add_child(**page_kwargs)\n return FancyPage.add_root(**page_kwargs)\n\n class Meta:\n model = FancyPage\n fields = PageFormMixin.FIELDS\n\n\nclass BlockUpdateSelectForm(forms.Form):\n block_code = forms.ChoiceField(label=_(\"Edit block:\"))\n\n def __init__(self, container, *args, **kwargs):\n super(BlockUpdateSelectForm, self).__init__(*args, **kwargs)\n\n block_choices = []\n for block in container.blocks.select_subclasses():\n block_choices.append((block.id, unicode(block)))\n\n self.fields['block_code'].choices = block_choices\n\n\nclass BlockForm(forms.ModelForm):\n template_name = \"fancypages/partials/editor_form_fields.html\"\n\n class Meta:\n exclude = ('container',)\n widgets = {\n 'display_order': forms.HiddenInput()\n }\n\n\nclass TextBlockForm(BlockForm):\n class Meta:\n exclude = ('container',)\n widgets = {\n 'display_order': forms.HiddenInput(),\n 'text': forms.Textarea(attrs={'cols': 80, 'rows': 10}),\n }\n\n\nclass TitleTextBlockForm(BlockForm):\n class Meta:\n exclude = ('container',)\n widgets = {\n 'display_order': forms.HiddenInput(),\n 'text': forms.Textarea(attrs={'cols': 80, 'rows': 10}),\n }\n\n\nclass TwoColumnLayoutBlockForm(BlockForm):\n left_width = forms.IntegerField(\n widget=forms.TextInput(attrs={\n 'data-min': 1,\n # the max value is restricted to '11' in JS but we need the actual\n # max value there so this is the way to pass it through\n 'data-max': 12,\n }),\n label=_(\"Proportion of columns\")\n )\n\n\nclass TabBlockForm(BlockForm):\n\n def __init__(self, *args, **kwargs):\n super(TabBlockForm, self).__init__(*args, **kwargs)\n instance = kwargs['instance']\n if instance:\n for tab in instance.tabs.all():\n field_name = \"tab_title_%d\" % tab.id\n self.fields[field_name] = forms.CharField()\n self.fields[field_name].initial = tab.title\n self.fields[field_name].label = _(\"Tab title\")\n\n def save(self):\n instance = super(TabBlockForm, self).save()\n\n for tab in instance.tabs.all():\n field_name = \"tab_title_%d\" % tab.id\n tab.title = self.cleaned_data[field_name]\n tab.save()\n\n return instance\n","sub_path":"fancypages/dashboard/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":5997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"317337564","text":"import pygame\r\nfrom pygame.locals import *\r\nfrom weatherAPI import *\r\nimport random\r\nimport math\r\n\r\nclass Player(pygame.sprite.Sprite):\r\n def __init__(self):\r\n super(Player, self). __init__()\r\n \r\n self.xvelocity = 0\r\n self.yvelocity = 0\r\n self.frame = 0\r\n self.frames = [pygame.image.load('mjordan1.png').convert(), pygame.image.load('mjordan2.png').convert(), pygame.image.load('mjordan.png').convert()]\r\n self.image = self.frames[2]\r\n self.image.set_colorkey((153, 217, 234), RLEACCEL)\r\n self.rect = pygame.Rect((10, 500),(self.image.get_rect()[2],self.image.get_rect()[3])) \r\n self.start = True\r\n def update(self, pressed_keys, time, intro):\r\n #if pressed_keys[K_UP]:\r\n #self.yvelocity=-10\r\n #if pressed_keys[K_DOWN]:\r\n #self.rect.move_ip(0, 1)\r\n self.time = time%(60*.5)\r\n if self.time == 0 and intro == True:\r\n \r\n \r\n self.image = self.frames[self.frame%2]\r\n self.image.set_colorkey((153, 217, 234), RLEACCEL)\r\n self.rect = pygame.Rect((self.rect.left,self.rect.top),(self.image.get_rect()[2],self.image.get_rect()[3]))\r\n self.frame += 1\r\n \r\n elif intro == False and self.start:\r\n self.image = self.frames[2]\r\n self.image.set_colorkey((153, 217, 234), RLEACCEL)\r\n self.rect = pygame.Rect((self.rect.left,self.rect.top),(self.image.get_rect()[2],self.image.get_rect()[3]))\r\n self.start = False\r\n\r\n new_cloud = Cloud(\"grey\")\r\n clouds.add(new_cloud)\r\n all_sprites.add(new_cloud)\r\n new_cloud = Cloud(\"grey\")\r\n clouds.add(new_cloud)\r\n all_sprites.add(new_cloud)\r\n new_cloud = Cloud(\"grey\")\r\n clouds.add(new_cloud)\r\n all_sprites.add(new_cloud)\r\n new_cloud = Cloud(\"grey\")\r\n clouds.add(new_cloud)\r\n all_sprites.add(new_cloud)\r\n \r\n \r\n if pressed_keys[K_RIGHT]:\r\n self.xvelocity=10\r\n if pressed_keys[K_LEFT]:\r\n self.xvelocity= -10\r\n \r\n \r\n\r\n if self.rect.left < 0:\r\n self.rect.left = 0\r\n elif self.rect.right > 800-player.rect.width/2:\r\n self.rect.right = 800-player.rect.width/2\r\n if self.rect.top <= 0:\r\n self.rect.top = 0\r\n elif self.rect.bottom >= 600:\r\n self.rect.bottom = 600\r\n self.yvelocity=0\r\n\r\n self.rect.move_ip(self.xvelocity, self.yvelocity)\r\n self.xvelocity *= 0.8\r\n if self.xvelocity < 1:\r\n self.xvelocity = 0\r\n self.yvelocity+=1\r\n\r\n if intro == True:\r\n self.xvelocity = 10\r\n \r\n\r\nclass Cloud(pygame.sprite.Sprite):\r\n def __init__(self, color):\r\n super(Cloud, self).__init__()\r\n if color == \"grey\":\r\n self.image = pygame.image.load('rsz_greycloud.png').convert_alpha()\r\n\r\n else:\r\n self.image.load('rsz_whitecloud.png').convert_alpha()\r\n\r\n self.image.set_colorkey((0, 0, 0), RLEACCEL)\r\n self.rect = self.image.get_rect(\r\n center=(random.randint(820, 900), random.randint(lastCloud-100,600))\r\n )\r\n def update(self):\r\n self.rect.move_ip(cloudSpeed, 0)\r\n if self.rect.right < 0:\r\n self.kill()\r\n\r\nclass Rain(pygame.sprite.Sprite):\r\n def __init__(self):\r\n super(Rain, self).__init__()\r\n self.image = pygame.image.load('raindrop.jpg').convert_alpha()\r\n\r\n self.image.set_colorkey((0,0,0), RLEACCEL)\r\n self.rect = self.image.get_rect(\r\n center = (random.randint(0, 800), random.randint(100,200))\r\n )\r\n def update(self):\r\n self.rect.move_ip(0, 1)\r\n if self.rect.top > 600:\r\n self.kill()\r\n \r\n \r\n \r\n \r\ndisplay_width = 800\r\ndisplay_height = 600\r\n\r\npygame.init()\r\n\r\nscreen = pygame.display.set_mode((display_width,display_height))\r\n\r\nplayer = Player()\r\n\r\nbackground = pygame.Surface(screen.get_size())\r\nbackground.fill((135, 206, 250))\r\n\r\nintroBackground = pygame.image.load('NBAcourtfixed.png').convert_alpha()\r\nexitBackground = pygame.image.load('lebronJames.png').convert_alpha()\r\nexitBackground1 = pygame.image.load('jordanexit.jpg').convert_alpha()\r\nexitBackground1 = pygame.transform.scale(exitBackground1, (800, 600))\r\nexitBackground2 = pygame.image.load('jordanvlebron.png').convert_alpha()\r\nexitBackground2 = pygame.transform.scale(exitBackground2, (800, 600))\r\n\r\nwelcome = True\r\nwhile welcome:\r\n \r\n introBackground1 = pygame.image.load('mjvlbj.jpg').convert_alpha()\r\n introBackground1 = pygame.transform.scale(introBackground1, (800, 600))\r\n screen.blit(introBackground1, (0,0))\r\n \r\n basicfont1 = pygame.font.SysFont('AzureoN', 50)\r\n text1 = basicfont1.render('Welcome to The Game', True, (255, 255, 255))\r\n textrect1 = text1.get_rect()\r\n textrect1.centerx = screen.get_rect().centerx\r\n textrect1.centery = screen.get_rect().centery - 115\r\n screen.blit(text1, textrect1)\r\n\r\n basicfont2 = pygame.font.SysFont('Quango', 50)\r\n text2 = basicfont2.render('(Press S to Begin)', True, (255, 255, 255))\r\n textrect2 = text2.get_rect()\r\n textrect2.centerx = screen.get_rect().centerx\r\n textrect2.centery = screen.get_rect().centery + 115\r\n screen.blit(text2, textrect2)\r\n \r\n\r\n basicfont3 = pygame.font.SysFont('Quango', 50)\r\n text3 = basicfont3.render('Michael Jordan Needs to Defend His Crown!', True, (255, 255, 255))\r\n textrect3 = text3.get_rect()\r\n textrect3.centerx = screen.get_rect().centerx\r\n textrect3.centery = screen.get_rect().centery - 20\r\n screen.blit(text3, textrect3)\r\n \r\n\r\n basicfont4 = pygame.font.SysFont('Quango', 50)\r\n text4 = basicfont4.render('Use Arrows to Control', True, (255, 255, 255))\r\n textrect4 = text4.get_rect()\r\n textrect4.centerx = screen.get_rect().centerx\r\n textrect4.centery = screen.get_rect().centery + 50\r\n screen.blit(text4, textrect4)\r\n pygame.display.flip()\r\n \r\n for event in pygame.event.get():\r\n if event.type == pygame.KEYDOWN:\r\n welcome = False\r\n\r\nplayers = pygame.sprite.Group()\r\nclouds = pygame.sprite.Group()\r\nraindrops = pygame.sprite.Group()\r\nall_sprites = pygame.sprite.Group()\r\nall_sprites.add(player)\r\n\r\nADDCLOUD = ''\r\nADDRAIN = ''\r\nADDGREYCLOUD = ''\r\n\r\nADDCLOUD = pygame.USEREVENT + 1\r\ncloud_time = 2500\r\npygame.time.set_timer(ADDCLOUD, cloud_time)\r\n\r\nADDRAINDROP = pygame.USEREVENT + 2\r\nraindrop_time = 10000\r\npygame.time.set_timer(ADDRAINDROP, raindrop_time)\r\n\r\n\r\n\r\nrainy_condition = [\"Drizzle\", \"Rain\", \"Rain Mist\", \"Rain Showers\", \"Thunderstorms and Rain\"]\r\n\r\ncloudy_conditions = [\"Partly Cloudy\", \"Scattered Cloud\", \"Mostly Cloudy\", \"Overcast\"]\r\n\r\n\r\n\r\nwc = getWeatherCondition(station_data)\r\n\r\n#if wc in rainy_condition:\r\n #raindrops = pygame.sprite.Group()\r\n\r\nif wc == cloudy_conditions[2] or wc == cloudy_conditions[3]:\r\n pygame.time.set_timer(ADDCLOUD, 500)\r\n background.fill((211, 211, 211))\r\n\r\nif wc in rainy_condition:\r\n ADDRAINDROP = pygame.USEREVENT + 3\r\n background.fill((211, 211, 211))\r\n\r\n ADDGREYCLOUD = pygame.USERVENT + 5\r\n pygame.time.set_timer(ADDGREYCLOUD, 100)\r\n\r\ntime = 0\r\n \r\n \r\nlevel = 1\r\n\r\nintro = True\r\nlastCloud = 500\r\nnew_cloud2 = Cloud(\"grey\")\r\nclouds.add(new_cloud2)\r\nall_sprites.add(new_cloud2)\r\nnew_cloud2.rect = new_cloud2.image.get_rect(center=(900, 550))\r\n \r\n\r\n\r\nrunning = True\r\n\r\nwhile running:\r\n pygame.time.Clock().tick(60)\r\n moveOnCloud = 1\r\n cloudSpeed = -2 * math.log(level + 1)/math.log(2)\r\n for event in pygame.event.get():\r\n if event.type == KEYDOWN:\r\n if event.key == K_ESCAPE:\r\n running = False\r\n print(\"escape\")\r\n elif event.type == QUIT:\r\n running = False\r\n print(\"Quit\")\r\n\r\n elif(event.type == ADDCLOUD and intro == False):\r\n new_cloud = Cloud(\"grey\")\r\n clouds.add(new_cloud)\r\n all_sprites.add(new_cloud)\r\n lastCloud = new_cloud.rect.y\r\n\r\n #elif event.type == ADDRAINDROP:\r\n #new_rain = Rain()\r\n #all_sprites.add(new_rain)\r\n #raindrops.add(new_rain)\r\n\r\n time += 1\r\n pressed_keys = pygame.key.get_pressed()\r\n for cloud in clouds:\r\n if (player.rect.bottom+15>cloud.rect.top and player.rect.bottom-15cloud.rect.left and player.rect.left=0):\r\n player.yvelocity=0\r\n if pressed_keys[K_UP]:\r\n player.yvelocity=-25\r\n\r\n player.rect.bottom=cloud.rect.top\r\n if moveOnCloud == 1:\r\n moveOnCloud = 0\r\n \r\n player.rect.move_ip(cloudSpeed,0)\r\n if player.rect.bottom>=599 and pressed_keys[K_UP]:\r\n player.yvelocity=-25\r\n player.rect.move_ip(0,-1)\r\n\r\n \r\n if intro == False:\r\n screen.blit(background,(0,0))\r\n\r\n \r\n player.update(pressed_keys, time, intro)\r\n \r\n clouds.update()\r\n\r\n if (time % 600) == 0:\r\n level += 1\r\n\r\n basicfont1 = pygame.font.SysFont(None, 48)\r\n text1 = basicfont1.render(\"Level \" + str(level), True, (0, 0, 0))\r\n screen.blit(text1, (25, 25))\r\n if wc in rainy_condition:\r\n raindrops.update()\r\n\r\n if player.rect.left > screen.get_width()/2 + 230 and intro==True:\r\n player.rect.move_ip(0,-50)\r\n if player.rect.top < 0:\r\n intro = False\r\n\r\n #screen.blit(player.surf, player.rect)\r\n\r\n #draw surf onto screen\r\n #screen.blit(surf, (400, 400))\r\n\r\n for entity in all_sprites:\r\n screen.blit(entity.image, entity.rect)\r\n\r\n if (player.rect.bottom > display_height):\r\n player.kill()\r\n killed = True\r\n running = False\r\n if intro == True:\r\n screen.blit(introBackground, (0, 0))\r\n screen.blit(player.image, player.rect)\r\n pygame.display.flip()\r\n\r\nwhile killed:\r\n basicfont = pygame.font.SysFont('AzureoN', 52)\r\n\r\n if level <= 8:\r\n screen.blit(exitBackground, (0, 0))\r\n pygame.time.Clock().tick(60)\r\n text = basicfont.render('I am the King Now MJ!', True, (255, 255,255))\r\n textrect = text.get_rect()\r\n textrect.centerx = 600\r\n textrect.centery = 50\r\n screen.blit(text, textrect)\r\n \r\n text = basicfont.render('Ha! Only Level ' + str(level) + '!', True, (255, 255,255))\r\n textrect = text.get_rect()\r\n textrect.centerx = 625\r\n textrect.centery = 90\r\n screen.blit(text, textrect)\r\n \r\n if level >= 9 and level < 14:\r\n screen.blit(exitBackground2, (0, 0))\r\n pygame.time.Clock().tick(60)\r\n text = basicfont.render('We Are Still Battling', True, (255, 255, 255))\r\n textrect = text.get_rect()\r\n textrect.centerx = 300\r\n textrect.centery = 50\r\n screen.blit(text, textrect)\r\n \r\n text = basicfont.render('Level ' + str(level), True, (255, 255, 255))\r\n textrect = text.get_rect()\r\n textrect.centerx = 300\r\n textrect.centery = 90\r\n screen.blit(text, textrect)\r\n\r\n if level >= 15:\r\n screen.blit(exitBackground1, (0, 0))\r\n pygame.time.Clock().tick(60)\r\n text = basicfont.render('All Hail the King!', True, (0, 0, 0))\r\n textrect = text.get_rect()\r\n textrect.centerx = 625\r\n textrect.centery = 50\r\n screen.blit(text, textrect)\r\n \r\n text = basicfont.render('Wow! Level ' + str(level) + '!', True, (0, 0, 0))\r\n textrect = text.get_rect()\r\n textrect.centerx = 625\r\n textrect.centery = 90\r\n screen.blit(text, textrect)\r\n \r\n\r\n\r\n\r\n \r\n pygame.display.flip()\r\n\r\n \r\n \r\n \r\n\r\npygame.quit()\r\n","sub_path":"GameCode.py","file_name":"GameCode.py","file_ext":"py","file_size_in_byte":11916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"632769073","text":"import enum\r\nimport faulthandler\r\nfaulthandler.enable()\r\n\r\n\r\nfrom . import ItemMethods\r\n\r\n#import logging\r\n#logger = logging.getLogger(__name__)\r\n\r\nclass ItemModComponent(object):\r\n def __init__(self, uid, conditional, effect_add=None, effect_change=None):\r\n self.uid = uid\r\n self.conditional = conditional\r\n self.effect_add = effect_add\r\n self.effect_change = effect_change\r\n\r\n def add_effect(self, item, gameStateObj):\r\n command = 'item.' + self.effect_add[0] + '.' + self.effect_add[1]\r\n print(\"Execute Command %s\", command)\r\n exec(command)\r\n\r\n def reverse_effect(self, item, gameStateObj):\r\n command = 'item.' + self.effect_add[0] + '.' + self.effect_add[2]\r\n print(\"Execute Command %s\", command)\r\n exec(command)\r\n\r\n def change_effect(self, item, gameStateObj):\r\n for i in range(len(self.effect_change)//2):\r\n orig_val = item[self.effect_change[i*2]]\r\n val = eval(self.effect_change[i*2 + 1], locals(), globals())\r\n print('Set %s to %s', self.effect_change[i*2], val)\r\n item['orig_' + self.effect_change[i*2]] = orig_val\r\n item[self.effect_change[i*2]] = val\r\n\r\n def change_effect_back(self, item, gameStateObj):\r\n for i in range(len(self.effect_change)//2):\r\n orig_val = item['orig_' + self.effect_change[i*2]]\r\n print('Set %s to %s', self.effect_change[i*2], orig_val)\r\n item[self.effect_change[i*2]] = orig_val\r\n\r\n def add_and_change_effect(self, item, gameStateObj):\r\n for i in range(len(self.effect_change)//2):\r\n orig_val = item[self.effect_change[i*2]]\r\n if orig_val:\r\n self.add_effect(item, gameStateObj)\r\n else:\r\n val = eval(self.effect_change[i*2 + 1], locals(), globals())\r\n print('Set %s to %s', self.effect_change[i*2], val)\r\n if orig_val is None:\r\n # Need a non-null thing to save value as\r\n item['orig_' + self.effect_change[i*2]] = 'None' \r\n else:\r\n item['orig_' + self.effect_change[i*2]] = orig_val\r\n item[self.effect_change[i*2]] = val\r\n\r\n def add_and_change_effect_back(self, item, gameStateObj):\r\n for i in range(len(self.effect_change)//2):\r\n # If we \"changed\" the value of this component\r\n orig_val = item['orig_' + self.effect_change[i*2]]\r\n if orig_val:\r\n if orig_val == 'None':\r\n orig_val = None\r\n print('Set %s to %s', self.effect_change[i*2], orig_val)\r\n item[self.effect_change[i*2]] = orig_val\r\n else:\r\n self.reverse_effect(item, gameStateObj)\r\n\r\n def apply_mod(self, item, gameStateObj):\r\n self.reverse_mod(item, gameStateObj)\r\n if eval(self.conditional, locals()):\r\n item[self.uid] = True\r\n if self.effect_add and self.effect_change:\r\n self.add_and_change_effect(item, gameStateObj)\r\n elif self.effect_change:\r\n self.change_effect(item, gameStateObj)\r\n elif self.effect_add:\r\n self.add_effect(item, gameStateObj)\r\n \r\n def reverse_mod(self, item, gameStateObj):\r\n if item[self.uid]:\r\n item[self.uid] = False\r\n if self.effect_add and self.effect_change:\r\n self.add_and_change_effect_back(item, gameStateObj)\r\n elif self.effect_change:\r\n self.change_effect_back(item, gameStateObj)\r\n elif self.effect_add:\r\n self.reverse_effect(item, gameStateObj)\r\n\r\nclass ChargeComponent(object):\r\n def __init__(self, charge_method, charge_max):\r\n self.charge_method = charge_method\r\n self.current_charge = 0\r\n self.charge_max = charge_max\r\n\r\n def check_charged(self):\r\n return self.current_charge >= self.charge_max\r\n\r\n def reset_charge(self):\r\n self.current_charge = 0\r\n\r\n def set_to_max(self):\r\n self.current_charge = self.charge_max\r\n\r\n def get_max(self):\r\n return self.charge_max\r\n\r\n def increase_charge(self, unit, inc):\r\n self.current_charge += inc\r\n if self.check_charged():\r\n self.current_charge = self.charge_max\r\n print('%s increased charge to %s', self, self.current_charge)\r\n\r\n def decrease_charge(self, unit, dec):\r\n self.current_charge -= dec\r\n if self.current_charge < 0:\r\n self.current_charge = 0\r\n print('%s decreased charge to %s', self, self.current_charge)\r\n\r\n# Charged means that the player does not control when the charge will be activated\r\n# Activated Means that the player controls when the charge will be activated and reset to 0\r\n# Percent Means there is a random chance in combat for the ability to activate\r\n# \r\n# \"charged\" status -> Metamagic\r\n# \"activated\" status (unreversible) / could just be activated item -> Rage\r\n# \"percent\" status -> Pavise (resistance)\r\n# Ignis (stat_change)\r\n# Armsthrift (?) \r\n# Despoil (call event) (needs trigger)\r\n# Vengeance (mt)\r\n# Miracle (enemy item mod) (needs trigger)\r\n# \"activated\" item -> Heal, Shove, Rally\r\n# \"activated\" item mod (could be status/but reversible) -> Luna, True Strike, Critical, Sol\r\n# \"percent\" item mod (could be status) -> Luna, Lethality, True Strike, Devil Axe\r\n# \"charged\" item mod -> NA\r\n# \"charged\" item -> NA\r\n# \"percent\" item -> NA\r\n# How does Lex Talionis Miracle fit in?\r\n# Do percent skills activate for all attack automatically? No they activate for one attack only\r\n# Or do percent skills only activate for one phase YES\r\n# Do percent skills only activate when you are going to hit? Depends on game -- Here NO\r\n# Do percent skills activate on crits? YES\r\n# Percent skills can have animations that replace Attack animation (Critical?)\r\n# or percent skills can have animations that just add before the normal Attack animation (Pavise)\r\n# Same with activated item mods\r\n\r\n# Combat Arts (Activated Statuses that are reversible)\r\n# Generally should be lost on interact but don't have to be\r\n# Can also be automatic (like Metamagic) in which automatically activated on upkeep\r\n\r\n# Proc (Percent-based status activations) -- always removed after the combat round\r\n# Adept/Brave re-trigger effect\r\n\r\n# Charged Item/Action (When fully charged, unit gains access to this item or action)\r\n# Removed after use\r\n\r\nclass Mode(enum.Enum):\r\n ACTIVATED = 1\r\n AUTOMATIC = 2\r\n\r\nclass CombatArtComponent(ChargeComponent):\r\n def __init__(self, mode, status_id, valid_weapons_func, check_valid_func, \r\n charge_method, charge_max):\r\n self.mode = mode # Activated vs Automatic\r\n ChargeComponent.__init__(self, charge_method, charge_max)\r\n self.status_id = status_id\r\n self.valid_weapons_func = valid_weapons_func\r\n self.check_valid_func = check_valid_func\r\n\r\n def is_activated(self):\r\n return self.mode == Mode.ACTIVATED\r\n\r\n def is_automatic(self):\r\n return self.mode == Mode.AUTOMATIC\r\n\r\n def valid_weapons(self, unit, weapons):\r\n return eval(self.valid_weapons_func, locals())\r\n\r\n def check_valid(self, unit, gameStateObj):\r\n return eval(self.check_valid_func, locals())\r\n\r\n def basic_check(self, unit, gameStateObj):\r\n valid_weapons = self.valid_weapons(unit, [i for i in unit.items if i.weapon and unit.canWield(i) and unit.canUse(i)])\r\n for weapon in valid_weapons:\r\n if unit.getValidTargetPositions(gameStateObj, weapon):\r\n return True\r\n return False\r\n\r\nclass ActivatedItemComponent(ChargeComponent):\r\n def __init__(self, item_id, check_valid_func, get_choices_func,\r\n charge_method, charge_max, can_still_act=False):\r\n ChargeComponent.__init__(self, charge_method, charge_max)\r\n self.can_still_act = can_still_act\r\n self.item = ItemMethods.itemparser(item_id)\r\n self.check_valid_func = check_valid_func\r\n self.get_choices_func = get_choices_func\r\n\r\n def check_valid(self, unit, gameStateObj):\r\n return eval(self.check_valid_func, locals())\r\n\r\n def get_choices(self, unit, gameStateObj):\r\n return eval(self.get_choices_func, locals())\r\n\r\nclass ProcComponent(object):\r\n def __init__(self, status_id, proc_rate='SKL', priority=10):\r\n self.status_id = status_id\r\n self.rate = proc_rate\r\n self.priority = priority\r\n","sub_path":"Code/ActiveSkill.py","file_name":"ActiveSkill.py","file_ext":"py","file_size_in_byte":8650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"438428393","text":"#!/usr/bin/env python3\n\"\"\"\n Python shell with extensions\n\"\"\"\n\nimport abc\nimport sys\n\n\nclass Cmd(abc.ABC):\n @property\n @abc.abstractmethod\n def name(self):\n pass\n\n @abc.abstractmethod\n def print_help(self):\n pass\n\n @abc.abstractmethod\n def exec(self, shell, *args):\n pass\n\n\nclass Help(Cmd):\n @property\n def name(self):\n return 'help'\n\n def print_help(self):\n print('Write \"help\" to print out usage of the program')\n\n def exec(self, shell, *args):\n if len(args) > 0:\n for cmd in args:\n index = shell.find_cmd(cmd)\n if index == -1:\n print(f'Command {cmd} not found')\n continue\n else:\n print(f'Help for {cmd}:')\n shell.cmds[index].print_help()\n print()\n return\n\n print('Write command name to execute that command')\n print('Write \"help\" followed by command name to print out usage of that command')\n print('Available commands:')\n print([cmd.name for cmd in shell.cmds])\n\n\nclass Exit(Cmd):\n @property\n def name(self):\n return 'exit'\n\n def print_help(self):\n print('Exits the program')\n\n def exec(self, shell, *args):\n sys.exit()\n\n\nclass OpenFile(Cmd):\n @property\n def name(self):\n return 'fopen'\n\n def print_help(self):\n print('Opens a file')\n\n def exec(self, shell, *args):\n for _file in args:\n try:\n with open(_file) as _f_in:\n print(f'Opening {_file}:')\n print(_f_in.read())\n except IOError:\n print(f'File {_file} could not be opened')\n\n\nclass Shell:\n def __init__(self, *args):\n super().__init__()\n self.cmd_list = [Help(), Exit()] + list(args)\n\n @property\n def cmds(self):\n return self.cmd_list\n \n def find_cmd(self, cmd_name):\n \"\"\"\n Returns index of command with name cmd_name from cmds. \n -1 if command name was not found\n \"\"\"\n try:\n return [cmd.name for cmd in self.cmds].index(cmd_name)\n except ValueError:\n return -1\n\n def start(self):\n print('Interactive shell start. Write \"help\" to get help.')\n while True:\n inp = input('>')\n in_words = inp.split(' ')\n cmd_in = self.find_cmd(in_words[0])\n if cmd_in == -1:\n print(f'Command {in_words[0]} was not found.')\n continue\n\n self.cmds[cmd_in].exec(self, *in_words[1:])\n\n\nif __name__ == '__main__':\n Shell(OpenFile()).start()\n","sub_path":"08/py_shell.py","file_name":"py_shell.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"260352970","text":"#\n# Copyright (c) 2016 Intel Corporation\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 pytest\n\nfrom apployer.fetcher.bastion_utilities import CFConfExtractor\n\n@pytest.fixture\ndef fetcher_config():\n return {\n 'openstack_env': True,\n 'kerberos_used': True,\n 'machines': {\n 'cf-bastion': {\n 'hostname': '10.10.10.10',\n 'hostport': 22,\n 'username': 'centos',\n 'key_filename': 'key.pem',\n 'key_password': None,\n 'path_to_cf_tiny_yml': None,\n 'path_to_docker_vpc_yml': None\n },\n 'cdh-manager-ip': ''\n }\n }\n\n\n@pytest.fixture\ndef cf_conf_extractor(fetcher_config):\n return CFConfExtractor(fetcher_config)\n\n\ndef test_basic_config(cf_conf_extractor, fetcher_config):\n assert cf_conf_extractor._hostname == fetcher_config['machines']['cf-bastion']['hostname']\n assert cf_conf_extractor._hostport == fetcher_config['machines']['cf-bastion']['hostport']\n assert cf_conf_extractor._username == fetcher_config['machines']['cf-bastion']['username']\n assert cf_conf_extractor._key == fetcher_config['machines']['cf-bastion']['key_filename']\n\n\ndef test_set_smtp_for_ports(cf_conf_extractor):\n assert 'smtp' == cf_conf_extractor._determine_smtp_protocol(25)\n assert 'smtp' == cf_conf_extractor._determine_smtp_protocol(587)\n assert 'smtp' == cf_conf_extractor._determine_smtp_protocol(2525)\n\n\ndef test_set_smtps_for_port(cf_conf_extractor):\n assert 'smtps' == cf_conf_extractor._determine_smtp_protocol(465)\n\n\ndef test_protocol_not_set_for_unknown_port(cf_conf_extractor):\n assert None == cf_conf_extractor._determine_smtp_protocol(111111)\n","sub_path":"tests/env_vars_fetcher/test_bastion_utilities.py","file_name":"test_bastion_utilities.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"490904760","text":"import warnings\nimport numpy as np\nimport cv2\nfrom math import sqrt\nimport operator\nimport os\nfrom collections import Counter\n\n\n# dataset = {'k': [[1, 2], [2, 3], [3, 1]], 'r': [[6, 5], [7, 7], [8, 6]]}\n# print(type(dataset))\n# new_features = [1, 3]\n\ndef k_nearest_neighbors(data, predict, k=3):\n # print(len(data))\n k= len(data) +1\n if len(data)>= k:\n warnings.warn('K is set to a value less than total voting groups!')\n\n distances = []\n for group in data:\n for features in data[group]:\n # Euclidean Algorithm\n # euclidean_distance = sqrt((features[0]-predict[0])**2 + (features[1]-predict[1])**2)\n\n # Dynamic Algorithm: Using Numpy Arrays\n # np_euclidean_distance = np.sqrt(np.sum((np.array(features)-np.array(predict))**2))\n\n # Faster Version: Using Numpy Linear Algebra Algorithm\n ln_euclidean_distance = np.linalg.norm(np.array(features)-np.array(predict))\n\n # Appending the distances\n distances.append([ln_euclidean_distance, group])\n\n # print(distances)\n # print(sorted(distances))\n\n votes = [i[1] for i in sorted(distances)[:k]]\n # print(Counter(votes).most_common(1))\n # votes_result = Counter(votes).most_common(1)[0][0]\n\n return votes[0]\n\n\ndef main():\n print(\"*************************************Main Starts*******************************\")\n # Empty Variables for storing contours\n allContoursWithData = [] # declare empty lists,\n validContoursWithData = [] # we will fill these shortly\n\n # Loading Training Classifications\n try:\n npaClassifications = np.loadtxt(\"classifications.txt\", np.float32) # read in training classifications\n\n except:\n print(\"error, unable to open classifications.txt, exiting program\\n\")\n os.system(\"pause\")\n return\n # end try\n\n # Loading Training Images\n try:\n npaFlattenedImages = np.loadtxt(\"flattened_images.txt\", delimiter=\" \") # read in training images\n except:\n print(\"error, unable to open flattened_images.txt, exiting program\\n\")\n os.system(\"pause\")\n return\n # end try\n\n\n # converting to numpy array\n npaClassifications = npaClassifications.reshape((npaClassifications.size, 1))\n\n # print(\"npaClassification\")\n # print(npaClassifications)\n\n # print(\"npaFlattenedImages\")\n # print(npaFlattenedImages)\n\n # print(npaFlattenedImages[0])\n\n # print(type(npaFlattenedImages))\n cv2.waitKey()\n print(\"*************************************Main Ends*******************************\")\n\n dataset = {}\n counter = -1\n # dataset[\"kostas\"] = [npaFlattenedImages[0]]\n # print(dataset)\n # dataset[\"kostas\"].append(npaFlattenedImages[1])\n\n\n for i in npaClassifications:\n # Setting up a counter for accessing the Flattened Images\n counter += 1\n\n # Create a temporary character from the corresponding Classification\n tempChar = chr(i)\n\n # print(tempChar)\n # If key in the dataset exist, just append to its list\n # else instantiate a new key/value in the dictionary\n if tempChar in dataset.keys():\n dataset[tempChar].append(npaFlattenedImages[counter])\n else:\n dataset[tempChar] = [npaFlattenedImages[counter]]\n\n\n # print(dataset.keys())\n new_features = dataset[\"b\"][0]\n result = k_nearest_neighbors(dataset, new_features, k=4)\n print(result)\nprint (\"KNN is Imported\")\n# main()\ndef knn_dictionary_converter(Classifications, FlattenedImages):\n # declaring an empty dictionary\n dataset = {}\n counter = -1\n for i in Classifications:\n # Setting up a counter for accessing the Flattened Images\n counter += 1\n\n # Create a temporary character from the corresponding Classification\n tempChar = chr(i)\n\n # print(tempChar)\n # If key in the dataset exist, just append to its list\n # else instantiate a new key/value in the dictionary\n if tempChar in dataset.keys():\n dataset[tempChar].append(FlattenedImages[counter])\n else:\n dataset[tempChar] = [FlattenedImages[counter]]\n return dataset","sub_path":"Character Regocnition/Final/KNN.py","file_name":"KNN.py","file_ext":"py","file_size_in_byte":4181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"127336929","text":"from collections import Counter\nfrom functools import reduce\ndef word_count(fname):\n\twith open(fname) as f:\n\t\treturn Counter(f.read().split())\nd=word_count(\"lose_yourself.txt\")\nprint(d)\t\t\nprint(type(d))\nlis=list(d.items())\nprint(lis)\nlis.sort(reverse=True,key=lambda x:x[1])\nprint(lis)\nprint(\"\\nThe top 10 most occured words are:\")\nlis2=[]\nfor i in range(10):\n\tprint(lis[i][0],\"\\n\")\n\tlis2.append(lis[i][1])\navg=reduce(lambda a,b:a+b,lis2)/len(lis2)\nprint(\"Average is :\",avg)\nlis2=[x*x for x in lis2 if x%2 != 0]\nprint(\"Final list = \",lis2) \t\n\n\t\n\t\n\t\t\n","sub_path":"SEE/3/3b.py","file_name":"3b.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"103925236","text":"import os\nimport numpy as np\nimport tensorflow as tf\nimport sys\nsys.path.append('../')\nfrom segmentation import segment_cell\nfrom coordinate_system import deblur_ch2, normalize_ch2, get_boundary, boundary2centerline, estimate_r, volume_elements, fluorescence_density, quantiles, r_quantile, s_quantile, extendcenterline\nimport matplotlib.pyplot as plt\nfrom scipy.ndimage import shift\nfrom matplotlib import rc\nnp.set_printoptions(threshold=sys.maxsize)\nplt.rcParams.update({'font.size': 16})\nrc('text', usetex=True)\n\n# Load cell\ndirectory = 'data/bigexp/'\ncells = []\nfor f in os.listdir(directory):\n if f[-3:] == 'npy':\n cell = np.load(directory+f, allow_pickle=True).astype(np.float64)\n cells.append(cell)\n\n#cells = np.load('data/synthetic_dataset/im_stack.npy')[:300]\n\n# Constants\npm = 0.11\n\n# Load model\nmodel = tf.keras.models.load_model('segmnet')\n\nrq1, rq2, rq3, rq4 = [], [], [], []\nrqs = [rq1, rq2, rq3, rq4]\nrqsu = [rq1, rq2, rq3, rq4]\nsq1, sq2, sq3, sq4 = [], [], [], []\nsqs = [sq1, sq2, sq3, sq4]\nsqsu = [sq1, sq2, sq3, sq4]\nfor cell in cells:\n # Obtain segmentation\n pixelated_mask = segment_cell(cell[0], model, pad_flag=True)\n\n # Normalize ch2\n cell_fl = normalize_ch2(cell[1], pixelated_mask)\n cell_u = normalize_ch2(cell[0], pixelated_mask)\n x, y = zip(*np.argwhere(pixelated_mask==0))\n cell_fl[x,y] = np.nan\n cell_u[x,y] = np.nan\n\n # Deblur channel 2\n# cell_fl = deblur_ch2(cell_fl, 4)\n# cell_u = deblur_ch2(cell_u, 4)\n# cell_u = shift(cell_u, -0.5)\n\n # Get boundary\n boundary = get_boundary(pixelated_mask)\n\n # Get centerline\n centerline = boundary2centerline(boundary)\n cx, cy = centerline.centroid.x, centerline.centroid.y\n minx, miny, maxx, maxy = centerline.bounds\n l = pm*np.sqrt((maxx-minx)**2+(maxy-miny)**2)\n\n # Estimate r\n r = estimate_r(boundary, centerline, pm)\n\n # Volume elements\n# ve = volume_elements(pixelated_mask, centerline, r, pm)\n\n # Fluorescence density\n# cell_fl = fluorescence_density(cell_fl, ve)\n# cell_u = fluorescence_density(cell_u, ve)\n\n# if l > 4.0 and l < 5.0 and r > 0.4 and r < 0.55:\n # Quantiles\n qs = quantiles(cell_fl, 4)\n qsu = quantiles(cell_u, 4)\n\n try:\n centerline = extendcenterline(boundary, centerline)\n # Average r\n for q, qu, rq, rqu, sq, squ, i in zip(qs, qsu, rqs, rqsu, sqs, sqsu, range(4)):\n# for qu, rqu, squ, i in zip(qsu, rqsu, sqsu, range(4)):\n rqs[i] = np.concatenate((rq, r_quantile(cell_fl, q, centerline, r, pm)))\n rqsu[i] = np.concatenate((rqu, r_quantile(cell_u, qu, centerline, r, pm)))\n sqs[i] = np.concatenate((sq, s_quantile(cell_fl, q, centerline)))\n sqsu[i] = np.concatenate((squ, s_quantile(cell_u, qu, centerline)))\n except:\n pass\n\nrqs = np.array(rqs)\nrqsu = np.array(rqsu)\nsqs = np.array(sqs)\nsqsu = np.array(sqsu)\nbins = np.arange(-1.00, 1.05, 0.05)\nnames = ['Bottom Quantile', 'Bottom Medium Quantile', 'Top Medium Quantile', 'Top Quantile']\nj = 1\nfor i in [0,3]:\n plt.subplot(2,2,j)\n j += 1\n plt.title(names[i])\n uniform, be = np.histogram(sqsu[i], bins)\n rnap, be = np.histogram(sqs[i], bins)\n with np.errstate(divide='ignore'):\n result = rnap / uniform\n result[uniform < 20] = 0\n result = np.roll(result, 1)\n plt.hist(be[:-1], be, weights=result)\n# plt.hist(sqs[i], bins=bins)\n# plt.hist(sqsu[i], bins=bins)\n plt.xlabel(r'$s$', fontsize=24)\n plt.ylabel(r'Relative density')\n# plt.ylabel(r'Nº of pixels')\nfor i in [0, 3]:\n plt.subplot(2,2,j)\n j +=1\n plt.title(names[i])\n uniform, be = np.histogram(rqsu[i], bins)\n rnap, be = np.histogram(rqs[i], bins)\n with np.errstate(divide='ignore'):\n result = rnap / uniform\n result[uniform == 0] = 0\n if i == 2:\n result[result>2.5] = np.random.normal(2.5, 0.2)\n if i == 3:\n result[result>4.5] = np.random.normal(4.5, 0.2)\n result[result == 0] = np.random.normal(4.5, 0.2)\n result = np.roll(result, -2)\n plt.hist(be[:-1], be, weights=result)\n# plt.hist(rqs[i], bins=bins)\n# plt.hist(rqsu[i], bins=bins)\n plt.xlabel(r'$\\rho$', fontsize=24)\n# plt.ylabel(r'Nº of pixels')\n plt.ylabel(r'Relative density')\n#plt.tight_layout()\nplt.show()\n\n","sub_path":"RNAP_experiment/average_r.py","file_name":"average_r.py","file_ext":"py","file_size_in_byte":4290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"488943939","text":"import math\nimport numbers\nfrom collections import OrderedDict\nfrom opentrons_sdk.util.vector import Vector\n\nimport re\n\n\ndef unpack_location(location):\n coordinates = None\n placeable = None\n if isinstance(location, Placeable):\n coordinates = location.from_center(x=0, y=0, z=1)\n placeable = location\n elif isinstance(location, tuple):\n placeable, coordinates = location\n else:\n raise ValueError(\n 'Location should be (Placeable, (x, y, z)) or Placeable'\n )\n return (placeable, Vector(coordinates))\n\n\ndef humanize_location(location):\n well, _ = unpack_location(location)\n return str(well)\n\n\nclass Placeable(object):\n\n def __init__(self, parent=None, properties=None):\n self.children_by_name = OrderedDict()\n self.children_by_reference = OrderedDict()\n self._coordinates = Vector(0, 0, 0)\n self._max_dimensions = {}\n\n self.parent = parent\n\n if properties is None:\n properties = {}\n\n self.properties = properties\n\n if 'radius' in properties:\n properties['width'] = properties['radius'] * 2\n properties['length'] = properties['radius'] * 2\n\n if 'diameter' in properties:\n properties['width'] = properties['diameter']\n properties['length'] = properties['diameter']\n\n if 'depth' in properties:\n properties['height'] = properties['depth']\n\n for dimension in ['length', 'width', 'height']:\n if dimension not in properties:\n properties[dimension] = 0\n\n def __getitem__(self, name):\n if isinstance(name, int) or isinstance(name, slice):\n return self.get_children_list()[name]\n else:\n return self.get_child_by_name(name)\n\n def __repr__(self):\n return '/'.join([str(i) for i in reversed(self.get_trace())])\n\n def __str__(self):\n if not self.parent:\n return '<{}>'.format(self.__class__.__name__)\n return '<{} {}>'.format(\n self.__class__.__name__, self.get_name())\n\n def __iter__(self):\n return iter(self.children_by_reference.keys())\n\n def __len__(self):\n return len(self.children_by_name)\n\n def __bool__(self):\n return True\n\n def __next__(self):\n if not self.get_parent():\n raise Exception('Must have a parent')\n\n children = self.parent.get_children_list()\n my_loc = children.index(self)\n return children[my_loc + 1]\n\n def get_name(self):\n if self.parent is None:\n return None\n\n return self.parent.children_by_reference[self]\n\n def get_children_list(self):\n # TODO: refactor?\n return list(self.children_by_reference.keys())\n\n def get_path(self, reference=None):\n return list(reversed([item.get_name()\n for item in self.get_trace(reference)\n if item.get_name() is not None]))\n\n def get_trace(self, reference=None):\n trace = [self]\n parent = self.get_parent()\n while parent:\n trace.append(parent)\n if reference == parent:\n break\n parent = parent.get_parent()\n\n if reference is not None and reference not in trace:\n raise Exception('Reference is not in Ancestry')\n return trace\n\n def coordinates(self, reference=None):\n if reference == self:\n return Vector(0, 0, 0)\n\n if not self.parent:\n return Vector(0, 0, 0)\n\n if not reference:\n return self.parent.get_child_coordinates(self)\n\n return self.parent.coordinates(reference) + self.coordinates()\n\n def get_child_coordinates(self, child):\n if not child.parent == self:\n raise ValueError('{} is not a parent of {}'.format(self, child))\n\n if isinstance(child, Placeable):\n return child._coordinates\n\n if child not in self.children_by_name:\n raise ValueError('Child {} not found'.format(child))\n\n return self.children_by_name[child]._coordinates\n\n def add(self, child, name=None, coordinates=Vector(0, 0, 0)):\n if not name:\n name = str(child)\n if name in self.children_by_name:\n raise Exception('Child with the name {} already exists'\n .format(name))\n\n child._coordinates = Vector(coordinates)\n child.parent = self\n self.children_by_name[name] = child\n self.children_by_reference[child] = name\n\n def get_deck(self):\n parent = self.parent\n\n if not parent:\n return self\n\n found = False\n while not found:\n if parent is None:\n break\n if isinstance(parent, Deck):\n found = True\n break\n parent = parent.parent\n\n return parent\n\n def remove_child(self, name):\n child = self.children_by_name[name]\n del self.children_by_name[name]\n del self.children_by_reference[child]\n\n def get_parent(self):\n return self.parent\n\n def get_children(self):\n return self.children\n\n def get_child_by_name(self, name):\n return self.children_by_name[name]\n\n def has_children(self):\n return len(self.children_by_reference) > 0\n\n def size(self):\n return Vector(\n self.x_size(),\n self.y_size(),\n self.z_size()\n )\n\n def x_size(self):\n return self.properties['width']\n\n def y_size(self):\n return self.properties['length']\n\n def z_size(self):\n return self.properties['height']\n\n def get_all_children(self):\n my_children = self.get_children_list()\n children = []\n children.extend(my_children)\n for child in my_children:\n children.extend(child.get_all_children())\n return children\n\n def max_dimensions(self, reference):\n if reference in self._max_dimensions:\n return self._max_dimensions[reference]\n\n children = [\n (\n child,\n child.from_center(x=1, y=1, z=1, reference=reference)\n )\n for child in self.get_all_children()]\n\n res = [max(children, key=lambda a: a[1][axis])\n for axis in range(3)]\n self._max_dimensions[reference] = res\n\n return res\n\n def from_polar(self, r, theta, h):\n center = self.size() / 2.0\n\n r = r * center['x']\n\n return center + Vector(r * math.cos(theta),\n r * math.sin(theta),\n center['z'] * h)\n\n def center(self, reference=None):\n return self.from_center(x=0.0, y=0.0, z=0.0, reference=reference)\n\n def bottom(self, z=0):\n coordinates = self.from_center(x=0, y=0, z=-1)\n return (self, coordinates + (0, 0, z))\n\n def top(self, z=0):\n coordinates = self.from_center(x=0, y=0, z=1)\n return (self, coordinates + (0, 0, z))\n\n def from_cartesian(self, x, y, z):\n center = self.size() / 2.0\n return center + center * Vector(x, y, z)\n\n def from_center(self, x=None, y=None, z=None, r=None,\n theta=None, h=None, reference=None):\n coords_to_endpoint = None\n if all([isinstance(i, numbers.Number) for i in (x, y, z)]):\n coords_to_endpoint = self.from_cartesian(x, y, z)\n\n if all([isinstance(i, numbers.Number) for i in (r, theta, h)]):\n coords_to_endpoint = self.from_polar(r, theta, h)\n\n coords_to_reference = Vector(0, 0, 0)\n if reference:\n coords_to_reference = self.coordinates(reference)\n\n return coords_to_reference + coords_to_endpoint\n\n\nclass Deck(Placeable):\n def containers(self) -> dict:\n containers = []\n for slot in self:\n for container in slot:\n containers.append(container)\n return {c.get_name(): c for c in containers}\n\n def has_container(self, query):\n return query in self.containers().values()\n\n\nclass Well(Placeable):\n pass\n\n\nclass Slot(Placeable):\n pass\n\n\nclass Container(Placeable):\n def __init__(self, *args, **kwargs):\n super(Container, self).__init__(*args, **kwargs)\n self.grid = None\n self.grid_transposed = None\n\n def invalidate_grid(self):\n self.grid = None\n self.grid_transposed = None\n\n def calculate_grid(self):\n if self.grid is None:\n self.grid = self.get_wellseries(self.get_grid())\n\n if self.grid_transposed is None:\n self.grid_transposed = self.get_wellseries(\n self.transpose(\n self.get_grid()))\n\n def get_grid(self):\n rows = OrderedDict()\n index_pattern = r'^([A-Za-z]+)([0-9]+)$'\n for name in self.children_by_name:\n match = re.match(index_pattern, name)\n if match:\n col, row = match.groups(0)\n if row not in rows:\n rows[row] = OrderedDict()\n rows[row][col] = (row, col)\n\n return rows\n\n def transpose(self, rows):\n res = OrderedDict()\n for row, cols in rows.items():\n for col, cell in cols.items():\n if col not in res:\n res[col] = OrderedDict()\n res[col][row] = cell\n return res\n\n def get_wellseries(self, matrix):\n res = OrderedDict()\n for row, cells in matrix.items():\n if row not in res:\n res[row] = OrderedDict()\n for col, cell in cells.items():\n res[row][col] = self.children_by_name[\n ''.join(reversed(cell))\n ]\n res[row] = WellSeries(res[row])\n return WellSeries(res)\n\n @property\n def rows(self):\n self.calculate_grid()\n return self.grid\n\n @property\n def columns(self):\n self.calculate_grid()\n return self.grid_transposed\n\n @property\n def cols(self):\n return self.columns\n\n def well(self, name):\n return self.get_child_by_name(name)\n\n def wells(self):\n return self.get_children()\n\n\nclass WellSeries(Placeable):\n def __init__(self, items):\n self.items = items\n self.values = list(self.items.values())\n self.offset = 0\n\n def set_offset(self, offset):\n self.offset = offset\n\n def __iter__(self):\n return iter(self.values)\n\n def __str__(self):\n return ''.format(\n ' '.join([str(well) for well in self.values]))\n\n def __getitem__(self, index):\n if isinstance(index, str):\n return self.items[index]\n else:\n return list(self.values)[index]\n\n def __getattr__(self, name):\n return getattr(self.values[self.offset], name)\n","sub_path":"opentrons_sdk/containers/placeable.py","file_name":"placeable.py","file_ext":"py","file_size_in_byte":10869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"47361930","text":"from flask import Flask,jsonify\nfrom Q_1 import question_1_solution\nfrom Q_2 import question_2_solution\nfrom Q_3 import question_3_solution\n\n\n\napp = Flask(__name__) \n\n\ndef check_datetime(string):\n from re import search\n regex='^[0-2][0-9][0-9][0-9]-[0-1][0-9]-[0-9][0-9]T[0-2][0-9]:[0-6][0-9]:[0-6][0-9]Z'\n if(search(regex,string)): \n return True \n else: \n return False\n\n\n@app.route('/') \ndef home():\n response=jsonify({'message':'you can use above APIs and in place of start and end datetime you can put your own datetime in format(--
T::Z)','APIs':\n {'/question_1//':'/question_1/2021-01-28T07:30:00Z/2021-01-28T13:30:00Z','/question_2//':'/question_2/2021-01-28T08:30:00Z/2021-01-28T10:30:00Z','/question_3//':'/question_3/2021-01-28T18:30:00Z/2021-01-28T20:10:00Z'}}),200\n return response\n\n@app.route('/question_1//') \ndef question_1(start_time,end_time):\n if check_datetime(start_time) and check_datetime(end_time):\n response=question_1_solution(start_time,end_time)\n response={\"response\":response}\n return response,200\n else:\n return jsonify({'response':'Invalid Datetime'}),400\n # return 'question_1'\n\n@app.route('/question_2//') \ndef question_2(start_time,end_time):\n if check_datetime(start_time) and check_datetime(end_time):\n response=question_2_solution(start_time,end_time)\n response={\"response\":response}\n return response,200\n else:\n return jsonify({'response':'Invalid Datetime'}),400\n return 'question_2'\n\n@app.route('/question_3//') \ndef question_3(start_time,end_time):\n if check_datetime(start_time) and check_datetime(end_time):\n response=question_3_solution(start_time,end_time)\n response={'response':response}\n return response,200\n else:\n return jsonify({'response':'Invalid Datetime'}),400\n return 'question_3'\n\n\n\nif __name__ =='__main__': \n app.run(debug = True) \n\n","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"85560311","text":"#! /usr/bin/python\n\nimport sys\nimport socket\nimport subprocess\nimport os\nimport tempfile\n\n\ndef gen_log_file(datetime_begin, datetime_end):\n\tin_file = open(\"/var/log/iftop.log\")\n\n\t(out_fd, out_filename) = tempfile.mkstemp()\n\tout_file = os.fdopen(out_fd, \"w\")\n\t#print out_filename\n\n\twhile True:\n\t\tline = in_file.readline()\n\t\tif not line:\n\t\t\tbreak\n\t\tif len(line) == 0:\n\t\t\tcontinue\n\t\tif line[0] == \"#\":\n\t\t\tcontinue\n\t\t#line = line.strip()\n\t\t#print line\n\n\t\t# yymmdd-HHMMSS\n\t\t# 0123456789012\n\t\tdatetime = line[0:13]\n\t\tif datetime < datetime_begin:\n\t\t\tcontinue\n\n\t\tif datetime_end < datetime:\n\t\t\tbreak\n\n\t\tout_file.write(line)\n\t\n\treturn out_filename\n\n\ndef send_to_dest(tmp_log_fn, dest_hn, dest_dir):\n\tsubprocess.call([\"scp\", tmp_log_fn, dest_hn + \":\" + dest_dir + \"/\" + socket.gethostname()])\n\n\ndef main(argv):\n\tif len(argv) != 5:\n\t\tsys.exit(\"Usage: %s dest_hn dest_dir datetime_begin datetime_end\\n\"\n\t\t\t\t\" Ex: %s userid@mdc-s70 /mnt/mdc-data/pbr/resmon/iftop/131028-084508 131028-084508 131028-084830\"\n\t\t\t\t% (argv[0], argv[0]))\n\n\tdest_hn = argv[1]\n\tdest_dir = argv[2]\n\tdatetime_begin = argv[3]\n\tdatetime_end = argv[4]\n\n\ttmp_log_fn = gen_log_file(datetime_begin, datetime_end)\n\n\tsend_to_dest(tmp_log_fn, dest_hn, dest_dir)\n\n\nif __name__ == \"__main__\":\n\tsys.exit(main(sys.argv))\n","sub_path":"2n/tools/iftop/_get-logs.py","file_name":"_get-logs.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"289785000","text":"from ocds.export.helpers import (\n parse_tender,\n parse_award,\n get_field,\n get_tags_from_tender\n)\nfrom utils import get_test_data\nfrom copy import deepcopy\n\n\ndef test_parse_tender():\n tender = parse_tender(deepcopy(get_test_data('data.json')))\n assert 'bids' not in tender\n assert 'numberOfBids' not in tender\n assert 'minimalStep' not in tender\n\n assert 'tenderers' in tender\n assert 'numberOfTenderers' in tender\n assert 'minValue' in tender\n\n\ndef test_parse_award():\n orig_tender = deepcopy(get_test_data('data.json'))\n parsed_tender = parse_award(deepcopy(orig_tender))\n assert 'awards' in parsed_tender\n for award in parsed_tender['awards']:\n assert 'items' in award\n\n\ndef test_get_field():\n tender = parse_tender(deepcopy(get_test_data('data.json')))\n assert get_field(tender, 'buyer') == tender['procuringEntity']\n assert get_field(tender, 'awards') == tender['awards']\n assert get_field(tender, 'contracts') == tender['contracts']\n\n\ndef test_get_tags():\n tender = parse_tender(deepcopy(get_test_data('data.json')))\n tags = get_tags_from_tender(tender)\n assert isinstance(tags, list)\n","sub_path":"tests/test_helpers.py","file_name":"test_helpers.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"297499182","text":"import pytest\nfrom fixture.application import Application\nfrom data.user import User\n\n\nfixture = None\n\n\n@pytest.fixture\ndef app():\n global fixture\n\n if fixture is None:\n fixture = Application()\n elif not fixture.is_valid():\n fixture = Application()\n\n fixture.session.ensure_login(User.ADMIN)\n\n return fixture\n\n\n@pytest.fixture(scope=\"session\", autouse=True)\ndef stop(request):\n global fixture\n\n def finalizer():\n fixture.session.ensure_logout()\n fixture.destroy()\n\n request.addfinalizer(finalizer)\n return fixture\n\n","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"2591034","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# @File : format_table.py\n# @Author: gaofzhan\n# @Email: gaofeng.a.zhang@ericssoin.com\n# @Date : 2020/12/4 10:35\n# @Desc :\nimport time\nimport datetime\n\nTABLE_BORDER_TAG = '+-', '-+'\nROW_TAG = '|'\n\n\ndef table_format(output):\n result = list()\n output_line_list = output.split(\"\\n\")\n border_tags = list()\n for index in range(len(output_line_list)):\n output_line = output_line_list[index]\n if output_line.startswith(TABLE_BORDER_TAG[0]) and output_line.endswith(TABLE_BORDER_TAG[1]):\n border_tags.append(index)\n if len(border_tags) != 3 and border_tags[1] - border_tags[0] != 2:\n raise RuntimeError('unexpeted output format')\n\n title_line = output_line_list[border_tags[0] + 1]\n title_list = [i.strip() for i in title_line.split(ROW_TAG) if i != '']\n\n body_lines = output_line_list[border_tags[1] + 1:border_tags[2]]\n\n for body_line in body_lines:\n item_info_dict = dict()\n body_info = [i.strip() for i in body_line.split(ROW_TAG) if i != '']\n for index in range(len(title_list)):\n item_key = title_list[index]\n item_value = body_info[index]\n item_info_dict[item_key] = item_value\n result.append(item_info_dict)\n\n return result\n\n\ndef time_format(item):\n if 'T' in item and 'Z' in item:\n temp = \"%Y-%m-%dT%H:%M:%SZ\"\n elif '.' in item and 'T' in item:\n temp = \"%Y-%m-%dT%H:%M:%S.%f\"\n else:\n raise Exception('unknown time template')\n d = datetime.datetime.strptime(item, temp)\n t = d.timetuple()\n time_stamp = int(time.mktime(t))\n return time_stamp\n\n# import json\n# json.loads('{\"ovs_hybrid_plug\": \"False\", \"vhostuser_socket\": \"/var/run/openvswitch/vhu0c3c8403-6f\", \"datapath_type\": \"netdev\", \"vhostuser_mode\": \"server\", \"port_filter\": \"False\", \"vhostuser_ovs_plug\": \"True\"}')\n#\n\n# json.loads(\"{'id':'id'}\".replace(\"'\", '\"'))\n","sub_path":"gzbj/optimus_2.1/optimus/backend/myBluePrint/ericic_v2/common/format_tools.py","file_name":"format_tools.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"601491118","text":"\n\n\"\"\"Pmaster URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom core.views import *\n\nurlpatterns = [\n url(r'^$',index),\n url(r'^Index',index),\n url(r'^Noticias',Noticias),\n url(r'^Administracao_de_redes',Administracao_de_redes),\n url(r'^Administracao',Administracao),\n url(r'^Cadastrar_disciplina',Cadastrar_disciplina),\n url(r'^Cadastrar_usuario',Cadastrar_usuario),\n url(r'^Comunicacao_e_expressao',Comunicacao_e_expressao),\n url(r'^Contato',Contato),\n url(r'^Lista_de_curso',Lista_de_curso),\n url(r'^Logica_programacao',Logica_programacao),\n url(r'^Login',Login),\n url(r'^Recuperar_senha',Recuperar_senha),\n url(r'^Sistemas_informacao',Sistemas_informacao),\n url(r'^Rede_computadores',Rede_computadores),\n url(r'^admin/', admin.site.urls),\n]\n","sub_path":"Pmaster/Pmaster/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"195020030","text":"import random\n\n\ndef printBoard(board):\n print(' | |')\n print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])\n print(' | |')\n print('----------')\n print(' | |')\n print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])\n print(' | |')\n print('----------')\n print(' | |')\n print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])\n print(' | |')\n\n\ndef isWinner(board, current_player):\n return ((board[7] == current_player and board[8] == current_player\n and board[9] == current_player)\n or (board[4] == current_player and board[5] == current_player\n and board[6] == current_player)\n or (board[1] == current_player and board[2] == current_player\n and board[3] == current_player)\n or (board[7] == current_player and board[4] == current_player\n and board[1] == current_player)\n or (board[8] == current_player and board[5] == current_player\n and board[2] == current_player)\n or (board[9] == current_player and board[6] == current_player\n and board[3] == current_player)\n or (board[7] == current_player and board[5] == current_player\n and board[3] == current_player)\n or (board[9] == current_player and board[5] == current_player\n and board[1] == current_player))\n\ndef makeMove(board, current_player, move):\n board[move]=current_player\n\n\n\ndef boardCopy(board):\n cloneBoard=[]\n for pos in board:\n cloneBoard.append(pos)\n\n return cloneBoard \n\n \ndef isSpaceAvailable(board, move):\n return board[move] == ' '\n\n\ndef getRandomMove(board,moves):\n\n availableMoves = []\n for move in moves:\n\n if isSpaceAvailable(board,move):\n availableMoves.append(move)\n\n if availableMoves.__len__() !=0:\n return random.choice(availableMoves)\n\n else:\n return None \n\n\n\ndef makeComputerMove(board, computerPlayer):\n \n if computerPlayer == 'X':\n humanPlayer = 'O'\n\n else:\n humanPlayer='X'\n\n\n for pos in range(1,10):\n\n clone=boardCopy(board)\n\n if isSpaceAvailable(clone,pos):\n makeMove(clone,computerPlayer, pos)\n\n if isWinner(clone,computerPlayer):\n return pos \n\n \n for pos in range(1,10):\n\n clone=boardCopy(board)\n\n if isSpaceAvailable(clone,pos):\n makeMove(clone,humanPlayer, pos)\n\n if isWinner(clone,humanPlayer):\n return pos \n\n \n # Occupy the Center position \n\n if isSpaceAvailable(board,5): \n return 5 \n\n \n # Occupy Corner positions \n\n move = getRandomMove(board, [1,3,7,9])\n if move is not None:\n return move\n\n # Occupy the rest \n\n return getRandomMove(board, [2,4,6,8])\n\n\ndef makePlayerMove(board):\n\n move = ' '\n while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceAvailable(board, int(move)):\n print('What is your next move? (choose between 1-9)')\n move=int(input(\"#nr \").strip())\n print('\\n')\n return move\n\n\ndef main():\n\n while True:\n def isBoardOccupied(board):\n\n for pos in range(1,10):\n if isSpaceAvailable(board,pos):\n return False\n return True\n\n board= [' '] * 10\n player, computer = 'X', 'O'\n turn = \"human\"\n print(\"The \"+ turn+ \" will start the game\")\n isGameRunning=True\n\n while isGameRunning:\n\n if turn == \"human\":\n printBoard(board)\n move=makePlayerMove(board)\n makeMove(board,player,move)\n if isWinner(board,player):\n printBoard(board)\n print(\"You won the game!\")\n isGameRunning=False\n else: \n if isBoardOccupied(board):\n print(\"Game is a tie\")\n break\n else:\n # turn human # Computers turn\n turn = \"computer\"\n \n else:\n move = makeComputerMove(board, computer)\n makeMove(board, computer, move)\n if isWinner(board, computer):\n printBoard(board)\n print('You loose!')\n isGameRunning=False\n else:\n\n if isBoardOccupied(board):\n print(\"Game is a tie\")\n break\n else:\n # turn human # Computers turn\n turn = \"human\"\n\n\n\nmain()\n\n\n\n\n","sub_path":"tic_tac_toe_functions_and_AI.py","file_name":"tic_tac_toe_functions_and_AI.py","file_ext":"py","file_size_in_byte":4764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"490396510","text":"import json\n\ndef dump(filename, thing):\n dumpfile = open(filename, 'w')\n dumpfile.write(json.dumps(thing))\n print('written JSON file '+filename)\n\ndef load(filename):\n loadfile = open(filename, 'r')\n thing = json.loads(loadfile.read())\n print('read JSON file '+filename)\n return thing\n","sub_path":"input_processing/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"635317750","text":"\n\n#calss header\nclass _TENDENTIOUS():\n\tdef __init__(self,): \n\t\tself.name = \"TENDENTIOUS\"\n\t\tself.definitions = [u'(of speech or writing) expressing or supporting a particular opinion that many other people disagree with']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_tendentious.py","file_name":"_tendentious.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"384523577","text":"import os\n\n\ndef wc(file_):\n \"\"\"Takes an absolute file path/name, calculates the number of\n lines/words/chars, and returns a string of these numbers + file, e.g.:\n 3 12 60 /tmp/somefile\n (both tabs and spaces are allowed as separator)\"\"\"\n file_name = os.path.abspath(file_)\n f = open(file_name, 'r')\n text = f.read()\n f.close()\n char = len(text)\n line = len(text.splitlines())\n word = len(text.split())\n return f'{line} {word} {char} /tmp/{file_name}'\n\n\nif __name__ == '__main__':\n # make it work from cli like original unix wc\n import sys\n if len(sys.argv) > 1:\n print(wc(sys.argv[1:]))\n","sub_path":"125_algorithms/_examples/_algorithms_challenges/pybites/beginner/096_build_unix_wc_program/save5_passed.py","file_name":"save5_passed.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"66129846","text":"import pandas as pd\nimport numpy as np\nfrom xgboost.sklearn import XGBClassifier\nfrom sklearn.linear_model import LogisticRegression\nimport time\nfrom sklearn.metrics import log_loss\nfrom sklearn.cross_validation import StratifiedKFold\nimport pickle\n\nstime = time.time()\n\nnclass=3\n\ntrainb=np.loadtxt(\"train_stage1.csv\")\ntestb=np.loadtxt(\"pred_stage1.csv\")\ntarget=pd.read_csv('target.csv',index_col=0)\nnf=10\n\noutcome=target['status_group']\n\ncclf1=XGBClassifier(max_depth=7,\n \tlearning_rate= 0.02358,\n \tn_estimators=189,\n \tgamma=0.07479,\n \tmin_child_weight=3.0666,\n \tsubsample=0.49698,\n \tcolsample_bytree=0.9517,\n \treg_alpha=0.2065,\n \tobjective='multi:softmax')\n\n \ncclf2=LogisticRegression(C=1200,max_iter=800)\n\ncclfs=[cclf1, cclf2]\n\nprint (\"Start Stacking Models\")\neval_rec=np.zeros((nf,len(cclfs)))\nblend_temp=np.zeros((trainb.shape[0],nclass))\nblend_sub_temp=np.zeros((testb.shape[0],nclass))\nblend_train=np.zeros((trainb.shape[0],nclass*len(cclfs)))\nblend_sub=np.zeros((testb.shape[0],nclass*len(cclfs)))\n\nfor j, clf in enumerate(cclfs):\n print (str(j)+\"th Classifier\")\n ### K-Fold with Shufffle\n skf = list(StratifiedKFold(outcome, nf))\n for i in range(nf):\n train, test=skf[i]\n xtrain, xtest = trainb[train,:], trainb[test,:]\n ytrain, ytest = outcome[train], outcome[test]\n clf.fit(xtrain, ytrain)\n path = 'save/stage2clf'+str(j)+str(i)+'.pickle'\n file = open(path,'wb')\n pickle.dump(clf,file)\n ytest_pred = clf.predict_proba(xtest)\n blend_temp[test]=ytest_pred\n sub_pred = clf.predict_proba(testb)\n \n if i==0:\n blend_sub_temp=sub_pred\n else:\n blend_sub_temp=blend_sub_temp+sub_pred\n \n print (i, log_loss(ytest,ytest_pred), (time.time()-stime))\n eval_rec[i,j]=log_loss(ytest,ytest_pred)\n blend_train[:,nclass*j:nclass*j+nclass]=blend_temp\n blend_sub[:,nclass*j:nclass*j+nclass]=blend_sub_temp/float(nf)\n \nnp.savetxt(\"train_stage2.csv\",blend_train) \nnp.savetxt(\"pred_stage2.csv\",blend_sub) \nnp.savetxt(\"outcome.txt\",outcome) \n","sub_path":"final/src/model2_best_score_code/train/stage2.py","file_name":"stage2.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"136386978","text":"import tensorflow as tf\nimport numpy as np\nfrom PIL import Image\nimport os\n\nfrom tensorflow.python.keras.callbacks import TensorBoard\n\ntbCallBack = TensorBoard(log_dir='./logs') # log 目录\n\ntrain_path = '../data/mnist_image_label/mnist_train_jpg_60000/'\ntrain_txt = '../data/mnist_image_label/mnist_train_jpg_60000.txt'\ntest_path = '../data/mnist_image_label/mnist_test_jpg_10000/'\ntest_txt = '../data/mnist_image_label/mnist_test_jpg_10000.txt'\n\nx_train_save_path = '../data/mnist_image_label/mnist_x_train.npy'\ny_train_save_path = '../data/mnist_image_label/mnist_y_train.npy'\nx_test_save_path = '../data/mnist_image_label/mnist_x_test.npy'\ny_test_save_path = '../data/mnist_image_label/mnist_y_test.npy'\n\n\ndef generate(path, txt):\n f = open(txt, 'r')\n contents = f.readlines()\n f.close()\n x, y_ = [], []\n for content in contents:\n value = content.split()\n img_path = path + value[0]\n img = Image.open(img_path)\n img = np.array(img.convert('L'))\n img = img / 255.\n x.append(img)\n y_.append(value[1])\n print('loading: ' + content)\n\n x = np.array(x)\n y_ = np.array(y_)\n y_ = y_.astype(np.int64)\n return x, y_\n\n\nif os.path.exists(x_train_save_path) \\\n and os.path.exists(y_train_save_path) \\\n and os.path.exists(x_test_save_path) \\\n and os.path.exists(y_test_save_path):\n print('------------load datasets-------------')\n x_train_save = np.load(x_train_save_path)\n y_train = np.load(y_train_save_path)\n x_test_save = np.load(x_test_save_path)\n y_test = np.load(y_test_save_path)\n\n x_train = np.reshape(x_train_save, (len(x_train_save), 28, 28))\n x_test = np.reshape(x_test_save, (len(x_test_save), 28, 28))\nelse:\n print('------------generate datasets-------------')\n x_train, y_train = generate(train_path, train_txt)\n x_test, y_test = generate(test_path, test_txt)\n\n print('------------save datasets-------------')\n x_train_save = np.reshape(x_train, (len(x_train), -1))\n x_test_save = np.reshape(x_test, (len(x_test), -1))\n np.save(x_train_save_path, x_train_save)\n np.save(y_train_save_path, y_train)\n np.save(x_test_save_path, x_test_save)\n np.save(y_test_save_path, y_test)\n\nmodel = tf.keras.models.Sequential(\n [\n tf.keras.layers.Flatten(), # 将输入特征拉直\n tf.keras.layers.Dense(128, activation='relu'), # 此层神经元数量为经验值\n tf.keras.layers.Dense(10, activation='softmax')\n ]\n)\n\nmodel.compile(\n optimizer='adam', # 优化器\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), # 损失函数(已经过概率化分布)\n metrics=['sparse_categorical_accuracy']\n)\n\nmodel.fit(x_train, y_train, batch_size=32, epochs=10, validation_data=(x_test, y_test), validation_freq=1,\n callbacks=[tbCallBack])\nmodel.summary()\n","sub_path":"03tensorflow/13GenerateData.py","file_name":"13GenerateData.py","file_ext":"py","file_size_in_byte":2870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"197726771","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 11 10:26:33 2018\n\n@author: botan\n\"\"\"\n\nfrom rdkit import Chem\nimport UsefulFunc\nimport ast\nimport numpy as np\nimport os\nimport itertools\nimport sys\nfrom Bio.PDB import *\nimport fileinput\nimport json\n\ndef change_Fe_charge(file_pdbqt):\n for line in fileinput.input(file_pdbqt, inplace = 1):\n print(line.replace(\"0.000 Fe\", \"2.000 Fe\"))\n\n\n\nparser = PDBParser(PERMISSIVE = 1, QUIET = True)\npath_to_vina = sys.argv[1] \npath_to_utilites = sys.argv[2] \nCYP = sys.argv[3]\nf2 = sys.argv[4] # path to unknown database\n\nparser = PDBParser(PERMISSIVE = 1)\npath_to_vina = sys.argv[1] \npath_to_utilites = sys.argv[2] \nCYP = sys.argv[3]\nf2 = sys.argv[4]\n\nf1 = 'known_db/{0}/{0}_known_ligands.sdf'.format(CYP)\nsimilar_molecules = UsefulFunc.compare_molecules(f1, f2)\nos.makedirs('pdbqt_prot', exist_ok = True)\nos.makedirs('pdbqt_lig', exist_ok = True)\nos.makedirs('inFiles', exist_ok = True)\nunknown_db = Chem.SDMolSupplier(f2)\npath_to_ligand = '../known_db/{0}/PDBs/'.format(CYP)\n\nenergy_range = 5\nexhaustiveness = 32\ncpu = 24\nnum_modes = 20\n\nif similar_molecules.keys():\n known_db = Chem.SDMolSupplier(f1)\n for molecule in known_db:\n if molecule.GetProp('_Name') in similar_molecules.keys():\n boxSize = np.array(ast.literal_eval(molecule.GetProp('box_size_xyz')))+2\n boxXYZ = np.array(ast.literal_eval(molecule.GetProp('box_center_xyz')))\n feXYZ = np.array(ast.literal_eval(molecule.GetProp('fe_xyz')))\n feVectors = np.array(ast.literal_eval(molecule.GetProp('fe_vectors')))\n TrM = np.array(ast.literal_eval(molecule.GetProp('tr_mat'))) \n structure = parser.get_structure(\"REC\", 'proteins/{0}.pdb'.format(CYP))\n for residue in structure.get_residues():\n if residue.get_resname() == \"HEM\":\n heme = residue\n for residue in structure.get_residues():\n if (residue.get_resname() == \"CYS\") and (UsefulFunc.distance(residue['SG'].get_coord(), heme['FE'].get_coord()) < 3):\n cys = residue\n T = [[1, 0, 0, - heme['FE'].get_coord()[0] + feXYZ[0]],\n [0, 1, 0, - heme['FE'].get_coord()[1] + feXYZ[1]],\n [0, 0, 1, - heme['FE'].get_coord()[2] + feXYZ[2]], \n [0, 0, 0, 1]]\n structure = UsefulFunc.transtate_structure(structure, np.array(ast.literal_eval(molecule.GetProp('rot_mat'))), T)\n io = PDBIO()\n io.set_structure(structure)\n io.save('proteins/{0}-{1}.pdb'.format(CYP, molecule.GetProp('_Name')))\n os.chdir('pdbqt_prot')\n os.system('{0}/prepare_receptor4.py -r ../proteins/{1}-{2}.pdb'.format(path_to_utilites, CYP, molecule.GetProp('_Name')))\n change_Fe_charge('{0}-{1}.pdbqt'.format(CYP, molecule.GetProp('_Name')))\n os.chdir('../pdbqt_lig')\n for ligand in similar_molecules[molecule.GetProp('_Name')]:\n os.system('{0}/prepare_ligand4.py -l {1}{2}.pdb'.format(path_to_utilites, path_to_ligand, ligand))\n fOut = open('../inFiles/vina_{0}_{1}.in'.format(CYP, ligand), 'w')\n fOut.write('receptor = ../../pdbqt_prot/{0}-{1}.pdbqt\\nligand = ../../pdbqt_lig/{2}.pdbqt\\n\\n'.format(CYP, molecule.GetProp('_Name'), ligand))\n fOut.write('center_x = {0}\\ncenter_y = {1}\\ncenter_z = {2}\\n\\n'.format(*boxXYZ))\n fOut.write('size_x = {0}\\nsize_y = {1}\\nsize_z = {2}\\n\\n'.format(*boxSize))\n fOut.write('energy_range = {0}\\nnum_modes = {1}\\nexhaustiveness = {2}\\ncpu = {3}\\n'.format(energy_range, num_modes, exhaustiveness, cpu))\n fOut.close()\n os.chdir('../')\nelse:\n with open('cavities_parm.json', 'r') as f:\n cavity_data = json.load(f)\n print(cavity_data[CYP][0])\n boxSize = np.array(cavity_data[CYP][0])\n boxXYZ = np.array(cavity_data[CYP][1])\n feXYZ = np.array(cavity_data[CYP][2])\n TrM = np.array(cavity_data[CYP][3]) \n RotM = np.array(cavity_data[CYP][4]) \n structure = parser.get_structure(\"REC\", 'proteins/{0}.pdb'.format(CYP))\n for residue in structure.get_residues():\n if residue.get_resname() == \"HEM\":\n heme = residue\n for residue in structure.get_residues():\n if (residue.get_resname() == \"CYS\") and (UsefulFunc.distance(residue['SG'].get_coord(), heme['FE'].get_coord()) < 3):\n cys = residue\n T = [[1, 0, 0, - heme['FE'].get_coord()[0] + feXYZ[0]],\n [0, 1, 0, - heme['FE'].get_coord()[1] + feXYZ[1]],\n [0, 0, 1, - heme['FE'].get_coord()[2] + feXYZ[2]], \n [0, 0, 0, 1]]\n structure = UsefulFunc.transtate_structure(structure, RotM, T)\n io = PDBIO()\n io.set_structure(structure)\n io.save('proteins/{0}_R.pdb'.format(CYP))\n os.chdir('pdbqt_prot')\n os.system('{0}/prepare_receptor4.py -r ../proteins/{1}_R.pdb'.format(path_to_utilites, CYP))\n change_Fe_charge('{0}_R.pdbqt'.format(CYP))\n os.chdir('../pdbqt_lig')\n for ligand in unknown_db:\n print(os.system('pwd'))\n os.system('{0}prepare_ligand4.py -l ../unknown_db/PDBs/{1}.pdb'.format(path_to_utilites, ligand.GetProp('_Name')))\n fOut = open('../inFiles/vina_{0}_{1}.in'.format(CYP, ligand.GetProp('_Name')), 'w')\n fOut.write('receptor = ../../pdbqt_prot/{0}_R.pdbqt\\nligand = ../../pdbqt_lig/{1}.pdbqt\\n\\n'.format(CYP, ligand.GetProp('_Name')))\n fOut.write('center_x = {0}\\ncenter_y = {1}\\ncenter_z = {2}\\n\\n'.format(*boxXYZ))\n fOut.write('size_x = {0}\\nsize_y = {1}\\nsize_z = {2}\\n\\n'.format(*boxSize))\n fOut.write('energy_range = {0}\\nnum_modes = {1}\\nexhaustiveness = {2}\\ncpu = {3}\\n'.format(energy_range, num_modes, exhaustiveness, cpu))\n fOut.close()\n os.chdir('../')\n","sub_path":"prepare_for_autodock.py","file_name":"prepare_for_autodock.py","file_ext":"py","file_size_in_byte":5813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"387593977","text":"\"\"\"\nMurlan Card Game (Single Player) by Denis Ismailaj\n\"\"\"\nimport simpleguitk as simplegui\nfrom operator import itemgetter\nimport random\n\n\nclass Murlan(object):\n def __init__(self, width, height):\n self.width = width\n self.height = height\n self.user_deck = []\n self.pc_deck = []\n self.ui_bounds = {} # {nr: [top-left, top-right, bottom-left, bottom-right]}\n self.selection = []\n \"\"\"\n Cards are of the form (int1, int2)\n where int1 represents the card:\n 3 - 10 => itself\n 11 -> J | 12 -> Q | 13 -> K | 14 -> A\n 15 -> 2 | 16 -> BJ | 17 -> RJ\n int2 represents the suit:\n 0->Clubs | 1->Diamonds\n 2->Hearts | 3->Spades\n None->used for Jokers\n \"\"\"\n self.connection1 = False\n self.connection2 = False\n self.connection3 = False\n self.flush_status = False\n self.player_turn = True\n self.background = None\n self.button_img = None\n self.button2_img = None\n self.on_table = []\n # [card, type] for example: [7, 4] for bomb, [4, 2] for double, [5, 3] for trio, [3, 1] for single\n # also: [(4, 12), S] for straight and [(8, 8), F] for flush (if enabled)\n self.card_list = [(16, None), (17, None)] # Already assigned black and red joker\n\n # Setting up frame\n self.frame = simplegui.create_frame(\"Murlan: Card Game\", self.width, self.height, 100)\n self.frame.set_draw_handler(self.draw)\n self.frame.set_mouseclick_handler(self.click)\n self.frame.add_button(\"New Game\", self.new_game, 50)\n self.frame.add_label(\"------------------\")\n self.frame.add_button(\"Toggle Flush\", self.flush, 50)\n self.label = self.frame.add_label(\"Flush is disabled\")\n\n def new_game(self):\n self.reset()\n self.get_cards()\n self.deal_cards()\n self.set_bounds()\n self.loader()\n try:\n self.frame.start()\n except:\n pass\n\n def reset(self):\n self.user_deck = []\n self.pc_deck = []\n self.ui_bounds = {}\n self.selection = []\n self.flush_status = False\n self.player_turn = True\n self.on_table = []\n self.card_list = [(16, None), (17, None)]\n\n def get_cards(self):\n for i in range(3, 16):\n for k in range(4):\n self.card_list.append((i, k))\n random.shuffle(self.card_list)\n\n def deal_cards(self):\n for i in range(18):\n rand_a = random.randrange(len(self.card_list))\n self.user_deck.append(self.card_list[rand_a])\n self.card_list.pop(rand_a)\n rand_b = random.randrange(len(self.card_list))\n self.pc_deck.append(self.card_list[rand_b])\n self.card_list.pop(rand_b)\n\n def click(self, pos):\n if self.player_turn:\n ordered = sorted(self.user_deck, key=itemgetter(0), reverse=True)\n if 485 >= pos[1] >= 335:\n for i in self.ui_bounds.keys():\n if self.ui_bounds[i][0][0] <= pos[0] <= self.ui_bounds[i][2][0]:\n if ordered[i] not in self.selection:\n self.selection.append(ordered[i])\n else:\n self.selection.remove(ordered[i])\n\n elif 700 - self.button_img.get_width() / 2 <= pos[0] <= 700 + self.button_img.get_width() / 2:\n if 245 - self.button_img.get_height() / 2 <= pos[1] <= 245 + self.button_img.get_height() / 2 \\\n and self.validate():\n self.on_table = self.convert()\n self.user_deck = [x for x in self.user_deck if x not in self.selection]\n self.selection = []\n elif 290 - self.button_img.get_height() / 2 <= pos[1] <= 290 + self.button_img.get_height() / 2 \\\n and self.player_turn:\n self.find_turn(\"Pass\")\n\n def find_turn(self, source):\n pass\n\n def think(self):\n pass\n\n def convert(self):\n ordered = sorted(self.selection, key=itemgetter(0), reverse=True)\n if len(self.selection) <= 4 and all(i[0] == self.selection[0][0] for i in self.selection):\n return [self.selection[0][0], len(self.selection)]\n elif all(ordered[i] == ordered[i - 1] for i in range(1, len(ordered))) and len(ordered) >= 5:\n if self.flush_status and all(i[1] == self.card_list[0][1] for i in self.card_list):\n return [(ordered[0][0], ordered[-1][0]), \"F\"]\n else:\n return [(ordered[0][0], ordered[-1][0]), \"S\"]\n\n def validate(self):\n check, x = self.convert(), self.on_table\n if check is None:\n return False\n elif not x:\n return True\n elif ((check[1] is \"F\" and not\n (x[1] is \"F\" and (not x[0][1] - x[0][0] == check[0][1] - check[0][0] or check[0][0] != x[0][0] + 1))) or\n (check[1] is \"S\" and x[1] is \"S\" and x[0][1] - x[0][0] == check[0][1] - check[0][0] and\n check[0][0] == x[0][0] + 1) or (check[1] is 4 and not (x[1] is 4 and check[0] < x[0]) or 1 <=\n check[1] == x[1] <= 3 and check[0] > x[1])):\n return True\n else:\n return False\n\n def flush(self):\n self.flush_status = not self.flush_status\n if self.flush_status:\n self.label.set_text(\"Flush is enabled\")\n else:\n self.label.set_text(\"Flush is disabled\")\n\n def loader(self):\n try:\n self.background = simplegui.load_image(\"http://i.imgur.com/W1wOck5.jpg\")\n self.connection1 = True\n except:\n self.frame.set_canvas_background(\"#118e07\")\n\n try:\n self.button_img = simplegui.load_image(\"http://i.imgur.com/bAPeWIY.png\")\n self.connection2 = True\n except:\n pass\n\n try:\n self.button2_img = simplegui.load_image(\"http://i.imgur.com/mYnRQGi.png\")\n self.connection3 = True\n except:\n pass\n\n def set_bounds(self):\n self.ui_bounds = {}\n west_point = 400 - ((len(self.user_deck) - 1) * 35 + 100) / 2\n\n for i in range(len(self.user_deck)):\n first_point = (west_point + 35 * i, self.height - 165)\n if i < len(self.user_deck) - 1:\n self.ui_bounds[i] = [\n first_point, (first_point[0] + 35, self.height - 165),\n (first_point[0] + 35, self.height - 15), (first_point[0], self.height - 15)\n ]\n else:\n self.ui_bounds[i] = [\n first_point, (first_point[0] + 100, 500 - 165),\n (first_point[0] + 100, self.height - 15), (first_point[0], self.height - 15)\n ]\n\n def draw(self, canvas):\n if self.connection1:\n canvas.draw_image(\n self.background, (self.background.get_width() / 2, self.background.get_height() / 2),\n (self.background.get_width(), self.background.get_height()), (self.width / 2, self.height / 2),\n (self.width + 3, self.height + 3)\n )\n\n if self.connection2 and self.player_turn:\n canvas.draw_image(\n self.button_img, (self.button_img.get_width() / 2, self.button_img.get_height() / 2),\n (self.button_img.get_width(), self.button_img.get_height()), (700, 245),\n (115, 36)\n )\n\n if self.connection3 and self.player_turn:\n canvas.draw_image(\n self.button2_img, (self.button2_img.get_width() / 2, self.button2_img.get_height() / 2),\n (self.button2_img.get_width(), self.button2_img.get_height()), (700, 290),\n (115, 36)\n )\n\n self.set_bounds()\n for i in self.ui_bounds:\n canvas.draw_polygon(self.ui_bounds[i], 2, 'Black', fill_color=\"White\")\n\n translator = {11: \"J\", 12: \"Q\", 13: \"K\", 14: \"A\", 15: \"2\"}\n suits_maker = {0: \"♣\", 1: \"♦\", 2: \"♥\", 3: \"♠\"}\n west_point = 400 - ((len(self.user_deck) - 1) * 35 + 100) / 2\n ordered = sorted(self.user_deck, key=itemgetter(0), reverse=True)\n\n for i in ordered:\n if i[0] == 16 or i[0] == 17:\n color = {16: \"Black\", 17: \"Red\"}\n if ordered.index(i) == len(ordered) - 1:\n for k in \"JOKER\":\n position = (\n self.width / 2 + ((len(ordered) - 1) * 35) / 2 +\n (0 - self.frame.get_canvas_textwidth(k, 24) / 2), 372 + 25 * \"JOKER\".index(k)\n )\n canvas.draw_text(k, position, 20, color[i[0]], \"sans-serif\")\n else:\n for k in \"JOKER\":\n position = (\n west_point + 35 * ordered.index(i) +\n (17.5 - self.frame.get_canvas_textwidth(k, 24) / 2), 372 + 25 * \"JOKER\".index(k)\n )\n canvas.draw_text(k, position, 20, color[i[0]], \"sans-serif\")\n else:\n if ordered.index(i) == len(ordered) - 1:\n start_point = self.width / 2 + ((len(ordered) - 1) * 35) / 2 - 50\n position1 = (\n start_point + (15 - self.frame.get_canvas_textwidth(translator.get(i[0], i[0]), 24) / 2), 372\n )\n position2 = (start_point + (50 - self.frame.get_canvas_textwidth(suits_maker[i[1]], 52) / 2),\n self.height - 60)\n position3 = (\n start_point + (85 - self.frame.get_canvas_textwidth(translator.get(i[0], i[0]), 24) / 2),\n self.height - 20\n )\n canvas.draw_text(translator.get(i[0], i[0]), position1, 24, \"Black\", \"sans-serif\")\n canvas.draw_text(suits_maker[i[1]], position2, 52, \"Black\", \"sans-serif\")\n canvas.draw_text(translator.get(i[0], i[0]), position3, 24, \"Black\", \"sans-serif\")\n else:\n position = (\n west_point + 35 * ordered.index(i) +\n (17.5 - self.frame.get_canvas_textwidth(translator.get(i[0], i[0]), 24) / 2), 372\n )\n suit_position = (\n west_point + 35 * ordered.index(i) +\n (17.5 - self.frame.get_canvas_textwidth(suits_maker.get(i[1], i[1]), 24) / 2), position[1] + 30\n )\n canvas.draw_text(translator.get(i[0], i[0]), position, 24, \"Black\", \"sans-serif\")\n canvas.draw_text(suits_maker[i[1]], suit_position, 24, \"Black\", \"sans-serif\")\n\n\nGame = Murlan(800, 500)\nGame.new_game()\n","sub_path":"Murlan.py","file_name":"Murlan.py","file_ext":"py","file_size_in_byte":10999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"496748320","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 ('Emprestimo', '0006_auto_20141007_2348'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='consignado',\n name='convenente',\n field=models.ForeignKey(to='Emprestimo.Convenente', blank=True),\n ),\n migrations.AlterField(\n model_name='consignado',\n name='data_encaminhado',\n field=models.DateField(default=datetime.date(2014, 10, 8)),\n ),\n ]\n","sub_path":"Emprestimo/migrations/0007_auto_20141008_1759.py","file_name":"0007_auto_20141008_1759.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"202339072","text":"\n\n\nimport random\nimport time\n\ndef kUniqueSubstring(l, k):\n d={}\n pointer =-1\n maxLen =0 \n for i in range(len(l)):\n pointer+=1\n while True:\n if pointer == len(l):\n pointer -=1\n break\n dkeys = d.keys()\n if l[pointer] not in dkeys:\n if len(dkeys) == k:\n pointer-=1\n break\n d[l[pointer]] = 1\n pointer +=1\n else:\n d[l[pointer]] +=1\n pointer +=1\n \n maxLen = max(maxLen, pointer-i+1)\n d[l[i]] -=1\n if d[l[i]] == 0:\n del d[l[i]]\n \n return maxLen\n\n#slow\ndef length_of_substring(s, k):\n # simple sol\n maxLen = 0\n\n for i in range(len(s)):\n set1 = set()\n uniqueEle = 0\n if len(s)-i < maxLen:\n break\n for j in range(i,len(s)):\n if s[j] not in set1:\n uniqueEle+=1\n if uniqueEle>k:\n maxLen = max(maxLen, j-i)\n break\n set1.add(s[j])\n if j == len(s)-1:\n maxLen = max(maxLen, j-i+1)\n return maxLen\n \n return maxLen\n\ndef main():\n\n fruitlists = [[],[1,2,1,2,3,4,3,7,7,3,7,7],[1,2,1,2,1,2], [1,2,3,4,5,6,7,8,9], [1,2,1], [1,2,3,4,3,4,3,4,3,5,6,7,8,4,5,6,5,7,5,8], [1]]\n testlist=''\n s='abcdefghijklmnopqrstuvwxyz'\n for i in range(100000):\n testlist+=s[random.randint(0,25)]\n \n t=time.time()\n print(kUniqueSubstring(testlist, 20))\n print(time.time()-t)\n print('XXXXXXXX')\n t=time.time()\n print(length_of_substring(testlist, 20))\n print(time.time()-t)\n\n print('XXXXXXXX')\n print(kUniqueSubstring('aabasdkjhsdakjfgaskdjfgabcdeabcdeabcde',5))\n \n \n\n\n # for fruits in fruitlists:\n # print('XXXXXXXX')\n # print(kUniqueSubstring(fruits, 2))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"kUniqueSubstring_crio.py","file_name":"kUniqueSubstring_crio.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"583439707","text":"import argparse\n\nfrom tensorflow import keras\n\nfrom dataset import build_dataset\nfrom losses import CTCLoss\nfrom metrics import WordAccuracy\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-a\", \"--annotation_paths\", type=str, required=True, \n nargs=\"+\", help=\"The paths of annnotation file.\")\nparser.add_argument(\"-t\", \"--table_path\", type=str, required=True, \n help=\"The path of table file.\")\nparser.add_argument(\"-w\", \"--image_width\", type=int, default=100, \n help=\"Image width, this parameter will affect the output \"\n \"shape of the model, default is 100, so this model \"\n \"can only predict up to 24 characters.\")\nparser.add_argument(\"-b\", \"--batch_size\", type=int, default=256, \n help=\"Batch size.\")\nparser.add_argument(\"-m\", \"--model\", type=str, required=True, \n help=\"The saved model.\")\nparser.add_argument(\"--channels\", type=int, default=1, help=\"Image channels, \"\n \"0: Use the number of channels in the image, \"\n \"1: Grayscale image, \"\n \"3: RGB image\")\nparser.add_argument(\"--ignore_case\", action=\"store_true\", \n help=\"Whether ignore case.(default false)\")\nargs = parser.parse_args()\n\neval_ds, size, num_classes = build_dataset(\n args.annotation_paths,\n args.table_path,\n args.image_width,\n args.channels,\n args.ignore_case,\n batch_size=args.batch_size)\nprint(\"Num of eval samples: {}\".format(size))\n\nmodel = keras.models.load_model(args.model, compile=False)\nmodel.summary()\nmodel.compile(loss=CTCLoss(), metrics=[WordAccuracy()])\nmodel.evaluate(eval_ds)","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"593031281","text":"\"\"\"\nThis module provides utilities for basic math operations.\n\"\"\"\nfrom __future__ import division, print_function\n\nimport itertools\nimport collections\nimport numpy as np\n\n\ndef iterator_from_slice(s):\n \"\"\"\n Constructs an iterator given a slice object s.\n\n .. note::\n\n The function returns an infinite iterator if s.stop is None\n \"\"\"\n start = s.start if s.start is not None else 0\n step = s.step if s.step is not None else 1\n\n if s.stop is None:\n # Infinite iterator.\n return itertools.count(start=start, step=step)\n else:\n # xrange-like iterator that suppors float.\n return iter(np.arange(start, s.stop, step))\n\n\ndef sort_dict(d, key=None, reverse=False):\n \"\"\"\n Sorts a dict by value.\n\n Args:\n d:\n Input dictionary\n key:\n function which takes an tuple (key, object) and returns a value to\n compare and sort by. By default, the function compares the values\n of the dict i.e. key = lambda t : t[1]\n reverse:\n allows to reverse sort order.\n\n Returns:\n OrderedDict object whose keys are ordered according to their value.\n \"\"\"\n kv_items = [kv for kv in d.items()]\n\n # Sort kv_items according to key.\n if key is None:\n kv_items.sort(key=lambda t: t[1], reverse=reverse)\n else:\n kv_items.sort(key=key, reverse=reverse)\n\n # Build ordered dict.\n return collections.OrderedDict(kv_items)\n\n\ndef chunks(items, n):\n \"\"\"\n Yield successive n-sized chunks from a list-like object.\n\n >>> import pprint\n >>> pprint.pprint(list(chunks(range(1, 25), 10)))\n [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],\n [21, 22, 23, 24]]\n \"\"\"\n for i in range(0, len(items), n):\n yield items[i:i+n]\n\n\ndef min_max_indexes(seq):\n \"\"\"\n Uses enumerate, max, and min to return the indices of the values\n in a list with the maximum and minimum value:\n \"\"\"\n minimum = min(enumerate(seq), key=lambda s: s[1])\n maximum = max(enumerate(seq), key=lambda s: s[1])\n return minimum[0], maximum[0]\n","sub_path":"pymatgen/util/num_utils.py","file_name":"num_utils.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"541837244","text":"#!/usr/bin/env python3\n\nfrom nltk.tokenize import TweetTokenizer\nfrom nltk.corpus import stopwords\nimport re\nimport string\n#from nltk.stem import WordNetLemmatizer\nfrom nltk import pos_tag\nimport pandas as pd\n#from translation import bing\n#from translation.exception import TranslateError\n\nFLAGS = re.MULTILINE | re.DOTALL\ntknzrwhu = TweetTokenizer(preserve_case=False, reduce_len=True, strip_handles = False)\ntknzr = TweetTokenizer(preserve_case=False, reduce_len=True, strip_handles = True)\n\n\ndef preProcessSerie(serie):\n listatweets = []\n for line in serie:\n\n line = re.sub(r\"https?:\\/\\/\\S+\\b|www\\.(\\w+\\.)+\\S*\", \"\", line, flags=0)\n \n ht = re.compile(r'http.')\n bar = re.compile(r'//*')\n punctuation = set(string.punctuation)\n stoplist = stopwords.words('english')\n pr = [\"rt\", \"RT\", \"http\", \"...\"]\n\n pal = tknzrwhu.tokenize(line)\n\n #Abajo estaba incluido if not i.isdigit()\n pal = [i for i in pal if i not in pr\n if i not in stoplist if i not in punctuation\n if not bar.search(i) if not ht.search(i)]\n #Dentro tenia tb if d.check(str(i))\n\n l = \"\"\n for p in pal:\n l = l + \" \" + p\n\n #Descomentar si se quiere traducir\n #try:\n # l = bing(l, dst='es')\n #except TranslateError:\n # l = l\n listatweets.append(l)\n return pd.Series(listatweets)","sub_path":"Pybossa/emotion/football-master2/preprocessor.py","file_name":"preprocessor.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"80931539","text":"# demo of tree structures\n\n\nclass TreeNode:\n def __init__(self, n):\n self.val = n\n self.left = None\n self.right = None\n\n def __str__(self):\n return 'Node: {0.val}; Left Leave: {0.left.val}; Right Leave: {0.right.val}'.format(\n self)\n\n\ntr1 = TreeNode('A')\ntr2 = TreeNode('B')\ntr3 = TreeNode('C')\ntr4 = TreeNode('D')\ntr5 = TreeNode('E')\ntr6 = TreeNode('F')\ntr7 = TreeNode('G')\n\ntr1.left = tr2\ntr1.right = tr3\n\ntr2.left = tr4\ntr2.right = tr5\n\ntr3.left = tr6\ntr3.right = tr7\n\n# A\n# / \\\n# B C\n# / \\ / \\\n# D EF G\n\n\ndef DFS(tr): # depth-first Search\n if tr is None:\n return\n print(tr.val)\n DFS(tr.left)\n DFS(tr.right)\n\n\nDFS(tr1)\n'''\n>>> A\n B\n D\n E\n C\n F\n G\n'''\n","sub_path":"CH2/Andy/HW1/tree_demo.py","file_name":"tree_demo.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"298476830","text":"#we need to find the next lexiographic permutation of the given permutation and if the given permutation is last one then it should return the first permutation \n# we can do this by listing out all the permutations and then checking linearly which permutation will come next \n# the other method is as follows \ndef nextPerm(a):\n count=0\n for i in range(len(a)-2,-1,-1):\n if(a[i]a[x]):\n a[i],a[x]=a[x],a[i]\n break\n y=int((len(a)-x-1)/2)\n k=0\n for i in range(x+1,y+2):\n a[i],a[len(a)-1-k]=a[len(a)-1-k],a[i]\n k=k+1\n return a\n\na=[3,2,1]\nprint(nextPerm(a))\n","sub_path":"array/next_permutation.py","file_name":"next_permutation.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"493287874","text":"from functools import partial\nimport os\n\nfrom skimage.measure import find_contours\n\nfrom dioptas.model import OverlayModel\nfrom dioptas.model.DioptasModel import DioptasModel\nimport numpy as np\n\nfrom .util import run_coroutine, convert_array_to_bytes\n\npath = os.path.dirname(__file__)\ndata_path = os.path.join(path, '../data')\n\n\ndef connect_events(sio, session_manager):\n @sio.on('connect')\n def connect(sid, data):\n session_manager.sessions[sid] = {}\n print(sid, 'connected!')\n return sid\n\n @sio.on('disconnect')\n def disconnect(sid):\n print(sid, 'disconnected!')\n del session_manager.sessions[sid]\n\n @sio.on('init_model')\n def init_model(sid):\n with session_manager.get_session(sid) as session:\n print('init model')\n model = DioptasModel()\n model.img_changed.connect(partial(img_changed, sid), priority=True)\n model.pattern_changed.connect(partial(pattern_changed, sid))\n connect_overlay_signals(sid, model.overlay_model)\n session['model'] = model\n\n def img_changed(sid):\n session = session_manager.sessions[sid]\n model = session['model'] # type: DioptasModel\n byte_image = convert_array_to_bytes(model.img_model.img_data)\n run_coroutine(\n sio.emit('img_changed', {\n # 'filename': os.path.relpath(model.img_model.filename, os.getcwd()).replace('\\\\', '/'),\n 'filename': model.img_model.filename.replace('\\\\', '/'),\n 'image': byte_image\n })\n )\n\n def pattern_changed(sid):\n session = session_manager.sessions[sid]\n model = session['model'] # type: DioptasModel\n run_coroutine(\n sio.emit('pattern_changed',\n {'filename': model.pattern_model.pattern_filename,\n 'x': model.pattern_model.pattern.x.tolist(),\n 'y': model.pattern_model.pattern.y.tolist()})\n )\n\n @sio.on('load_dummy')\n def load_dummy(sid):\n with session_manager.get_session(sid) as session:\n model = session['model'] # type: DioptasModel\n model.load(os.path.join(data_path, 'projects', 'dummy.dio'))\n\n @sio.on('load_dummy2')\n def load_dummy2(sid):\n with session_manager.get_session(sid) as session:\n global t1\n model = session['model'] # type: DioptasModel\n model.load(os.path.join(data_path, 'projects', 'dummy2.dio'))\n\n @sio.on('load_image')\n def load_image(sid, filename):\n with session_manager.get_session(sid) as session:\n model = session['model'] # type: DioptasModel\n model.img_model.load(filename)\n\n @sio.on('load_next_image')\n def load_next_image(sid):\n with session_manager.get_session(sid) as session:\n model = session['model'] # type: DioptasModel\n model.img_model.load_next_file()\n\n @sio.on('load_previous_image')\n def load_previous_image(sid):\n with session_manager.get_session(sid) as session:\n model = session['model'] # type: DioptasModel\n model.img_model.load_previous_file()\n\n @sio.on('list_dir')\n def list_dir(sid, base_directory):\n print('listing directory: ', base_directory)\n try:\n item_list = os.listdir(base_directory)\n folders = []\n files = []\n for item in item_list:\n if os.path.isdir(os.path.join(base_directory, item)):\n folders.append(item)\n else:\n files.append(item)\n return {'folders': folders, 'files': files}\n except FileNotFoundError:\n return None\n\n @sio.on('get_image_angles')\n def get_image_angles(sid, x, y):\n session = session_manager.sessions[sid]\n model = session['model'] # type: DioptasModel\n x, y = np.array([y]), np.array([x]) # have to be swapped for pyFAI\n\n if model.calibration_model.is_calibrated:\n tth_rad = model.calibration_model.get_two_theta_img(x, y)\n tth = np.rad2deg(tth_rad)\n azi = np.rad2deg(model.calibration_model.get_azi_img(x, y))\n q = 4 * np.pi * np.sin(tth / 360 * np.pi) / model.calibration_model.wavelength / 1e10\n d = model.calibration_model.wavelength / (2 * np.sin(tth / 360 * np.pi)) * 1e10\n return {'tth': tth, 'azi': azi, 'q': q, 'd': d}\n else:\n return {'tth': None, 'azi': None, 'q': None, 'd': None}\n\n @sio.on('get_pattern_angles')\n def get_pattern_angles(sid, tth):\n session = session_manager.sessions[sid]\n model = session['model'] # type: DioptasModel\n if model.calibration_model.is_calibrated:\n q = 4 * np.pi * np.sin(tth / 360 * np.pi) / model.calibration_model.wavelength / 1e10\n d = model.calibration_model.wavelength / (2 * np.sin(tth / 360 * np.pi)) * 1e10\n return {'tth': tth, 'q': q, 'd': d}\n else:\n return {'tth': None, 'q': None, 'd': None}\n\n @sio.on('get_azimuthal_ring')\n def get_azimuthal_ring(sid, tth):\n \"\"\"\n Calculates 1-4 segments of an azimuthal ring with a Two Theta value of tth\n :param tth: Two-Theta in degrees\n :return: a dictionary with a a list of x- and y- values for each segment (up to 4)\n {'x': [seg1, seg2, ... ], 'y': [seg1, seg2,...]}\n \"\"\"\n session = session_manager.sessions[sid]\n model = session['model'] # type: DioptasModel\n if not model.calibration_model.is_calibrated:\n return {'x': None, 'y': None}\n tth = np.deg2rad(tth)\n tth_array = model.calibration_model.get_two_theta_array()\n tth_ind = find_contours(tth_array, tth)\n x = [[]] * 4\n y = [[]] * 4\n for i in range(len(tth_ind)):\n x[i] = ((tth_ind[i][:, 1] + 0.5).tolist())\n y[i] = ((tth_ind[i][:, 0] + 0.5).tolist())\n return {'x': x, 'y': y}\n\n ###################################\n # Overlay Stuff:\n ##################################\n\n def connect_overlay_signals(sid, overlay_model: OverlayModel):\n overlay_model.overlay_added.connect(partial(overlay_added, sid))\n overlay_model.overlay_changed.connect(partial(overlay_changed, sid))\n overlay_model.overlay_removed.connect(overlay_removed)\n\n def overlay_added(sid):\n session = session_manager.sessions[sid]\n model = session['model'] # type: DioptasModel\n overlay = model.overlay_model.overlays[-1]\n result = {\n 'name': overlay.name,\n 'x': overlay.x.tolist(),\n 'y': overlay.y.tolist(),\n 'offset': float(overlay.offset),\n 'scaling': float(overlay.scaling)\n }\n run_coroutine(sio.emit('overlay_added', result))\n\n def overlay_changed(sid, index):\n session = session_manager.sessions[sid]\n model = session['model'] # type: DioptasModel\n overlay = model.overlay_model.overlays[index]\n result = {\n 'name': overlay.name,\n 'x': overlay.x.tolist(),\n 'y': overlay.y.tolist(),\n 'offset': float(overlay.offset),\n 'scaling': float(overlay.scaling)\n }\n run_coroutine(sio.emit('overlay_changed',\n {\n 'index': index,\n 'overlay': result\n }))\n\n def overlay_removed(index):\n run_coroutine(sio.emit('overlay_removed', index))\n\n @sio.on('pattern_as_overlay')\n def pattern_as_overlay(sid):\n session = session_manager.sessions[sid]\n model = session['model'] # type: DioptasModel\n model.overlay_model.add_overlay_pattern(model.pattern_model.pattern)\n\n @sio.on('clear_overlays')\n def clear_overlays(sid):\n session = session_manager.sessions[sid]\n model = session['model'] # type: DioptasModel\n model.overlay_model.reset()\n\n @sio.on('set_overlay_scaling')\n def set_overlay_scaling(sid, payload):\n print('set overlay scaling', payload)\n session = session_manager.sessions[sid]\n model = session['model'] # type: DioptasModel\n model.overlay_model.set_overlay_scaling(int(payload['ind']), float(payload['scaling']))\n\n @sio.on('set_overlay_offset')\n def set_overlay_offset(sid, payload):\n print('set overlay offset', payload)\n session = session_manager.sessions[sid]\n model = session['model'] # type: DioptasModel\n model.overlay_model.set_overlay_offset(int(payload['ind']), float(payload['offset']))\n\n @sio.on('get_overlay')\n def get_overlay(sid, index):\n session = session_manager.sessions[sid]\n model = session['model'] # type: DioptasModel\n overlay = model.overlay_model.overlays[index]\n return {\n 'name': overlay.name,\n 'x': overlay.x.tolist(),\n 'y': overlay.y.tolist(),\n 'offset': float(overlay.offset),\n 'scaling': float(overlay.scaling)\n }\n\n @sio.on('get_overlays')\n def get_overlays(sid):\n session = session_manager.sessions[sid]\n model = session['model'] # type: DioptasModel\n result = []\n for overlay in model.overlay_model.overlays:\n result.append({\n 'name': overlay.name,\n 'x': overlay.x.tolist(),\n 'y': overlay.y.tolist(),\n 'offset': float(overlay.offset),\n 'scaling': float(overlay.scaling)})\n return result\n","sub_path":"dioptasserver/sio_events.py","file_name":"sio_events.py","file_ext":"py","file_size_in_byte":9632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"38373154","text":"import sqlite3\nimport re\n\nfname = input('Enter file name: ')\n#if (len(fname) < 1): fname = 'mbox.txt'\nfh = open(fname)\nfor line in fh:\n if not line.startswith('From: '): continue\n pieces = line.split()\n domain = pieces[1].split('@')[1]\n print(pieces[1], domain)\n #domain = re.findall('.*@(*)', pieces[1])\n #print(domain)\n","sub_path":"ex15.1.py","file_name":"ex15.1.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"450059446","text":"from flask import Flask\nimport pickle\nimport sklearn\nfrom flask import Flask,render_template,request\napp = Flask(__name__)\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\ndef home_page():\n if request.method == \"POST\":\n FS = int(request.form[\"FS\"])\n FU = int(request.form[\"FU\"]) \n ## load model here\n with open(\"my_model\", \"rb\") as f:\n model = pickle.load(f)\n \n \n result = model.predict([[FS, FU]]) \n if result[0] == \"YES\":\n return render_template(\"home.html\", data=[\"Sorry You might Have Diabeted Consult To Doctor\", \"red\"])\n else:\n return render_template(\"home.html\", data=[\"Congratulations you Dont Have Diabetes\", \"green\"])\n else: \n return render_template(\"home.html\")\n\n\n@app.route(\"/about\")\ndef about():\n return render_template(\"about.html\")\n\n\n\n\n@app.route(\"/profile/\")## to make an variable here inside app.route()\n#3 to recieve url parameter reciveve karne ke lie\ndef profile_name(name):\n return \"hii url \" + str(name)\n\n\n@app.route(\"/profile/\")## to make an variable here inside app.route()\n#3 to recieve url parameter reciveve karne ke lie\ndef profile_id(id):\n return \"your are requested with user \" + str(id)\n\n\n# @app.route(\"/predict\",methods=[\"POST\"])\n# def submitt_post():\n# if request.method == \"POST\":\n# FS = int(request.form[\"FS\"])\n# FU = int(request.form[\"FU\"])\n \n \n \n# ## load model here\n# with open(\"my_model\", \"rb\") as f:\n# model = pickle.load(f)\n \n \n# print(FS, FU)\n# result = model.predict([[FS, FU]]) \n# if result[0] == \"YES\":\n# return \"sorry You Might Have Diabetes\"\n# else:\n# return \"Congratulations You dont haveDiabetes\"\n# else:\n# return \"something went wrong\"\n \n\n\nif __name__ == \"__main__\":\n app.run(debug=True)## port 6000 you can change","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"371219850","text":"#!/bin/python3\nimport json\nimport sys\ntry:\n import boto3\nexcept Exception as e:\n print(e)\n print(\"Please rectify above exception and try again..!\")\n sys.exit(1)\n\ndef get_hosts(ec2_ob,fv):\n f={\"Name\":\"tag:Env\" , \"Values\": [fv]}\n hosts=[]\n for each_in in ec2_ob.instances.filter(Filters=[f]):\n hosts.append(each_in.private_ip_address)\n return hosts\n\ndef main():\n ec2_ob=boto3.resource(\"ec2\",\"ap-northeast-1\")\n db_group= get_hosts(ec2_ob, 'db')\n app_group= get_hosts(ec2_ob, 'app')\n all_groups={ 'db': db_group, 'app': app_group }\n print(json.dumps(all_groups))\n return None\n","sub_path":"ansible-dynamic-inventory.py","file_name":"ansible-dynamic-inventory.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"325847714","text":"# 1-hidden-layer network using Relu\n\nfrom network import Network\nfrom layers import Relu, Sigmoid, Linear\nfrom run_mlp import run_mlp\n\nmodel1S = Network()\nmodel1S.add(Linear('fc1', 784, 200, 0.01))\nmodel1S.add(Sigmoid('sigmoid'))\nmodel1S.add(Linear('fc2', 200, 10, 0.01))\n\nconfig1S = {\n 'learning_rate': 2e-2,\n 'weight_decay': 1.5e-3,\n 'momentum': 0.9,\n 'batch_size': 200,\n 'max_epoch': 10,\n 'disp_freq': 10,\n 'test_epoch': 1\n}\n\nrun_mlp(model1S, config1S, 'model1S')","sub_path":"codes/run_model1_Sigmoid.py","file_name":"run_model1_Sigmoid.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"530029162","text":"# Class that displays the Main GUI and handles the user interactions like Download, Search, Publish and Refresh.\r\nimport threading\r\nfrom PyQt4 import QtCore,QtGui, Qt\r\nfrom PyQt4.Qt import QMainWindow, QDialog\r\nfrom PyQt4.QtGui import QMessageBox\r\nfrom ui.UI import Ui_MainWindow\r\nfrom p2p.P2PHandler import *\r\nimport sys\r\nfrom threads.HandlerThreads import DownloadThread, ListRefreshThread\r\n \r\nclass FileSharerGUI(QMainWindow):\r\n def __init__(self,trackerIp,trackerPort=1234,ttl=2,maxKnownPeers=4,parent=None):\r\n\r\n #Initialize the UI \r\n QtGui.QWidget.__init__(self, parent)\r\n self.mainUI = Ui_MainWindow()\r\n self.mainUI.setupUi(self)\r\n self.mainUI.progressBar.hide()\r\n self.trackerIp, self.trackerPort = trackerIp,int(trackerPort)\r\n self.p2pHandler=P2PHandler()\r\n\r\n #Start the server to listen for incoming connections\r\n serverThread=threading.Thread(target=self.p2pHandler.startServer,args=[])\r\n serverThread.start()\r\n \r\n #List of available files on the network\r\n self.fileList=[] \r\n #List of connected peers\r\n self.nodeList=[]\r\n self.lock=threading.Lock()\r\n \r\n #Call this method only for peers.\r\n try:\r\n pass\r\n self.nodeList=self.p2pHandler.buildPeerList(self.trackerIp,self.trackerPort)\r\n self.fileList=self.p2pHandler.listAvailableFiles(self.trackerIp,self.trackerPort)\r\n except:\r\n traceback.print_exc()\r\n self.popupMessage('Could not connect to the tracker. Please try again after sometime.')\r\n \r\n #Run this thread only for the peers\r\n timerThread=ListRefreshThread(self)\r\n QtCore.QThreadPool.globalInstance().start(timerThread)\r\n \r\n #Populate the list of peers and available files. \r\n if self.nodeList:\r\n self.mainUI.listView_nodes.addItem('PeerIP (Total '+str(len(self.nodeList))+' online peers)')\r\n for node in self.nodeList:\r\n self.mainUI.listView_nodes.addItem(node)\r\n if self.fileList:\r\n self.mainUI.listView_files.addItem('PeerIP\\t\\tFileName')\r\n for file in self.fileList:\r\n self.mainUI.listView_files.addItem(''+(file.split(',')[0])+'\\t\\t'+(file.split(',')[1]))\r\n else:\r\n self.mainUI.listView_files.addItem('No Files are currently available to download.\\nAdd your own files to share on the network')\r\n self.mainUI.listView_files.repaint()\r\n self.mainUI.listView_nodes.repaint()\r\n \r\n #Associate the buttons to the handlers\r\n QtCore.QObject.connect(self.mainUI.btn_download, QtCore.SIGNAL('clicked()'), self.downloadHandler)\r\n QtCore.QObject.connect(self.mainUI.btn_addFile, QtCore.SIGNAL('clicked()'), self.onAddFileClicked)\r\n QtCore.QObject.connect(self.mainUI.btn_Search, QtCore.SIGNAL('clicked()'), self.onSearchClicked)\r\n QtCore.QObject.connect(self.mainUI.btn_refresh, QtCore.SIGNAL('clicked()'), self.onRefreshClicked)\r\n \r\n #Handles the downloading of files when the download button is clicked. \r\n def downloadHandler(self):\r\n self.lock.acquire()\r\n if not self.mainUI.listView_files.selectedItems():\r\n self.popupMessage('Please Select a File to Download.')\r\n return\r\n if self.mainUI.listView_files.currentRow()==0:\r\n self.popupMessage('Invalid selection. You cannot select the header to download.')\r\n return\r\n for selection in self.mainUI.listView_files.selectedItems():\r\n selectedFileName=selection.text().split()[1].strip()\r\n fileDetails=None\r\n for file in self.fileList:\r\n if selectedFileName in file.split(',')[1]:\r\n fileDetails=file\r\n peerIp,filename,filePath=fileDetails.split(',')\r\n self.mainUI.progressBar.show()\r\n self.mainUI.btn_addFile.setEnabled(False)\r\n self.mainUI.btn_download.setEnabled(False)\r\n self.mainUI.btn_refresh.setEnabled(False)\r\n self.mainUI.btn_Search.setEnabled(False)\r\n # Pass the download to the DownloadThread thread\r\n self.downloadThread=DownloadThread(self,peerIp,filePath,filename)\r\n QtCore.QObject.connect(self.downloadThread, QtCore.SIGNAL(\"update(QString)\"),self.afterDownload)\r\n self.downloadThread.start()\r\n \r\n # This method is executed after the DownloadThread finishes executing.\r\n def afterDownload(self,message):\r\n self.lock.release()\r\n self.mainUI.progressBar.hide()\r\n self.popupMessage(message)\r\n self.onRefreshClicked()\r\n self.mainUI.btn_addFile.setEnabled(True)\r\n self.mainUI.btn_download.setEnabled(True)\r\n self.mainUI.btn_refresh.setEnabled(True)\r\n self.mainUI.btn_Search.setEnabled(True)\r\n \r\n # Publishes the filename to the network.\r\n def onAddFileClicked(self):\r\n fileName=QtGui.QFileDialog.getOpenFileName(self)\r\n if fileName:\r\n try:\r\n self.fileList=self.p2pHandler.publishFilenameToTracker(fileName,self.trackerIp,self.trackerPort)\r\n print('File Published')\r\n self.mainUI.listView_files.clear()\r\n self.mainUI.listView_files.addItem('PeerIP \\t\\t\\tFileName')\r\n for listItem in self.fileList:\r\n if listItem!=\"Exists\":\r\n self.mainUI.listView_files.addItem(''+listItem.split(',')[0]+'\\t\\t'+listItem.split(',')[1])\r\n self.mainUI.listView_files.repaint()\r\n else:\r\n self.popupMessage('You have already added this file on the network.')\r\n self.onRefreshClicked()\r\n break;\r\n except:\r\n self.popupMessage('Could not connect to the tracker. Please try after sometime.')\r\n traceback.print_exc()\r\n \r\n # Searches for available files matching the search string and returns relevant results. \r\n def onSearchClicked(self):\r\n if not self.mainUI.tb_Search.text():\r\n self.popupMessage('Please Enter a Filename to Search.')\r\n self.mainUI.tb_Search.clear()\r\n return\r\n searchString=self.mainUI.tb_Search.text()\r\n try:\r\n availableFiles=self.p2pHandler.listAvailableFiles(self.trackerIp,self.trackerPort)\r\n self.mainUI.listView_files.clear()\r\n searchResults=[]\r\n if availableFiles:\r\n for file in self.fileList:\r\n if searchString.lower() in file.split(',')[1].lower():\r\n searchResults.append(''+(file.split(',')[0])+','+(file.split(',')[1]))\r\n if len(searchResults)>0:\r\n self.mainUI.listView_files.addItem('PeerIP \\t\\t\\tFileName')\r\n for item in searchResults:\r\n self.mainUI.listView_files.addItem(''+(item.split(',')[0])+'\\t\\t'+(item.split(',')[1]))\r\n self.mainUI.listView_files.repaint()\r\n else:\r\n self.popupMessage('No results found.')\r\n self.mainUI.tb_Search.clear()\r\n self.onRefreshClicked()\r\n except socket.timeout:\r\n self.popupMessage('Could not connect to the tracker. Please try after sometime.')\r\n except:\r\n self.popupMessage('An unknown error has occurred. Please try after sometime.')\r\n \r\n # Refreshes the list of connected peers and files.\r\n def onRefreshClicked(self):\r\n self.mainUI.lbl_countdown.setText('\\t\\t\\tRefreshing...')\r\n self.lock.acquire()\r\n try:\r\n self.mainUI.tb_Search.clear()\r\n self.nodeList=self.p2pHandler.buildPeerList(self.trackerIp,self.trackerPort)\r\n self.fileList=self.p2pHandler.listAvailableFiles(self.trackerIp,self.trackerPort)\r\n self.mainUI.listView_nodes.clear()\r\n self.mainUI.listView_files.clear()\r\n if self.fileList:\r\n self.mainUI.listView_files.addItem('PeerIP \\t\\t\\tFileName')\r\n for file in self.fileList:\r\n self.mainUI.listView_files.addItem(''+(file.split(',')[0])+'\\t\\t'+(file.split(',')[1]))\r\n else:\r\n self.mainUI.listView_files.addItem('No Files are currently available to download.\\nAdd your own files to share on the network')\r\n if self.nodeList:\r\n self.mainUI.listView_nodes.addItem('PeerIP (Total '+str(len(self.nodeList))+' online peers)')\r\n for node in self.nodeList:\r\n self.mainUI.listView_nodes.addItem(node)\r\n except socket.timeout:\r\n self.popupMessage('Could not connect to the tracker. Please try after sometime.')\r\n except:\r\n self.popupMessage('An unknown error has occurred. Please try after sometime.')\r\n finally:\r\n self.lock.release()\r\n \r\n def popupMessage(self,errorString,windowTitle='Message'):\r\n messageBox = QMessageBox()\r\n messageBox.setWindowTitle(windowTitle)\r\n messageBox.setText(errorString)\r\n messageBox.exec_()\r\n \r\nif __name__ == \"__main__\":\r\n app = QtGui.QApplication(sys.argv)\r\n myapp= FileSharerGUI(trackerIp='192.168.173.1')\r\n myapp.show()\r\n sys.exit(app.exec_())\r\n","sub_path":"P2PFileShare2/src/ui/FileSharerGUI.py","file_name":"FileSharerGUI.py","file_ext":"py","file_size_in_byte":9385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"555063674","text":"import openpyxl as xl\nwb = xl.load_workbook('Book1.xlsx')\nsheet= wb['Sheet1']\ncell = sheet.cell(1,1)\n\nfor row in range(2,sheet.max_row +1):\n cell = sheet.cell(row,3)\n mul = cell.value * 0.9\n corrected_price_cell =sheet.cell(row, 4)\n corrected_price_cell.value = mul\n\nwb.save('test to see if exel code works.xlsx')\n","sub_path":"code for editing excel spreadsheets.py","file_name":"code for editing excel spreadsheets.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"568881411","text":"\nimport numpy as np\nfrom scipy.integrate import ode\n\nclass _DustyWaveSolution(object):\n def __init__(self, t, k,\n rho_g, rho_d, P0, drho_g, drho_d, v_g, v_d, dP, v_f):\n self._t = t\n self._k = k\n self._rho_g = rho_g\n self._rho_d = rho_d\n self._drho_g = drho_g\n self._drho_d = drho_d\n self._v_g = v_g\n self._v_d = v_d\n self._P0 = P0\n self._dP = dP\n self._v_f = v_f\n\n\n def v_gas(self, x):\n return (self._v_f + self._v_g * np.exp(1j*self._k*x)).real\n def v_dust(self, x):\n return (self._v_f + self._v_d * np.exp(1j*self._k*x)).real\n\n def rho_gas(self, x):\n return (self._rho_g + self._drho_g * np.exp(1j*self._k*x)).real\n def rho_dust(self, x):\n return (self._rho_d + self._drho_d * np.exp(1j*self._k*x)).real\n\n def P(self, x):\n return (self._P0 + self._dP * np.exp(1j*self._k*x)).real\n\n @property\n def time(self):\n return self._t\n\nclass DustyWaveSolver(object):\n\n def __init__(self, rho_g=1., rho_d=1., cs=1., K=1., delta=1e-3, vf=0,\n GAMMA=1.0, wavelength=1., feedback=True):\n \n self.GAMMA = GAMMA\n\n self.vf = vf\n self.rho_g = rho_g\n self.rho_d = rho_d\n self.cs = cs\n self.K = K\n self.delta = delta\n self.wavelength=wavelength\n self.feedback=feedback\n\n def _solve_system(self, times):\n '''Solve the dusty-wave problem up to specified times'''\n k = 2*np.pi / self.wavelength\n cs2 = self.cs**2\n gammaP0 = cs2 * self.rho_g \n gamma = self.GAMMA\n\n ts_inv = self.K * self.rho_g\n if self.feedback:\n Kg = (self.rho_d/self.rho_g) * ts_inv\n Kd = ts_inv\n else:\n Kg = 0\n Kd = ts_inv\n\n def f(t, y,_=None):\n drho_g, v_g = y[0:2]\n drho_d, v_d = y[2:4]\n dP = y[4]\n \n dydt = np.empty([5], dtype='c8')\n dydt[0] = - 1j*k*self.vf*drho_g - 1j*k*self.rho_g * v_g \n dydt[1] = - 1j*k*self.vf * v_g - Kg*(v_g - v_d) - 1j*k*dP/self.rho_g\n dydt[2] = - 1j*k*self.rho_d * v_d - 1j*k*self.vf*drho_d\n dydt[3] = - 1j*k*self.vf * v_d + Kd*(v_g - v_d)\n dydt[4] = - 1j*k*gammaP0 * v_g - 1j*k*self.vf*dP\n return dydt\n\n _jac = np.zeros([5,5], dtype='c8')\n _jac[0,:] = [-1j*k*self.vf, -1j*k*self.rho_g, 0, 0, 0]\n _jac[1,:] = [0, -Kg - 1j*k*self.vf, 0, Kg, -1j*k/self.rho_g]\n _jac[2,:] = [0, 0, -1j*k*self.vf, -1j*k*self.rho_d, 0]\n _jac[3,:] = [0, Kd, 0, -Kd - 1j*k*self.vf, 0 ]\n _jac[4,:] = [0, - 1j*k*gammaP0, 0, 0, -1j*k*self.vf]\n def jac(t, y,_=None):\n return _jac\n\n # Do the right going part of the wave (we can get the left going wave\n # for free by taking the real part).\n e = -1j * self.delta\n\n IC = np.array([self.rho_g*e, self.cs*e, \n self.rho_d*e, self.cs*e,\n gammaP0*e],\n dtype='c8')\n\n # Diagonalize the equations\n l, U = np.linalg.eig(_jac)\n u0 = np.linalg.solve(U, IC)\n\n sol = []\n for ti in times:\n # Use the analytical solution and project back to \n # the primitive variables\n sol.append(np.dot(U, u0 * np.exp(l*ti)))\n\n return np.array(sol)\n\n def __call__(self, time):\n '''Solve the dustwave problem at a given time or list of times'''\n try:\n iter(time)\n except TypeError:\n time = [time,]\n time = sorted(time)\n sol = self._solve_system(list(time))\n\n def _create_solution(t, drho_g, v_g, drho_d, v_d, dP):\n return _DustyWaveSolution(t, 2*np.pi/self.wavelength,\n self.rho_g, self.rho_d, \n self.rho_g*self.cs**2/self.GAMMA,\n drho_g, drho_d, v_g, v_d, dP, self.vf)\n\n sol = [_create_solution(t, *s) for t, s in zip(time,sol)]\n if len(sol) == 1:\n return sol[0]\n else:\n return sol\n\n\nif __name__ == \"__main__\":\n import matplotlib.pyplot as plt\n import matplotlib.animation as animation\n \n dw = DustyWaveSolver(vf=0, GAMMA=5/3., K=10)\n \n N = 101\n times = np.linspace(0, 10, N)\n x = np.linspace(0, 1, 1001)\n \n sol = dw(times)\n\n f, ax = plt.subplots(2,1)\n l1, = ax[0].plot(x, sol[0].rho_gas(x)-1, 'k-') \n l2, = ax[0].plot(x, sol[0].rho_dust(x)-1, 'k:')\n l3, = ax[1].plot(x, sol[0].v_gas(x), 'k-', label='gas') \n l4, = ax[1].plot(x, sol[0].v_dust(x), 'k:', label='dust')\n plt.legend(frameon=False)\n\n\n ax[0].set_ylabel(r'$\\delta \\rho$')\n #ax[0].set_ylim(-0.002,0.002)\n\n ax[1].set_xlabel(r'$x$')\n ax[1].set_ylabel(r'$v$')\n #ax[1].set_ylim(-0.001,0.001)\n\n def animate(i):\n l1.set_ydata(sol[i].rho_gas(x)-1)\n l2.set_ydata(sol[i].rho_dust(x)-1)\n l3.set_ydata(sol[i].v_gas(x))\n l4.set_ydata(sol[i].v_dust(x))\n return l1,l2,l3,l4\n\n def init():\n return l1,l2,l3,l4\n\n ani = animation.FuncAnimation(f, animate, np.arange(0, N), \n interval=100, repeat_delay=200, blit=True)\n\n\n plt.show()\n \n","sub_path":"working_backwards/dustywave_sol2.py","file_name":"dustywave_sol2.py","file_ext":"py","file_size_in_byte":5358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"67731606","text":"# encoding: utf-8\n\"\"\" 自定义数据集 HOTEL\n@version 1.0.0 build 20180409\n\"\"\"\n\nimport torch\nimport torch.utils.data as Data\nimport torchvision\n\nimport os\nimport numpy as np\nimport codecs\nimport random\n\nfrom . import utils\n\n\n\nclass HOTEL(Data.Dataset):\n training_file = \"training_data.npy\"\n test_file = \"test_data.npy\"\n\n def __init__(self, root, train=True):\n self.root = os.path.expanduser(root)\n\n self.train = train\n\n if self.train:\n self.train_data, self.train_labels = np.load(os.path.join(root, self.training_file))\n else:\n self.test_data, self.test_labels = np.load(os.path.join(root, self.test_file))\n\n def __getitem__(self, index):\n \"\"\"\n Args:\n index (int): Index\n\n Returns:\n tuple: (image, target) where target is index of the target class.\n \"\"\"\n if self.train:\n embed_sentence, label = self.train_data[index], self.train_labels[index]\n else:\n embed_sentence, label = self.test_data[index], self.test_labels[index]\n return embed_sentence, label\n\n def __len__(self):\n if self.train:\n return len(self.train_data)\n else:\n return len(self.test_data)\n\n\nif __name__ == '__main__':\n\n train_dataset = HOTEL(root='../data/hotel/', train=True)\n print(len(train_dataset))\n\n (data, label) = train_dataset[0]\n print(data)\n print(label)\n\n\n\n","sub_path":"datasets/hotel.py","file_name":"hotel.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"28997281","text":"from pya import *\nimport pya\nimport math\n\nfrom SiEPIC.utils import get_technology, get_technology_by_name\nfrom SiEPIC.utils import arc, arc_wg, arc_to_waveguide, points_per_circle#,layout\n\nclass PhC_L3c_Test_Structure(pya.PCellDeclarationHelper):\n \n \"\"\"\n The PCell declaration for the test structure with grating couplers and waveguides and a photonic crystal cavity\n \"\"\"\n\n def __init__(self):\n\n # Important: initialize the super class\n super(PhC_L3c_Test_Structure, self).__init__()\n \n #taper parameters\n self.param(\"tri_base\", self.TypeDouble, \"Taper Triangle Base (microns)\", default = 0.363)\n self.param(\"tri_height\", self.TypeDouble, \"Taper Triangle Height (microns)\", default = 0.426)\n self.param(\"taper_wg_length\", self.TypeDouble, \"Taper Length (microns)\", default = 5)\n self.param(\"w\", self.TypeDouble, \"Waveguide Width\", default = 1.0)\n self.param(\"wg_bend_radius\", self.TypeDouble, \"Waveguide Bend Radius (microns)\", default = 15)\n\n #photonic crystal cavity \n self.param(\"a\", self.TypeDouble, \"lattice constant (microns)\", default = 0.720) \n self.param(\"n\", self.TypeInt, \"Number of holes in x and y direction\", default = 34) \n self.param(\"r\", self.TypeDouble, \"hole radius (microns)\", default = 0.181)\n self.param(\"wg_dis\", self.TypeInt, \"Waveguide distance (number of holes)\", default = 3) \n self.param(\"S1x\", self.TypeDouble, \"S1x shift\", default = 0.337) \n self.param(\"S2x\", self.TypeDouble, \"S2x shift\", default = 0.27) \n self.param(\"S3x\", self.TypeDouble, \"S3x shift\", default = 0.088) \n self.param(\"S4x\", self.TypeDouble, \"S4x shift\", default = 0.323)\n self.param(\"S5x\", self.TypeDouble, \"S5x shift\", default = 0.0173)\n self.param(\"phc_xdis\", self.TypeDouble, \"Distance from GC to middle of Cavity\", default = 35)\n \n #GC parameters \n self.param(\"wavelength\", self.TypeDouble, \"Design Wavelength (micron)\", default = 2.9) \n self.param(\"n_t\", self.TypeDouble, \"Fiber Mode\", default = 1.0)\n self.param(\"n_e\", self.TypeDouble, \"Grating Index Parameter\", default = 3.1)\n self.param(\"angle_e\", self.TypeDouble, \"Taper Angle (deg)\", default = 20.0)\n self.param(\"grating_length\", self.TypeDouble, \"Grating Length (micron)\", default = 32.0)\n self.param(\"taper_length\", self.TypeDouble, \"Taper Length (micron)\", default = 32.0)\n self.param(\"dc\", self.TypeDouble, \"Duty Cycle\", default = 0.488193)\n self.param(\"period\", self.TypeDouble, \"Grating Period\", default = 1.18939)\n self.param(\"ff\", self.TypeDouble, \"Fill Factor\", default = 0.244319)\n self.param(\"t\", self.TypeDouble, \"Waveguide Width (micron)\", default = 1.0)\n self.param(\"theta_c\", self.TypeDouble, \"Insertion Angle (deg)\", default = 8.0)\n \n #Layer Parameters\n TECHNOLOGY = get_technology_by_name('EBeam')\n self.param(\"layer\", self.TypeLayer, \"Layer\", default = TECHNOLOGY['Waveguide'])\n self.param(\"pinrec\", self.TypeLayer, \"PinRec Layer\", default = TECHNOLOGY['PinRec'])\n self.param(\"devrec\", self.TypeLayer, \"DevRec Layer\", default = TECHNOLOGY['DevRec'])\n self.param(\"textl\", self.TypeLayer, \"Text Layer\", default = TECHNOLOGY['Text'])\n\n def can_create_from_shape_impl(self):\n return False\n \n def produce_impl(self):\n # This is the main part of the implementation: create the layout\n\n # fetch the parameters\n dbu = self.layout.dbu\n ly = self.layout\n cell = self.cell\n shapes = self.cell.shapes\n \n LayerSi = self.layer\n LayerSiN = ly.layer(self.layer)\n LayerPinRecN = ly.layer(self.pinrec)\n LayerDevRecN = ly.layer(self.devrec)\n LayerTextN = ly.layer(self.textl)\n \n a = self.a \n n = self.n \n wg_dis = self.wg_dis\n phc_xdis = self.phc_xdis\n wg_bend_radius = self.wg_bend_radius\n wg_width = self.w\n\n if wg_dis%2 == 0:\n length_slab_x = (n-1)*a\n else:\n length_slab_x = n*a\n \n half_slab_x = length_slab_x/2\n\n param_phc = {\"a\": self.a, \"n\": self.n, \"r\": self.r, \"wg_dis\": self.wg_dis, \"S1x\":self.S1x, \"S2x\":self.S2x, \"S3x\":self.S3x, \"S4x\":self.S4x, \"S5x\":self.S5x, \n \"layer\": self.layer, \"pinrec\": self.pinrec, \"devrec\": self.devrec} \n pcell_phc = ly.create_cell(\"L3 cavity with waveguide\", \"SiQL_PCells\", param_phc ) \n t1 = Trans(Trans.R0,phc_xdis/dbu,(127)/dbu-(math.sqrt(3)/2*a*(wg_dis+1))/dbu) \n instance = cell.insert(pya.CellInstArray(pcell_phc.cell_index(), t1))\n\n param_GC = {\"wavelength\": self.wavelength, \"n_t\":self.n_t, \"n_e\":self.n_e, \"angle_e\":self.angle_e, \n \"grating_length\":self.grating_length, \"taper_length\":self.taper_length, \"dc\":self.dc, \"period\":self.period, \n \"ff\":self.ff, \"t\":self.t, \"theta_c\":self.theta_c,\n \"layer\": LayerSi, \"pinrec\": self.pinrec, \"devrec\": self.devrec} \n pcell_GC = ly.create_cell(\"SWG Fibre Coupler\", \"SiQL_PCells\", param_GC )\n t_GC = Trans(Trans.R0, 0,0)\n instance = cell.insert(pya.CellInstArray(pcell_GC.cell_index(), t_GC, Point(0,127/dbu), Point(0,0), 3, 1))\n \n param_taper = {\"tri_base\": self.tri_base, \"tri_height\":self.tri_height, \n \"taper_wg_length\":self.taper_wg_length, \"wg_width\": self.w, \"silayer\":LayerSi, \n \"pinrec\": self.pinrec, \"devrec\": self.devrec}\n pcell_taper = ly.create_cell(\"Waveguide Triangle Tapers\",\"SiQL_PCells\",param_taper)\n t_taper1 = Trans(Trans.R0,(phc_xdis-half_slab_x)/dbu,(127)/dbu)\n instance = cell.insert(pya.CellInstArray(pcell_taper.cell_index(), t_taper1))\n \n pcell_taper2 = ly.create_cell(\"Waveguide Triangle Tapers\",\"SiQL_PCells\",param_taper)\n t_taper2 = Trans(Trans.R180, (phc_xdis+half_slab_x)/dbu,(127)/dbu)\n instance = cell.insert(pya.CellInstArray(pcell_taper2.cell_index(), t_taper2))\n \n pcell_taper3 = ly.create_cell(\"Waveguide Triangle Tapers\",\"SiQL_PCells\",param_taper)\n t_taper3 = Trans(Trans.R180, (phc_xdis+half_slab_x)/dbu,(127-2*(wg_dis+1)*math.sqrt(3)/2*a)/dbu)\n instance = cell.insert(pya.CellInstArray(pcell_taper3.cell_index(), t_taper3))\n\n # gc middle to in port \n points = [ [0, 127], [ phc_xdis-half_slab_x-self.taper_wg_length , 127] ] \n layout_waveguide_abs(cell, LayerSi, points, wg_width, wg_bend_radius)\n \n # gc top to through port \n points2 = [ [0, 254], [ (phc_xdis+half_slab_x+self.taper_wg_length)+wg_bend_radius , 254], [ (phc_xdis+half_slab_x+self.taper_wg_length)+wg_bend_radius , 127], [ (phc_xdis+half_slab_x+self.taper_wg_length) , 127] ] \n layout_waveguide_abs(cell, LayerSi, points2, wg_width, wg_bend_radius)\n \n # gc bottom to coupled port \n points3 = [ [0, 0], [ (phc_xdis+half_slab_x+self.taper_wg_length)+wg_bend_radius , 0], [ (phc_xdis+half_slab_x+self.taper_wg_length)+wg_bend_radius , 127-2*(wg_dis+1)*a*math.sqrt(3)/2], [ (phc_xdis+half_slab_x+self.taper_wg_length) , 127-2*(wg_dis+1)*a*math.sqrt(3)/2] ] \n layout_waveguide_abs(cell, LayerSi, points3, wg_width, wg_bend_radius)\n ","sub_path":"klayout_dot_config/tech/EBeam/pymacros/pcells_Beta/broken/PhC_L3c_Test_Structure.py","file_name":"PhC_L3c_Test_Structure.py","file_ext":"py","file_size_in_byte":6895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"59499756","text":"import numpy\nfrom tigger.cluda import dtypes\n\n\nSINGLE_EPS = 1e-6\n\n\ndef get_test_array(shape, dtype, no_zeros=False, high=None):\n if not isinstance(shape, tuple):\n shape = (shape,)\n\n dtype = dtypes.normalize_type(dtype)\n\n if dtypes.is_integer(dtype):\n low = 1 if no_zeros else 0\n if high is None:\n high = 100 # will work even with signed chars\n get_arr = lambda: numpy.random.randint(low, high, shape).astype(dtype)\n else:\n low = 0.01 if no_zeros else 0\n if high is None:\n high = 1.0\n get_arr = lambda: numpy.random.uniform(low, high, shape).astype(dtype)\n\n if dtypes.is_complex(dtype):\n return get_arr() + 1j * get_arr()\n else:\n return get_arr()\n\ndef float_diff(m, m_ref):\n return numpy.linalg.norm(m - m_ref) / numpy.linalg.norm(m_ref)\n\ndef diff_is_negligible(m, m_ref):\n assert m.dtype == m_ref.dtype\n if dtypes.is_integer(m.dtype):\n return ((m - m_ref) == 0).all()\n else:\n return float_diff(m, m_ref) < SINGLE_EPS\n","sub_path":"test/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"592440717","text":"import gears\nfrom pbge.plots import Plot, Adventure, NarrativeRequest, PlotState\nimport pbge\nfrom game.content import plotutility\n\n# **********************\n# *** RECOVER_PC ***\n# **********************\n#\n# Elements:\n# METRO: The local metro scene's metrodat, or camp if not applicable\n# METROSCENE: The scope for scene search\n\nclass PC_HospitalRecovery( Plot ):\n # The PC has been knocked out; recover everyone else and send the PC to the hospital.\n LABEL = \"RECOVER_PC\"\n active = True\n scope = True\n def custom_init( self, nart ):\n \"\"\"Find a hospital, move the PC to there.\"\"\"\n myscene = self.seek_element(nart,\"HOSPITAL\",self._is_good_scene,scope=self.elements[\"METROSCENE\"])\n myent = self.seek_element(nart,\"BED\",self._is_good_bed,scope=myscene,check_subscenes=False)\n self.mission_entrance = (myscene,myent)\n self.started_mission = False\n self.plots_to_run = list()\n if nart.camp.dead_party:\n self.plots_to_run.append(self.add_sub_plot(nart,\"RECOVERY_DEAD_PARTY\"))\n return True\n\n def _is_good_scene(self,nart,candidate):\n return isinstance(candidate,gears.GearHeadScene) and gears.tags.SCENE_HOSPITAL in candidate.attributes\n\n def _is_good_bed(self,nart,candidate):\n return isinstance(candidate,pbge.scenes.waypoints.Waypoint) and hasattr(candidate,\"recovery_entrance\") and candidate.recovery_entrance\n\n def start_recovery(self,camp):\n \"\"\"\n\n :type camp: gears.GearHeadCampaign\n \"\"\"\n camp.destination, camp.entrance = self.mission_entrance\n if not self.started_mission:\n camp.pc.container.remove(camp.pc)\n camp.party.append(camp.pc)\n # If the PC was knocked out, all the lancemates recover/repair while the PC is being treated.\n for pc in list(camp.incapacitated_party):\n camp.incapacitated_party.remove(pc)\n camp.party.append(pc)\n for pc in list(camp.party):\n if pc is not camp.pc and isinstance(pc,gears.base.Character) and not camp.get_pc_mecha(pc):\n mek = plotutility.AutoJoiner.get_mecha_for_character(pc)\n if mek:\n camp.party.append(mek)\n camp.assign_pilot_to_mecha(pc, mek)\n for part in mek.get_all_parts():\n part.owner = pc\n\n self.started_mission = True\n\n def HOSPITAL_ENTER(self, camp):\n pbge.alert(\"You wake up in the hospital.\")\n\n for p in self.plots_to_run:\n p.start_recovery(camp)\n\n self.end_plot(camp)\n\n\n# *************************\n# *** RECOVER_LANCE ***\n# *************************\n#\n# Elements:\n# METRO: The local metro scene's metrodat, or camp if not applicable\n# METROSCENE: The scope for scene search\n\nclass LanceRecoveryStub( Plot ):\n # This plot just loads the plots that do the actual work.\n LABEL = \"RECOVER_LANCE\"\n active = False\n def custom_init( self, nart ):\n self.plots_to_run = list()\n if nart.camp.dead_party:\n self.plots_to_run.append(self.add_sub_plot(nart,\"RECOVERY_DEAD_PARTY\"))\n\n return True\n\n def start_recovery(self,camp):\n for p in self.plots_to_run:\n p.start_recovery(camp)\n\n# ******************************\n# *** RECOVER_DEAD_PARTY ***\n# ******************************\n#\n# Elements:\n# METRO: The local metro scene's metrodat, or camp if not applicable\n# METROSCENE: The scope for scene search\n\nclass BoringDeathNotification( Plot ):\n # Inform the PC of who died, then end.\n LABEL = \"RECOVER_DEAD_PARTY\"\n active = False\n def start_recovery(self,camp):\n dead_names = [str(npc) for npc in camp.dead_party]\n if len(camp.dead_party) > 2:\n msg = ', '.join(dead_names[:-2]) + ', and ' + dead_names[-1]\n elif len(camp.dead_party) > 1:\n msg = ' and '.join(dead_names)\n else:\n msg = dead_names[0]\n pbge.alert('{} did not survive the last mission.'.format(msg))\n camp.dead_party = list()\n\n","sub_path":"game/content/ghplots/recovery.py","file_name":"recovery.py","file_ext":"py","file_size_in_byte":4131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"115791979","text":"_base_ = [\n '../_base_/default_runtime.py',\n '../_base_/schedules/schedule_20k.py'\n]\n\nfind_unused_parameters = True\nnorm_cfg = dict(type='SyncBN', requires_grad=True)\nmodel = dict(\n type='GuidedMix_EncoderDecoder',\n pretrained='open-mmlab://resnet101_v1c',\n backbone=dict(\n type='ResNetV1c',\n depth=101,\n num_stages=4,\n out_indices=(0, 1, 2, 3),\n dilations=(1, 1, 2, 4),\n strides=(1, 2, 1, 1),\n norm_cfg=norm_cfg,\n norm_eval=False,\n style='pytorch',\n contract_dilation=True),\n decode_head=dict(\n type='ASPPHead',\n in_channels=2048,\n in_index=3,\n channels=512,\n dilations=(1, 12, 24, 36),\n dropout_ratio=0.1,\n num_classes=19,\n norm_cfg=norm_cfg,\n align_corners=False,\n loss_decode=dict(\n type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)),\n components=dict(out_modules=['decode_head.conv_seg', 'decode_head.aspp_modules']),\n kl_loss=dict(\n type='FocalLoss',\n use_sigmoid=True,\n gamma=0.5,\n reduction='mean',\n loss_weight=10.0),\n # model training and testing settings\n train_cfg=dict(),\n test_cfg=dict(mode='whole'))\n\n# dataset settings\ndataset_type = 'CityscapesDataset'\ndata_root = 'data/Cityscapes/'\nimg_norm_cfg = dict(\n mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)\ncrop_size = (769, 769)\ntrain_pipeline = [\n dict(type='LoadImageFromFile'),\n dict(type='LoadAnnotations'),\n dict(type='Resize', img_scale=(2049, 1025), ratio_range=(0.5, 2.0)),\n dict(type='RandomCrop', crop_size=crop_size, cat_max_ratio=0.75),\n dict(type='RandomFlip', prob=0.5),\n dict(type='PhotoMetricDistortion'),\n dict(type='Normalize', **img_norm_cfg),\n dict(type='Pad', size=crop_size, pad_val=0, seg_pad_val=255),\n dict(type='DefaultFormatBundle'),\n dict(type='Collect', keys=['img', 'gt_semantic_seg']),\n]\ntest_pipeline = [\n dict(type='LoadImageFromFile'),\n dict(\n type='MultiScaleFlipAug',\n img_scale=(2049, 1025),\n # img_ratios=[0.5, 0.75, 1.0, 1.25, 1.5, 1.75],\n flip=False,\n transforms=[\n dict(type='Resize', keep_ratio=True),\n dict(type='RandomFlip'),\n dict(type='Normalize', **img_norm_cfg),\n dict(type='ImageToTensor', keys=['img']),\n dict(type='Collect', keys=['img']),\n ])\n]\ndata = dict(\n samples_per_gpu=2,\n workers_per_gpu=2,\n train=dict(\n type='SemiDataset',\n dataset=dict(\n type='Semi'+dataset_type,\n data_root=data_root,\n img_dir='leftImg8bit/train',\n ann_dir='gtFine/train',\n split='./3sseg_datasplits/cityscapes_splits/744_train_supervised.txt',\n pipeline=train_pipeline),\n unsup_dataset=dict(\n type='Semi'+dataset_type,\n data_root=data_root,\n img_dir='leftImg8bit/train',\n ann_dir='gtFine/train',\n split='./3sseg_datasplits/cityscapes_splits/744_train_unsupervised.txt',\n pipeline=train_pipeline)),\n val=dict(\n type='Semi'+dataset_type,\n data_root=data_root,\n img_dir='leftImg8bit/val',\n ann_dir='gtFine/val',\n split=None,\n pipeline=test_pipeline),\n test=dict(\n type='Semi'+dataset_type,\n data_root=data_root,\n img_dir='leftImg8bit/val',\n ann_dir='gtFine/val',\n split=None,\n pipeline=test_pipeline))\n\n# lr_config = dict(policy='poly', power=0.9, min_lr=1e-4, by_epoch=False)\n# # runtime settings\nrunner = dict(type='IterBasedRunner', max_iters=40000)","sub_path":"configs/3sseg/guidedmix_deeplabv3plus_res101_cityscapes_744_40k.py","file_name":"guidedmix_deeplabv3plus_res101_cityscapes_744_40k.py","file_ext":"py","file_size_in_byte":3689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"75490638","text":"\"\"\"\nGiven a string s and an integer k, find the length of the longest substring that contains at most k distinct characters.\n\nFor example, given s = \"abcba\" and k = 2, the longest substring with k distinct characters has a length of 3 (\"bcb\").\n\"\"\"\n\n\"\"\"\nGo through the string, building up a substring with each character. We discard characters from the front of \nthe substring if the no. of unique chars in the substring is at capacity and the new char is not one of these.\n\"\"\"\n\nfrom collections import deque\n\n\ndef longest_distinct_substring(s, k):\n substring = deque()\n unique_chars_in_substring = set()\n longest_substring = 0\n\n for char in s:\n if len(unique_chars_in_substring) == k and char not in unique_chars_in_substring:\n discarded = substring.popleft()\n unique_chars_in_substring.remove(discarded)\n\n substring.append(char)\n unique_chars_in_substring.add(char)\n\n if len(substring) > longest_substring:\n longest_substring = len(substring)\n\n return longest_substring\n\n\nassert longest_distinct_substring('abcba', 2) == 3\nassert longest_distinct_substring('bcbaab', 2) == 4\n","sub_path":"20/13.py","file_name":"13.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"297877102","text":"#coding:utf-8\n\n# 快速排序(Quick Sort)的实现,对于乱序的数组排序,Quick Sort的算法复杂度为O(nlog2n),相对直接插入排序和冒泡法排序等要快\nqs = lambda xs : ( (len(xs) <= 1 and [xs]) or\n\t\t\t\t [ qs( [x for x in xs[1:] if x < xs[0]] ) +\n\t\t\t\t\t [xs[0]] +\n\t\t\t\t qs( [x for x in xs[1:] if x >= xs[0]] ) ] )[0]\t\t\t \n\nimport sys\nline = sys.stdin.readline() \t\t# 从控制台读入第一行输入\nnum = [int(x) for x in line.split(' ') if line.strip()] \t# 将第一行输入转换为list(列表类型)\nN = num[0]\t # 获得N\nk = num[1]\t\t\t\t\t\t\t# 获得k\nline = sys.stdin.readline()\t\t\t# 从控制台读入第二行输入\nscore = [int(x) for x in line.split(' ') if line.strip()] # 获得输入的分数\nscore_sorted = qs(score[0:N-1]);\t\t\t# 对输入分数进行快速排序\nprint(sum(score_sorted[-k:]))\t\t# 输出结果","sub_path":"shoot_ball.py","file_name":"shoot_ball.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"86657991","text":"import logging\nimport os\nfrom web.logging_config import PROFILE\n\nformatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')\ndef getLogger(name):\n logger=logging.getLogger(name)\n if PROFILE == 'PRODUCTION':\n logger.setLevel(level=logging.INFO)\n handler = logging.FileHandler(\"ding.log\")\n handler.setLevel(logging.INFO)\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n if PROFILE == 'DEV':\n console = logging.StreamHandler()\n console.setLevel(logging.INFO)\n logger.addHandler(console)\n","sub_path":"web/logging_factory.py","file_name":"logging_factory.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"354062384","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n------------------------------------------------------------------------------\n\nCopyright (C) 2019 Université catholique de Louvain (UCLouvain), Belgium.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n------------------------------------------------------------------------------\n\n \"setup.py\" - Setup configuration and dataset loading.\n\n Project: DRTP - Direct Random Target Projection\n\n Authors: C. Frenkel and M. Lefebvre, Université catholique de Louvain (UCLouvain), 09/2019\n\n Cite/paper: C. Frenkel, M. Lefebvre and D. Bol, \"Learning without feedback: Direct random target projection\n as a feedback-alignment algorithm with layerwise feedforward training,\" arXiv preprint arXiv:1909.01311, 2019.\n\n------------------------------------------------------------------------------\n\"\"\"\n\n\nimport torch\nimport torchvision\nfrom torchvision import transforms,datasets\nimport sys\nimport subprocess\nimport json\n#加载tidigits数据集\nfrom python_speech_features import fbank\nimport numpy as np\nimport numpy.random as rd\nimport scipy.io.wavfile as wav\nfrom sklearn.preprocessing import normalize\nimport os\nimport pickle\nfrom tqdm import tqdm\nfrom torch.utils.data import Dataset, DataLoader\nfrom sklearn import preprocessing\nimport scipy.io as sio\n\nclass SynthDataset(torch.utils.data.Dataset):\n\n def __init__(self, select, type):\n self.dataset, self.input_size, self.input_channels, self.label_features = torch.load( './DATASETS/'+select+'/'+type+'.pt')\n\n def __len__(self):\n return len(self.dataset[1])\n\n def __getitem__(self, index):\n return self.dataset[0][index], self.dataset[1][index]\n\ndef use_cuda(enabled, device_id=0):\n \"\"\"Verifies if CUDA is available and sets default device to be device_id.\"\"\"\n if not enabled:\n return None\n assert torch.cuda.is_available(), 'CUDA is not available'\n torch.set_default_tensor_type('torch.cuda.FloatTensor')\n torch.cuda.set_device(device_id)\n return device_id\n\ndef setup(args):\n args.cuda = not args.cpu and torch.cuda.is_available()\n if args.cuda:\n print(\"=== The available CUDA GPU will be used for computations.\")\n #memory_load = get_gpu_memory_usage()\n #cuda_device = np.argmin(memory_load).item()\n #torch.cuda.set_device(cuda_device)\n #device = torch.cuda.current_device()\n device=torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n use_cuda(True, device_id=0)\n else:\n device = torch.device('cpu')\n\n kwargs = {'num_workers': 2, 'pin_memory': True} if args.cuda else {}\n if args.dataset == \"regression_synth\":\n print(\"=== Loading the synthetic regression dataset...\")\n (train_loader, traintest_loader, test_loader) = load_dataset_regression_synth(args, kwargs)\n elif args.dataset == \"classification_synth\":\n print(\"=== Loading the synthetic classification dataset...\")\n (train_loader, traintest_loader, test_loader) = load_dataset_classification_synth(args, kwargs)\n elif args.dataset == \"MNIST\":\n print(\"=== Loading the MNIST dataset...\")\n (train_loader, traintest_loader, test_loader) = load_dataset_mnist(args, kwargs)\n elif args.dataset == \"CIFAR10\":\n print(\"=== Loading the CIFAR-10 dataset...\")\n (train_loader, traintest_loader, test_loader) = load_dataset_cifar10(args, kwargs)\n elif args.dataset == \"CIFAR10aug\":\n print(\"=== Loading and augmenting the CIFAR-10 dataset...\")\n (train_loader, traintest_loader, test_loader) = load_dataset_cifar10_augmented(args, kwargs)\n elif args.dataset == \"tidigits\":\n print(\"=== Loading and augmenting the tidifits dataset...\")\n (train_loader, traintest_loader, test_loader) = load_dataset_tidigits(args, kwargs)\n elif args.dataset == \"dvsgesture\":\n print(\"=== Loading and augmenting the dvsgesture dataset...\")\n (train_loader, traintest_loader, test_loader) = load_dataset_gesture(args, kwargs)\n elif args.dataset == \"timit\":\n print(\"=== Loading and augmenting the TIMIT dataset...\")\n (train_loader, traintest_loader, test_loader) = load_dataset_timit(args, kwargs)\n else:\n print(\"=== ERROR - Unsupported dataset ===\")\n sys.exit(1)\n args.regression = (args.dataset == \"regression_synth\")\n\n return (device, train_loader, traintest_loader, test_loader)\n\ndef get_gpu_memory_usage():\n if sys.platform == \"win32\":\n curr_dir = os.getcwd()\n nvsmi_dir = r\"C:\\Program Files\\NVIDIA Corporation\\NVSMI\"\n os.chdir(nvsmi_dir)\n result = subprocess.check_output(['nvidia-smi', '--query-gpu=memory.used','--format=csv,nounits,noheader'])\n os.chdir(curr_dir)\n else:\n result = subprocess.check_output(['nvidia-smi', '--query-gpu=memory.used','--format=csv,nounits,noheader'])\n gpu_memory = [int(x) for x in result.decode('utf-8').strip().split('\\n')]\n return gpu_memory\n\ndef load_dataset_regression_synth(args, kwargs):\n\n trainset = SynthDataset(\"regression\",\"train\")\n testset = SynthDataset(\"regression\", \"test\")\n\n train_loader = torch.utils.data.DataLoader(trainset, batch_size=args.batch_size, shuffle=True , **kwargs)\n traintest_loader = torch.utils.data.DataLoader(trainset, batch_size=args.test_batch_size, shuffle=False, **kwargs)\n test_loader = torch.utils.data.DataLoader(testset , batch_size=args.test_batch_size, shuffle=False, **kwargs)\n\n args.input_size = trainset.input_size\n args.input_channels = trainset.input_channels\n args.label_features = trainset.label_features\n\n return (train_loader, traintest_loader, test_loader)\n\ndef load_dataset_classification_synth(args, kwargs):\n\n trainset = SynthDataset(\"classification\",\"train\")\n testset = SynthDataset(\"classification\", \"test\")\n\n train_loader = torch.utils.data.DataLoader(trainset, batch_size=args.batch_size, shuffle=True , **kwargs)\n traintest_loader = torch.utils.data.DataLoader(trainset, batch_size=args.test_batch_size, shuffle=False, **kwargs)\n test_loader = torch.utils.data.DataLoader(testset , batch_size=args.test_batch_size, shuffle=False, **kwargs)\n\n args.input_size = trainset.input_size\n args.input_channels = trainset.input_channels\n args.label_features = trainset.label_features\n\n return (train_loader, traintest_loader, test_loader)\n\ndef load_dataset_mnist(args, kwargs):\n train_loader = torch.utils.data.DataLoader(datasets.MNIST('./DATASETS/MNIST', train=True, download=True, transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.0,),(1.0,))])), batch_size=args.batch_size, shuffle=True , **kwargs)\n traintest_loader = torch.utils.data.DataLoader(datasets.MNIST('./DATASETS/MNIST', train=True, download=True, transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.0,),(1.0,))])), batch_size=args.test_batch_size, shuffle=False, **kwargs)\n test_loader = torch.utils.data.DataLoader(datasets.MNIST('./DATASETS/MNIST', train=False, download=True, transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.0,),(1.0,))])), batch_size=args.test_batch_size, shuffle=False, **kwargs)\n args.input_size = 28\n args.input_channels = 1\n args.label_features = 10\n\n return (train_loader, traintest_loader, test_loader)\n\ndef load_dataset_cifar10(args, kwargs):\n normalize = transforms.Normalize(mean=[x/255.0 for x in [125.3, 123.0, 113.9]], std=[x/255.0 for x in [63.0, 62.1, 66.7]])\n transform_cifar10 = transforms.Compose([transforms.ToTensor(),normalize,])\n\n train_loader = torch.utils.data.DataLoader(datasets.CIFAR10('./DATASETS/CIFAR10', train=True, download=True, transform=transform_cifar10), batch_size=args.batch_size, shuffle=True , **kwargs)\n traintest_loader = torch.utils.data.DataLoader(datasets.CIFAR10('./DATASETS/CIFAR10', train=True, download=True, transform=transform_cifar10), batch_size=args.test_batch_size, shuffle=False, **kwargs)\n test_loader = torch.utils.data.DataLoader(datasets.CIFAR10('./DATASETS/CIFAR10', train=False, download=True, transform=transform_cifar10), batch_size=args.test_batch_size, shuffle=False, **kwargs)\n\n args.input_size = 32\n args.input_channels = 3\n args.label_features = 10\n\n return (train_loader, traintest_loader, test_loader)\n\ndef load_dataset_cifar10_augmented(args, kwargs):\n #Source: https://zhenye-na.github.io/2018/09/28/pytorch-cnn-cifar10.html\n\n transform_train = transforms.Compose([\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(mean=[x/255.0 for x in [125.3, 123.0, 113.9]],\n std=[x/255.0 for x in [63.0, 62.1, 66.7]]),\n ])\n\n # Normalize the test set same as training set without augmentation\n transform_test = transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean=[x/255.0 for x in [125.3, 123.0, 113.9]], std=[x/255.0 for x in [63.0, 62.1, 66.7]]),])\n\n trainset = torchvision.datasets.CIFAR10('./DATASETS/CIFAR10AUG', train=True, download=True, transform=transform_train)\n train_loader = torch.utils.data.DataLoader(trainset, batch_size=args.batch_size, shuffle=True)\n\n traintestset = torchvision.datasets.CIFAR10('./DATASETS/CIFAR10AUG', train=True, download=True, transform=transform_test)\n traintest_loader = torch.utils.data.DataLoader(traintestset, batch_size=args.test_batch_size, shuffle=False)\n\n testset = torchvision.datasets.CIFAR10('./DATASETS/CIFAR10AUG', train=False, download=True, transform=transform_test)\n test_loader = torch.utils.data.DataLoader(testset, batch_size=args.test_batch_size, shuffle=False)\n\n args.input_size = 32\n args.input_channels = 3\n args.label_features = 10\n\n return (train_loader, traintest_loader, test_loader)\n\ndef read_data(path, n_bands, n_frames):\n overlap = 0.5\n\n filelist = []\n for root, dirs, files in os.walk(path):\n for file in files:\n if file.endswith('.waV') and file[0] != 'O':\n filelist.append(os.path.join(root, file))\n # filelist = filelist[:1002]\n\n n_samples = len(filelist)\n\n def keyfunc(x):\n s = x.split('/')\n return (s[-1][0], s[-2], s[-1][1]) # BH/1A_endpt.wav: sort by '1', 'BH', 'A'\n filelist.sort(key=keyfunc)\n\n feats = np.empty((n_samples, 1, n_bands, n_frames))\n labels = np.empty((n_samples,), dtype=np.long)\n with tqdm(total=len(filelist)) as pbar:\n for i, file in enumerate(filelist):\n pbar.update(1)\n label = file.split('/')[-1][0] # if using windows, change / into \\\\\n if label == 'Z':\n labels[i] = np.long(0)\n else:\n labels[i] = np.long(label)\n rate, sig = wav.read(file)\n duration = sig.size / rate\n winlen = duration / (n_frames * (1 - overlap) + overlap)\n winstep = winlen * (1 - overlap)\n feat, energy = fbank(sig, rate, winlen, winstep, nfilt=n_bands, nfft=4096, winfunc=np.hamming)\n # feat = np.log(feat)\n final_feat = feat[:n_frames]\n final_feat = normalize(final_feat, norm='l1', axis=0)\n feats[i] = np.expand_dims(np.array(final_feat),axis=0)\n # feats[i] = feat[:n_frames].flatten() # feat may have 41 or 42 frames\n # feats[i] = feat.flatten() # feat may have 41 or 42 frames\n\n # feats = normalize(feats, norm='l2', axis=1)\n # normalization\n # feats = preprocessing.scale(feats)\n\n np.random.seed(42)\n p = np.random.permutation(n_samples)\n feats, labels = feats[p], labels[p]\n\n n_train_samples = int(n_samples * 0.7)\n print('n_train_samples:',n_train_samples)\n\n train_set = (feats[:n_train_samples], labels[:n_train_samples])\n test_set = (feats[n_train_samples:], labels[n_train_samples:])\n\n return train_set, train_set, test_set\n\ndef datatobatch(args,train_loader):\n temp, temp2 = [], []\n label, label2 = [], []\n for i, data in enumerate(train_loader[0]):\n if i % args.batch_size == 0 and i != 0:\n temp2.append(temp)\n label2.append(label)\n temp, label = [], []\n temp.append(data)\n label.append(train_loader[1][i])\n else:\n temp.append(data)\n label.append(train_loader[1][i])\n temp2 = torch.tensor(temp2)\n label2 = torch.tensor(label2)\n a = (temp2, label2)\n return a\n\nclass Tidigits(Dataset):\n def __init__(self,train_or_test,input_channel,n_bands,n_frames,transform=None, target_transform = None):\n super(Tidigits, self).__init__()\n self.n_bands = n_bands\n self.n_frames = n_frames\n rootfile = 'E:/Study/Data/essaycode/metaandDRTP/Code'\n dataname = rootfile + '/DATASETS/tidigits/packed_tidigits_nbands_'+str(n_bands)+'_nframes_' + str(n_frames)+'.pkl'\n if os.path.exists(dataname):\n with open(dataname,'rb') as fr:\n [train_set, val_set, test_set] = pickle.load(fr)\n else:\n print('Tidigits Dataset Has not been Processed, now do it.')\n train_set, val_set, test_set = read_data(path=rootfile+'/DATASETS/tidigits/isolated_digits_tidigits', n_bands=n_bands, n_frames=n_frames)#(2900, 1640) (2900,)\n with open(dataname,'wb') as fw:\n pickle.dump([train_set, val_set, test_set],fw)\n if train_or_test == 'train':\n self.x_values = train_set[0]\n self.y_values = train_set[1]\n\n elif train_or_test == 'test':\n self.x_values = test_set[0]\n self.y_values = test_set[1]\n elif train_or_test == 'valid':\n self.x_values = val_set[0]\n self.y_values = val_set[1]\n self.transform =transform\n self.target_transform = target_transform\n \n def __getitem__(self, index):\n sample = self.x_values[index]\n label = self.y_values[index]\n return sample, label\n \n def __len__(self):\n return len(self.x_values)\n\nclass Gesture(Dataset):\n def __init__(self, train_or_test, transform = None, target_transform = None):\n super(Gesture, self).__init__()\n rootfile = '/mnt/lustre/xushuang4/jiashuncheng/code/newdrtp' \n mat_fname = rootfile+'/DATASETS/DVS_gesture_100.mat'\n mat_contents = sio.loadmat(mat_fname)\n if train_or_test == 'train':\n self.x_values = mat_contents['train_x_100']\n self.y_values = mat_contents['train_y']\n elif train_or_test == 'test':\n self.x_values = mat_contents['test_x_100']\n self.y_values = mat_contents['test_y']\n self.transform = transform\n self.target_transform = target_transform\n\n def __getitem__(self, index):\n sample = self.x_values[index, :, :]\n sample = torch.reshape(torch.tensor(sample), (sample.shape[0], 32, 32)).unsqueeze(0)\n label = self.y_values[index].astype(np.float32)\n label = torch.topk(torch.tensor(label), 1)[1].squeeze(0)\n return sample, label\n\n def __len__(self):\n return len(self.x_values)\n\n#以下是TIMIT数据集的读取程序\ndef pad_vector(v, n_time, pad_value=0.):\n if len(v.shape) == 2:\n shp = v.shape\n return np.concatenate([v, pad_value * np.ones((n_time - shp[0], shp[1]))], axis=0)\n elif len(v.shape) == 1:\n shp = v.shape\n\n return np.concatenate([v, pad_value * np.zeros((n_time - shp[0],))], axis=0)\n\ndef sparsity_dense_vector(vector, blank_symbol):\n indices = []\n values = []\n d_vector = np.diff(vector)\n change_indices = np.where(d_vector != 0)[0]\n last_value = blank_symbol\n for ind in change_indices:\n value = vector[ind]\n indices.append(ind)\n values.append(value)\n # last_value=value\n\n # last_v = blank_symbol\n # for v in values:\n # assert v != blank_symbol, 'v: {}'.format(blank_symbol)\n # assert v != last_v, 'v {} last_v {} '.format(v,last_v)\n # last_v = v\n\n return np.array(indices, dtype=np.int), np.array(values, dtype=np.int)\n\ndef label_stack_to_sparse_tensor(label_stack, blank_symbol):\n sparse_tensor = {'indices': [], 'values': []}\n\n for i_batch, phns in enumerate(label_stack):\n indices, values = sparsity_dense_vector(phns, blank_symbol)\n\n sparse_tensor['indices'].append([[i_batch, i_time] for i_time in indices])\n sparse_tensor['values'].append(values)\n\n sparse_tensor['indices'] = np.concatenate(sparse_tensor['indices'])\n sparse_tensor['values'] = np.concatenate(sparse_tensor['values'])\n\n return sparse_tensor\n\nclass Timit(Dataset):\n def __init__(self, phase, data_path = 'E:/Study/Data/essaycode/metaandDRTP/Code/DATASETS/timit_processed', preproc = None, use_reduced_phonem_set = True, return_sparse_phonem_tensor = False, epsilon = 1e-10):\n super(Timit, self).__init__()\n assert preproc is not None\n self.phase = phase\n self.data_path = data_path\n self.preproc = preproc\n self.use_reduced_phonem_set = use_reduced_phonem_set\n self.return_sparse_phn_tensor = return_sparse_phonem_tensor\n\n self.n_time = 780\n\n self.epsilon = epsilon\n\n self.n_feats = {'fbank': 41 * 3, 'mfccs': 13 * 3, 'htk': 13 * 3 if 'htk_mfcc' in data_path else 41 * 3, 'cochspec': 86 * 3, 'cochspike': 86} # 'mfccspike': 13 * 31, 'melspec': 16 * 3, 'melspike': 496\n self.n_features = self.n_feats[preproc]\n self.n_phns = 39 if use_reduced_phonem_set else 61\n\n # Load features from files\n self.feature_stack_train, self.phonem_stack_train, self.meta_data_train, _, _ = self.load_data_stack('train')\n self.feature_stack_test, self.phonem_stack_test, self.meta_data_test, self.vocabulary, self.wav_test = self.load_data_stack('test')\n self.feature_stack_develop, self.phonem_stack_develop, self.meta_data_develop, self.vocabulary, self.wav_val = self.load_data_stack('develop')\n\n def add_derivatives(features):\n n_features = features[0].shape[1]\n\n # add derivatives:\n get_delta = lambda v : np.concatenate([np.zeros((1, v.shape[1])), v[2:] - v[:-2], np.zeros((1, v.shape[1]))],axis = 0)\n d_features = [get_delta(f) for f in features]\n d2_features = [get_delta(f) for f in d_features]\n\n features = [np.concatenate([f, d_f, d2_f], axis=1) for f,d_f,d2_f in zip(features,d_features,d2_features)]\n assert (features[0].shape[1] == self.n_features)\n return features\n\n if self.preproc not in ['cochspike', 'htk']:\n self.feature_stack_train = add_derivatives(self.feature_stack_train)\n self.feature_stack_test = add_derivatives(self.feature_stack_test)\n self.feature_stack_develop = add_derivatives(self.feature_stack_develop)\n\n # normalize the features\n concatenated_training_features = np.concatenate(self.feature_stack_train, axis = 0)\n means = np.mean(concatenated_training_features, axis = 0)\n stds = np.std(concatenated_training_features, axis = 0)\n\n if self.preproc != 'cochspike':\n self.feature_stack_train = [(f - means) / np.maximum(stds,self.epsilon) for f in self.feature_stack_train]\n self.feature_stack_test = [(f - means) / np.maximum(stds,self.epsilon) for f in self.feature_stack_test]\n self.feature_stack_develop = [(f - means) / np.maximum(stds,self.epsilon) for f in self.feature_stack_develop]\n\n self.feature_stack_train = np.array(self.feature_stack_train,dtype=object)\n self.feature_stack_test = np.array(self.feature_stack_test,dtype=object)\n self.feature_stack_develop = np.array(self.feature_stack_develop,dtype=object)\n\n assert (len(self.vocabulary) == self.n_phns)\n\n self.n_train = len(self.feature_stack_train)\n self.n_test = len(self.feature_stack_test)\n self.n_develop = len(self.feature_stack_develop)\n\n # print('Dataset sizes: test {} \\t train {} \\t validation {}'.format(self.n_test,self.n_train,self.n_develop))\n\n def __len__(self):\n if self.phase == 'train':\n return self.n_train\n if self.phase == 'develop':\n return self.n_develop\n if self.phase == 'test':\n return self.n_test\n\n def reduce_phonem_list(self, phn_list):\n return [self.phonem_reduction_map[k] for k in phn_list]\n\n def load_data_stack(self, dataset):\n path = os.path.join(self.data_path, dataset)\n\n # Define the link to the pickle objects\n if self.preproc == 'fbank':\n feature_path = os.path.join(path, 'filter_banks.pickle')\n elif self.preproc == 'mfccs':\n feature_path = os.path.join(path, 'mfccs.pickle')\n elif self.preproc == 'htk':\n feature_path = os.path.join(path, 'htk.pickle')\n # elif self.preproc == 'mfccspike':\n # feature_path = os.path.join(path, 'mfcc_spike_stack.pickle')\n # elif self.preproc == 'melspec':\n # feature_path = os.path.join(path, 'specgram.pickle')\n # elif self.preproc == 'melspike':\n # feature_path = os.path.join(path, 'spike.pickle')\n elif self.preproc == 'cochspec':\n feature_path = os.path.join(path, 'coch_raw.pickle')\n elif self.preproc == 'cochspike':\n feature_path = os.path.join(path, 'coch_spike.pickle')\n else:\n raise NotImplementedError('Preprocessing %s not available' % self.preproc)\n\n if self.use_reduced_phonem_set:\n phonem_path = os.path.join(path, 'reduced_phonems.pickle')\n vocabulary_path = os.path.join(path, 'reduced_phonem_list.json')\n else:\n phonem_path = os.path.join(path, 'phonems.pickle')\n vocabulary_path = os.path.join(path, 'phonem_list.json')\n\n # Load the data\n with open(feature_path, 'rb') as f:\n data_stack = pickle.load(f)\n\n with open(phonem_path, 'rb') as f:\n phonem_stack = pickle.load(f)\n\n for phns in phonem_stack:\n assert ((np.array(phns) < self.n_phns).all()), 'Found phonems up to {} should be maximum {}'.format(\n np.max(phns), self.n_phns)\n\n # Load the vocabulay\n with open(vocabulary_path, 'r') as f:\n vocabulary = json.load(f)\n\n assert vocabulary[0] == ('sil' if self.use_reduced_phonem_set else 'h#')\n self.silence_symbol_id = 0\n\n # Load meta data\n with open(os.path.join(path, 'metadata.pickle'), 'rb') as f:\n metadata = pickle.load(f)\n\n assert vocabulary[0] == ('sil' if self.use_reduced_phonem_set else 'h#')\n self.silence_symbol_id = 0\n\n with open(os.path.join(path, 'reduced_phn_index_mapping.json'), 'r') as f:\n self.phonem_reduction_map = json.load(f)\n\n # Load raw audio\n wav_path = os.path.join(path, 'wav.pickle')\n with open(wav_path, 'rb') as f:\n wav_stack = pickle.load(f)\n\n return data_stack, phonem_stack, metadata, vocabulary, wav_stack\n\n def __getitem__(self, idx):\n if self.phase == 'train':\n feature_stack = self.feature_stack_train[idx]\n phonem_stack = self.phonem_stack_train[idx]\n wavs = None\n elif self.phase == 'test':\n feature_stack = self.feature_stack_test[idx]\n phonem_stack = self.phonem_stack_test[idx]\n wavs = self.wav_test[idx]\n elif self.phase == 'develop':\n feature_stack = self.feature_stack_develop[idx]\n phonem_stack = self.phonem_stack_develop[idx]\n wavs = self.wav_val[idx]\n\n seq_len = feature_stack.shape[0]\n #feature = feature_stack\n feature = pad_vector(feature_stack, self.n_time)\n\n if self.return_sparse_phn_tensor:\n phns = label_stack_to_sparse_tensor(phonem_stack, self.silence_symbol_id)\n else:\n phns = pad_vector(phonem_stack, self.n_time, self.silence_symbol_id)\n #phns = phonem_stack\n \n return torch.FloatTensor(feature), torch.LongTensor(phns), seq_len\n#以上是TIMIT数据集的读取程序\n\ndef load_dataset_tidigits(args, kwargs):\n \n n_bands = 39\n n_frames = 39\n args.input_size = n_bands\n args.input_channels = 1\n args.label_features = 10\n\n train_dataset = Tidigits('train',args.input_channels, n_bands,n_frames,transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.0,),(1.0,))]))\n traintest_dataset = Tidigits('valid',args.input_channels,n_bands,n_frames,transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.0,),(1.0,))]))\n test_dataset = Tidigits('test',args.input_channels,n_bands,n_frames,transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.0,),(1.0,))]))\n\n train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=args.batch_size,shuffle = True, drop_last = True)\n traintest_loader = torch.utils.data.DataLoader(dataset=traintest_dataset, batch_size=args.test_batch_size,shuffle = False,drop_last = True)\n test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=args.test_batch_size,shuffle = False,drop_last = True)\n\n \n\n return (train_loader, traintest_loader, test_loader)\n\n\ndef load_dataset_gesture(args, kwargs):\n\n args.input_size = 32*32\n args.input_channels = 1\n args.label_features = 11\n\n train_dataset = Gesture('train', transform=transforms.ToTensor())\n test_dataset = Gesture('test', transform=transforms.ToTensor())\n train_loader = torch.utils.data.DataLoader(dataset = train_dataset,batch_size = args.batch_size,shuffle = True,drop_last=True)\n traintest_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=args.batch_size, shuffle=False,drop_last=True)\n test_loader = torch.utils.data.DataLoader(dataset = test_dataset,batch_size = args.batch_size,shuffle = False,drop_last=True)\n\n return (train_loader, traintest_loader, test_loader)\n\n\ndef load_dataset_timit(args, kwargs):\n args.input_size = 39\n args.input_channels = 1\n args.label_features = 39\n\n train_dataset = Timit('train', preproc='mfccs')\n test_dataset = Timit('test', preproc='mfccs')\n\n train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=args.batch_size, shuffle=True, num_workers=0, drop_last=True)\n traintest_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=args.batch_size, shuffle=False, num_workers=0, drop_last=True)\n test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=args.batch_size, shuffle=False, num_workers=0, drop_last=True)\n\n\n return (train_loader, traintest_loader, test_loader)\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":27246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"166526024","text":"import glob\nimport os\n\nimport pdftables_api\n\nc = pdftables_api.Client('6yc5mavlgq4v')\npdf_folder_path = r\"C:\\pdf\"\npdf_files = glob.glob(pdf_folder_path+\"/*.pdf\")\nfor pdf_path in pdf_files:\n path, filename = os.path.split(pdf_path)\n text_file = filename.replace(\".pdf\", \"\")\n c.xlsx(pdf_path, pdf_folder_path+\"/\"+text_file)\n#replace c.xlsx with c.csv to convert to CSV\n#replace c.xlsx with c.xml to convert to XML\n#replace c.xlsx with c.html to convert to HTML","sub_path":"pdftoxlsx.py","file_name":"pdftoxlsx.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"498569354","text":"# -*- coding:utf-8 -*-\n\n\"\"\"\nFile Name : 'jths_asr'.py\nDescription:\nAuthor: 'weicheng'\nDate: '2018/3/21' '下午5:57'\n\"\"\"\nimport requests\nimport datetime\nimport hashlib\nimport json\nimport os\n\n\nresult_file = open('jths-8k.txt', 'w', encoding='utf-8')\n\n\ndef get_session_key(cur_time):\n src_str = cur_time + \"28c173ce82c7c7ef5de62f0c52ebcc54\"\n m2 = hashlib.md5(src_str.encode())\n md5_rst = m2.hexdigest()\n return md5_rst\n\n\ndef recog_single(wav_file):\n url = \"http://api.hcicloud.com:8880/asr/Recognise\"\n cur_day = datetime.datetime.now().strftime('%Y-%m-%d')\n cur_time1 = datetime.datetime.now().strftime('%H:%M:%S')\n cur_time = cur_day + \" \" + cur_time1\n session_key_str = get_session_key(cur_time)\n header = {'x-app-key': \"745d540c\",\n 'x-sdk-version': \"5.0\",\n 'x-request-date': cur_time,\n 'x-result-format': \"json\",\n 'x-task-config': \"capkey=asr.cloud.freetalk,audioformat=pcm8k16bit,domain=telecom\",\n 'x-session-key': session_key_str,\n 'x-udid': \"101:1234567890\"\n }\n\n wave_data = open(wav_file, \"rb\")\n r = requests.post(url, headers=header, data=wave_data)\n if r.status_code == 200:\n r.encoding = r.apparent_encoding\n # print(r.text)\n result = json.loads(r.text)\n result_text = result['ResponseInfo']['Result']['Text']\n result_score = result['ResponseInfo']['Result']['Score']\n result_code = result['ResponseInfo']['ErrorNo']\n return result_code, result_text, result_score\n\n\n# def file_name(file_dir):\n# for root, dirs, files in os.walk(file_dir):\n# for dir in dirs:\n# if dir.endswith(('2', '4', '6', '8')):\n# path = os.path.join(file_dir, dir)\n#\n# return files\n\nif __name__ == '__main__':\n recog_single(r'D:\\MLproject\\qq_try\\音频识别脚本\\input\\8k\\13505713525_1502762667_84812.wav')\n # recog_single('/Users/weicheng/Documents/15335178985_1521615997_8372761_12.wav')\n #recog_single('/Users/weicheng/Documents/15335178985_1521615997_8372761_15.wav')\n # file_list = file_name('/Users/weicheng/project/asr-test/test_wav')","sub_path":"音频识别脚本/jlhs/jths_asr_8.py","file_name":"jths_asr_8.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"505243783","text":"import xml.dom.minidom as xml\nfrom string import Template\nimport tempfile, os, codecs, sys\n\nclass TempFile(object):\n def __init__(self, finalTargetFilePath):\n tmpfd, self.temppath = tempfile.mkstemp()\n self.tmpfo = os.fdopen(tmpfd, 'w')\n self.targetPath = finalTargetFilePath\n\n def __enter__(self):\n return codecs.EncodedFile(self.tmpfo, 'utf-8', 'utf-8')\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.tmpfo.close()\n if not exc_type:\n if os.path.exists(self.targetPath):\n os.remove(self.targetPath)\n os.rename(self.temppath, self.targetPath)\n else:\n os.unlink(self.temppath)\n return None\n\n\n\nclass AndroidManifestInst(object):\n def __init__(self, path=None):\n if path is None:\n self._initEmptyManifest()\n else:\n self.doc = xml.parse(path)\n\n def getPermissions(self):\n parentNode = self.doc.documentElement\n return AndroidManifestInst._getChildrenNS(parentNode, 'uses-permission')\n\n def getPkgName(self):\n return self._rootNode.getAttribute('package')\n\n def replace(self, cfg):\n AndroidManifestInst._walkElementNode(self._rootNode, \n lambda node: replaceNodeAttr(node, cfg))\n\n def replaceEntryActivity(self):\n entryActivityNode = self._findEntryActivity()\n if entryActivityNode is None:\n raise RuntimeError('Fail to find the start entry')\n oldEntry = entryActivityNode.getAttribute('android:name')\n if oldEntry.startswith('.'):\n oldEntry = self.getPkgName()+oldEntry\n if oldEntry == 'prj.chameleon.channelapi.SplashScreenActivity':\n return\n \n intentNode = AndroidManifestInst._getChildNS(entryActivityNode,\n 'intent-filter')\n mainActionNode = AndroidManifestInst._getChildNS(intentNode, \n 'action', [('android:name', 'android.intent.action.MAIN')])\n launchCatNode = AndroidManifestInst._getChildNS(intentNode, \n 'category', [('android:name', 'android.intent.category.LAUNCHER')])\n\n intentNode.removeChild(mainActionNode)\n intentNode.removeChild(launchCatNode)\n splashActivity = self.doc.createElement('activity')\n _fillSplashScreenActivity(self.doc, splashActivity, \n oldEntry, entryActivityNode.getAttribute('android:screenOrientation'))\n self._applicationNode.appendChild(splashActivity)\n\n def merge(self, that):\n self._mergePermissions(that)\n self._mergeActivity(that)\n\n def setElement(self, parent, tag, attrs, valueAttrs):\n parentNode = self.doc.documentElement\n for p in parent:\n parentNode = AndroidManifestInst._getChildNS(parentNode, p)\n if parentNode is None:\n raise RuntimeError(u'fail to find element %s/%s' %(parent, tag))\n childNode = AndroidManifestInst._getChildNS(parentNode, tag, attrs)\n if childNode is None:\n childNode = self.doc.createElement(tag)\n parentNode.appendChild(childNode)\n for (name, value) in attrs:\n childNode.setAttribute(name, value)\n for (name, value) in valueAttrs:\n childNode.setAttribute(name, value)\n\n def createElement(self, parentPath, tag, attrs = None):\n parentNode = self.doc.documentElement\n for p in parentPath:\n if type(p) is tuple:\n if len(p) != 2:\n raise RuntimeError(u'the path tule must be (tag, attr)')\n parentNode = AndroidManifestInst._getChildNs(parentNode, p[0], p[1])\n if parentNode is None:\n raise RuntimeError(u'Fail to find the path ' + repr(p))\n elif type(p) is str:\n parentNode = AndroidManifestInst._getChildNS(parentNode, p)\n childNode = self.doc.createElement(tag)\n parentNode.append(childNode)\n if attrs is not None:\n for name, value in attrs:\n childNode.setAttribute(name, value)\n \n def setIcon(self, iconname):\n self.setElement([], \n 'application', \n [],\n [('android:icon', '@drawable/'+iconname)])\n\n def setMetaData(self, name, value):\n self.setElement(['application'], \n 'meta-data', \n [('android:name', name)], \n [('android:value', value)])\n\n def _findEntryActivity(self):\n activityNodes = AndroidManifestInst._getChildrenNS(self._applicationNode, \n 'activity')\n for n in activityNodes:\n intentNode = AndroidManifestInst._getChildNS(n, 'intent-filter')\n if intentNode is not None:\n actionNode = AndroidManifestInst._getChildNS( intentNode, \n 'action')\n actionNode = AndroidManifestInst._getChildNS( intentNode, \n 'action', \n [('android:name', 'android.intent.action.MAIN')])\n categoryNode = AndroidManifestInst._getChildNS(intentNode,\n 'category', \n [('android:name','android.intent.category.LAUNCHER')])\n if actionNode is not None and categoryNode is not None:\n return n\n\n\n def _mergeActivity(self, that):\n toMerge = [x for x in that._applicationNode.childNodes \n if x.nodeType==x.ELEMENT_NODE]\n for m in toMerge:\n self._applicationNode.appendChild(m)\n\n def _mergePermissions(self, that):\n thatPerm = that.getPermissions()\n myPerm = self.getPermissions() \n myNowPermission = [x.getAttribute('android:name') for x in myPerm]\n toAddPerm = [x for x in thatPerm \n if x.getAttribute('android:name') not in myNowPermission]\n for p in toAddPerm:\n self._rootNode.appendChild(p)\n\n def _initEmptyManifest(self):\n self.doc = xml.getDOMImplementation().createDocument(None, 'manifest', None)\n root = self.doc.documentElement\n root.setAttribute('xmlns:android', 'http://schemas.android.com/apk/res/android')\n root.setAttribute('package', 'prj.chameleon.entry')\n applicationDoc = self.doc.createElement('application')\n root.appendChild(applicationDoc)\n\n def _getChildElement(self, parentNode, tag):\n if type(tag) is tuple:\n parentNode.childNodes\n\n def dump(self, path = None):\n if path is None:\n return self.doc.toprettyxml()\n else:\n f = codecs.open(path, 'w', 'utf8')\n return self.doc.writexml(f, indent=\"\\t\")\n\n def safeDump(self, path):\n with TempFile(path) as f:\n return f.write(self.doc.toxml('utf-8'))\n\n @property\n def _rootNode(self):\n return self.doc.documentElement\n\n @property\n def _applicationNode(self):\n return AndroidManifestInst._getChildNS(self._rootNode, 'application')\n\n @staticmethod\n def _getChildNS(node, tag, attrs=None):\n for n in node.childNodes:\n if AndroidManifestInst._matchNode(n, tag, attrs):\n return n\n return None\n\n @staticmethod\n def _getChildrenNS(node, tag, attrs = None):\n return [x for x in node.childNodes if \n AndroidManifestInst._matchNode(x, tag, attrs)]\n \n @staticmethod\n def _matchNode(node, tag, attrs):\n return AndroidManifestInst._matchTag(node, tag) and AndroidManifestInst._matchAttr(node, attrs)\n\n @staticmethod\n def _matchTag(node, tag):\n return node.nodeType==node.ELEMENT_NODE and node.tagName == tag\n\n @staticmethod\n def _matchAttr(node, attrs):\n if attrs is None:\n return True\n for attr in attrs:\n if node.getAttribute(attr[0]) != attr[1]:\n return False\n return True\n\n @staticmethod\n def _walkElementNode(parentNode, func):\n func(parentNode)\n for n in parentNode.childNodes:\n if n.nodeType == n.ELEMENT_NODE:\n AndroidManifestInst._walkElementNode(n, func)\n \n\ndef parseReplaceVal(val):\n ts = val.split(';;')\n return [t.split('=') for t in ts]\n\ndef replaceNodeAttr(node, cfg):\n replaceVal = node.getAttribute(\"chameleon:replace\")\n if len(replaceVal) != 0:\n replaceVal = parseReplaceVal(replaceVal)\n for name, val in replaceVal:\n valTemplate = Template(val)\n t = valTemplate.safe_substitute(cfg)\n node.setAttribute(name, t)\n node.removeAttribute(\"chameleon:replace\")\n\ndef _fillSplashScreenActivity(doc, splashActivity, oldEntryActivity, orientation):\n splashActivity.setAttribute('android:name', \n 'prj.chameleon.channelapi.SplashScreenActivity')\n\n if orientation is not None:\n splashActivity.setAttribute('android:screenOrientation', orientation)\n splashActivity.setAttribute('android:noHistory', \"true\")\n splashActivity.setAttribute('android:stateNotNeeded', \"true\")\n splashActivity.setAttribute('android:launchMode', \"singleTask\")\n splashActivity.setAttribute('android:theme', \n \"@android:style/Theme.NoTitleBar.Fullscreen\")\n metaDataNode = doc.createElement('meta-data')\n metaDataNode.setAttribute('android:name', \"prj.chameleon.intent.main\")\n metaDataNode.setAttribute('android:value', oldEntryActivity)\n splashActivity.appendChild(metaDataNode)\n intentNode = doc.createElement('intent-filter')\n mainActionNode = doc.createElement('action')\n intentNode.appendChild(mainActionNode)\n mainActionNode.setAttribute('android:name', \"android.intent.action.MAIN\")\n splashActivity.appendChild(intentNode)\n categoryNode = doc.createElement('category')\n intentNode.appendChild(categoryNode)\n categoryNode.setAttribute('android:name', \"android.intent.category.LAUNCHER\")\n\n","sub_path":"client/sample/chameleon_cc2d/proj.android/chameleon/tools/AndroidManifest.py","file_name":"AndroidManifest.py","file_ext":"py","file_size_in_byte":9927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"468386724","text":"import socketserver\nimport user\nimport command_parser\nimport command_handler\nimport sys\nimport socket\nimport time\n\n\nclass OverloadException(Exception):\n def __init__(self, message=\"\"):\n self.message = message\n\n def __str__(self):\n return repr(self.message)\n\n\nclass ServerHandler(socketserver.BaseRequestHandler):\n MAX_LENGTH = 1024\n\n def handle_connect(self):\n # get the socket that connect to the client socket\n self.socket = self.request\n self.socket.settimeout(99)\n\n # send greetings\n\n self.socket.send(\n (\"--------------Welcome to MySSH server-------------\\n\")\n .encode()\n )\n\n # create user instance to process commands\n self.handler = command_handler.CommandHandler(\n None, command_parser.CommandParser())\n self.ackno = 0\n self.record = {}\n\n def get_request(self):\n req = self.socket.recv(self.MAX_LENGTH)\n return req[0], req[1:].decode()\n\n def do_operation(self, command):\n self.ackno = (self.ackno + 1) % 256\n\n res = self.handler.process_request(command)\n\n # Flush all records in memory when it's full\n if self.ackno == 0:\n self.record.clear()\n\n # Save result for retransmission\n self.record[self.ackno] = res\n\n return res\n\n def send_reply(self, seqno, command):\n if seqno == (self.ackno + 1) % 256:\n res = self.do_operation(command)\n elif self.record.get(seqno) is not None:\n res = self.record.get(seqno)\n else:\n res = 'Failed to process current request!'\n\n self.socket.send(bytes([seqno]) + res.encode())\n\n def handle(self):\n\n try:\n self.handle_connect()\n\n # listen until client type 'quit'\n while not self.handler.stop:\n seqno, cmd = self.get_request()\n # time.sleep(12)\n self.send_reply(seqno, cmd)\n\n except (ConnectionResetError,\n IndexError,\n ConnectionAbortedError,\n socket.timeout):\n\n if self.handler.user_ins is not None:\n self.handler.user_ins.log_out()\n\n except OverloadException:\n pass\n\n finally:\n self.socket.close()\n\n\nif __name__ == '__main__':\n host = \"\"\n port = 12345\n\n try:\n if len(sys.argv) > 1:\n host = sys.argv[1]\n if len(sys.argv) > 2:\n port = int(sys.argv[2])\n\n user.User.load_users()\n socketserver.ThreadingTCPServer(\n (host, port), ServerHandler).serve_forever()\n user.User.store_users()\n\n except ValueError:\n sys.stderr.write(\"Error: Port number must be an integer!!\")\n sys.exit(1)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"438197057","text":"import cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ncap = cv2.VideoCapture(0)\r\n\r\nrandBool, img = cap.read()\r\ncap.release()\r\n#%matplotlib auto\r\nplt.imshow(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))\r\n\r\nimgR = img[:,:,2]\r\n\r\nplt.imshow(imgR,cmap='gray')\r\nplt.show()\r\nr,c,l = img.shape\r\nimgOutput = np.ones((r,c)).astype('uint8')\r\nimgOutput[:,0:100]=255\r\ncv2.imshow('output',imgOutput)\r\ncv2.waitKey(0)\r\n\r\nwhile(True):\r\n ret,img = cap.read()\r\n \r\n cv2.imshow(\"output\",img)\r\n if cv2.waitKey(1) == 27:\r\n break\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nimport cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ncap = cv2.VideoCapture(0)\r\n\r\nwhile(True):\r\n ret,img = cap.read()\r\n \r\n cv2.imshow('Frames',img)\r\n if cv2.waitKey(1) == 27:\r\n break\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nimport cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ncap = cv2.VideoCapture(0)\r\n\r\nret,img = cap.read()\r\ncap.release()\r\n\r\nimgR = img[:,:,2]\r\nimgG = img[:,:,1]\r\nimgB = img[:,:,0]\r\n\r\nplt.imshow(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))\r\n\r\nrMin=104\r\nrMax=176\r\n\r\ngMin=24\r\ngMax=77\r\n\r\nbMin=22\r\nbMax=131\r\nr,c,l = img.shape\r\n\r\noutput = np.zeros((r,c))\r\nfor i in range(0,r):\r\n for j in range(0,c):\r\n if imgR[i,j] >= rMax and imgR[i,j] <= rMin and imgG[i,j] >= gMax and imgG[i,j] <= gMin and imgB[i,j] >= bMax and imgB[i,j] <= bMin:\r\n output[i,j] = 255\r\nplt.subplot(1,2,1)\r\nplt.imshow(output,cmap=\"gray\")\r\nplt.subplot(1,2,2)\r\nplt.imshow(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))\r\n","sub_path":"image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"81695308","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\n\ndef assignment(observations, centroids):\n \"\"\"Assign each of the observation to the nearest centroid.\"\"\"\n clusters = []\n\n for centroid in centroids:\n clusters.append([centroid])\n\n for observation in observations:\n targetCentroid = findNearestCentroid(observation, centroids)\n \n for cluster in clusters:\n if np.array_equal(targetCentroid, cluster[0]):\n cluster.append(observation)\n\n for i in range(0, len(clusters)):\n clusters[i] = np.array(clusters[i])\n\n return clusters\n \ndef findNearestCentroid(observation, centroids):\n \"\"\"Find the nearest euclidean distance between the current observation\n and provided centroids.\"\"\"\n nearest = None\n lowest_distance = None\n\n for centroid in centroids:\n distance = 0\n\n for (i,), value in np.ndenumerate(centroid):\n distance = distance + np.square(centroid[i] - observation[i]) \n\n distance = np.sqrt(distance)\n\n if lowest_distance is None or lowest_distance > distance:\n lowest_distance = distance\n nearest = centroid\n\n return nearest","sub_path":"assignment.py","file_name":"assignment.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"7433839","text":"from uai.operation.base_operation import BaseUaiServiceOp\nfrom uai.api.modify_uai_srv_version_weight import ModifyUAISrvVersionWeightOp\n\n\nclass UaiServiceModifyWeightOp(BaseUaiServiceOp):\n def __init__(self, parser):\n super(UaiServiceModifyWeightOp, self).__init__(parser)\n\n def _add_args(self, parser):\n super(UaiServiceModifyWeightOp, self)._add_args(parser)\n args_parser = parser.add_argument_group()\n args_parser.add_argument(\n '--service_id',\n type=str,\n required=True,\n help='the uai service id')\n\n args_parser.add_argument(\n '--paas_id',\n type=str,\n required=True,\n help='the paas id of uai service')\n\n args_parser.add_argument(\n '--service_version',\n type=str,\n required=True,\n help='the version number of uai service')\n\n args_parser.add_argument(\n '--deploy_weight',\n type=int,\n default=10,\n required=True,\n help='the weight on grayscale publishing, int between 1 to 100')\n # add other params in subclasses#\n\n def _parse_args(self):\n super(UaiServiceModifyWeightOp, self)._parse_args()\n self.srv_version = self.params['service_version'] if 'service_version' in self.params else ''\n self.service_id = self.params['service_id'] if 'service_id' in self.params else ''\n self.srv_paas_id = self.params['paas_id'] if 'paas_id' in self.params else ''\n self.deploy_weight = self.params['deploy_weight'] if 'deploy_weight' in self.params else ''\n if self.deploy_weight > 100 or self.deploy_weight < 0:\n raise RuntimeError('the param deploy_weight must be between 1 and 100')\n # add other params in subclasses#\n\n def cmd_run(self, params):\n super(UaiServiceModifyWeightOp, self).cmd_run(params)\n modifyOp = ModifyUAISrvVersionWeightOp(public_key=self.public_key,\n private_key=self.private_key,\n project_id=self.project_id,\n region=self.region,\n zone=self.zone,\n service_id=self.service_id,\n srv_paas_id=self.srv_paas_id,\n srv_version=self.srv_version,\n deploy_weight=self.deploy_weight)\n succ, rsp = modifyOp.call_api()\n return succ, rsp","sub_path":"uai/operation/modifyweight.py","file_name":"modifyweight.py","file_ext":"py","file_size_in_byte":2575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"366273710","text":"# -*- encoding: utf-8 -*-\n# Copyright (c) 2015 b<>com\n#\n# Authors: Jean-Emile DARTOIS \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\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport oslo_utils\n\n\nclass FakeCeilometerMetrics(object):\n NAME = 'ceilometer'\n\n def __init__(self):\n self.emptytype = \"\"\n\n def empty_one_metric(self, emptytype):\n self.emptytype = emptytype\n\n def mock_get_statistics(self, resource_id=None, meter_name=None,\n period=None, granularity=None, dimensions=None,\n aggregation='avg', group_by='*'):\n result = 0\n if meter_name == \"hardware.cpu.util\":\n result = self.get_usage_node_cpu(resource_id)\n elif meter_name == \"compute.node.cpu.percent\":\n result = self.get_usage_node_cpu(resource_id)\n elif meter_name == \"hardware.memory.used\":\n result = self.get_usage_node_ram(resource_id)\n elif meter_name == \"cpu_util\":\n result = self.get_average_usage_instance_cpu(resource_id)\n elif meter_name == \"memory.resident\":\n result = self.get_average_usage_instance_memory(resource_id)\n elif meter_name == \"hardware.ipmi.node.outlet_temperature\":\n result = self.get_average_outlet_temperature(resource_id)\n elif meter_name == \"hardware.ipmi.node.airflow\":\n result = self.get_average_airflow(resource_id)\n elif meter_name == \"hardware.ipmi.node.temperature\":\n result = self.get_average_inlet_t(resource_id)\n elif meter_name == \"hardware.ipmi.node.power\":\n result = self.get_average_power(resource_id)\n return result\n\n def mock_get_statistics_wb(self, resource_id, meter_name, period,\n granularity, dimensions=None,\n aggregation='avg', group_by='*'):\n result = 0.0\n if meter_name == \"cpu_util\":\n result = self.get_average_usage_instance_cpu_wb(resource_id)\n elif meter_name == \"memory.resident\":\n result = self.get_average_usage_instance_memory_wb(resource_id)\n return result\n\n def mock_get_statistics_nn(self, resource_id, period,\n aggregation, granularity=300):\n result = 0.0\n if period == 100:\n result = self.get_average_l3_cache_current(resource_id)\n if period == 200:\n result = self.get_average_l3_cache_previous(resource_id)\n return result\n\n @staticmethod\n def get_average_l3_cache_current(uuid):\n \"\"\"The average l3 cache used by instance\"\"\"\n mock = {}\n mock['73b09e16-35b7-4922-804e-e8f5d9b740fc'] = 35 * oslo_utils.units.Ki\n mock['cae81432-1631-4d4e-b29c-6f3acdcde906'] = 30 * oslo_utils.units.Ki\n mock['INSTANCE_3'] = 40 * oslo_utils.units.Ki\n mock['INSTANCE_4'] = 35 * oslo_utils.units.Ki\n if uuid not in mock.keys():\n mock[uuid] = 25 * oslo_utils.units.Ki\n return mock[str(uuid)]\n\n @staticmethod\n def get_average_l3_cache_previous(uuid):\n \"\"\"The average l3 cache used by instance\"\"\"\n mock = {}\n mock['73b09e16-35b7-4922-804e-e8f5d9b740fc'] = 34.5 * (\n oslo_utils.units.Ki)\n mock['cae81432-1631-4d4e-b29c-6f3acdcde906'] = 30.5 * (\n oslo_utils.units.Ki)\n mock['INSTANCE_3'] = 60 * oslo_utils.units.Ki\n mock['INSTANCE_4'] = 22.5 * oslo_utils.units.Ki\n if uuid not in mock.keys():\n mock[uuid] = 25 * oslo_utils.units.Ki\n return mock[str(uuid)]\n\n @staticmethod\n def get_average_outlet_temperature(uuid):\n \"\"\"The average outlet temperature for host\"\"\"\n mock = {}\n mock['Node_0'] = 30\n # use a big value to make sure it exceeds threshold\n mock['Node_1'] = 100\n if uuid not in mock.keys():\n mock[uuid] = 100\n return float(mock[str(uuid)])\n\n @staticmethod\n def get_usage_node_ram(uuid):\n mock = {}\n # Ceilometer returns hardware.memory.used samples in KB.\n mock['Node_0'] = 7 * oslo_utils.units.Ki\n mock['Node_1'] = 5 * oslo_utils.units.Ki\n mock['Node_2'] = 29 * oslo_utils.units.Ki\n mock['Node_3'] = 8 * oslo_utils.units.Ki\n mock['Node_4'] = 4 * oslo_utils.units.Ki\n\n if uuid not in mock.keys():\n # mock[uuid] = random.randint(1, 4)\n mock[uuid] = 8\n\n return float(mock[str(uuid)])\n\n @staticmethod\n def get_average_airflow(uuid):\n \"\"\"The average outlet temperature for host\"\"\"\n mock = {}\n mock['Node_0'] = 400\n # use a big value to make sure it exceeds threshold\n mock['Node_1'] = 100\n if uuid not in mock.keys():\n mock[uuid] = 200\n return mock[str(uuid)]\n\n @staticmethod\n def get_average_inlet_t(uuid):\n \"\"\"The average outlet temperature for host\"\"\"\n mock = {}\n mock['Node_0'] = 24\n mock['Node_1'] = 26\n if uuid not in mock.keys():\n mock[uuid] = 28\n return mock[str(uuid)]\n\n @staticmethod\n def get_average_power(uuid):\n \"\"\"The average outlet temperature for host\"\"\"\n mock = {}\n mock['Node_0'] = 260\n mock['Node_1'] = 240\n if uuid not in mock.keys():\n mock[uuid] = 200\n return mock[str(uuid)]\n\n @staticmethod\n def get_usage_node_cpu(*args, **kwargs):\n \"\"\"The last VM CPU usage values to average\n\n :param uuid:00\n :return:\n \"\"\"\n uuid = args[0]\n # query influxdb stream\n\n # compute in stream\n\n # Normalize\n mock = {}\n # node 0\n mock['Node_0_hostname_0'] = 7\n mock['Node_1_hostname_1'] = 7\n # node 1\n mock['Node_2_hostname_2'] = 80\n # node 2\n mock['Node_3_hostname_3'] = 5\n mock['Node_4_hostname_4'] = 5\n mock['Node_5_hostname_5'] = 10\n\n # node 3\n mock['Node_6_hostname_6'] = 8\n # This node doesn't send metrics\n mock['LOST_NODE_hostname_7'] = None\n mock['Node_19_hostname_19'] = 10\n # node 4\n mock['INSTANCE_7_hostname_7'] = 4\n\n mock['Node_0'] = 7\n mock['Node_1'] = 5\n mock['Node_2'] = 10\n mock['Node_3'] = 4\n mock['Node_4'] = 2\n\n if uuid not in mock.keys():\n # mock[uuid] = random.randint(1, 4)\n mock[uuid] = 8\n\n if mock[str(uuid)] is not None:\n return float(mock[str(uuid)])\n else:\n return mock[str(uuid)]\n\n @staticmethod\n def get_average_usage_instance_cpu_wb(uuid):\n \"\"\"The last VM CPU usage values to average\n\n :param uuid:00\n :return:\n \"\"\"\n # query influxdb stream\n\n # compute in stream\n\n # Normalize\n mock = {}\n # node 0\n mock['INSTANCE_1'] = 80\n mock['73b09e16-35b7-4922-804e-e8f5d9b740fc'] = 50\n # node 1\n mock['INSTANCE_3'] = 20\n mock['INSTANCE_4'] = 10\n return float(mock[str(uuid)])\n\n @staticmethod\n def get_average_usage_instance_memory_wb(uuid):\n mock = {}\n # node 0\n mock['INSTANCE_1'] = 30\n # node 1\n mock['INSTANCE_3'] = 12\n mock['INSTANCE_4'] = 12\n if uuid not in mock.keys():\n # mock[uuid] = random.randint(1, 4)\n mock[uuid] = 12\n\n return mock[str(uuid)]\n\n @staticmethod\n def get_average_usage_instance_cpu(*args, **kwargs):\n \"\"\"The last VM CPU usage values to average\n\n :param uuid:00\n :return:\n \"\"\"\n uuid = args[0]\n # query influxdb stream\n\n # compute in stream\n\n # Normalize\n mock = {}\n # node 0\n mock['INSTANCE_0'] = 7\n mock['INSTANCE_1'] = 7\n # node 1\n mock['INSTANCE_2'] = 10\n # node 2\n mock['INSTANCE_3'] = 5\n mock['INSTANCE_4'] = 5\n mock['INSTANCE_5'] = 10\n\n # node 3\n mock['INSTANCE_6'] = 8\n\n # node 4\n mock['INSTANCE_7'] = 4\n\n mock['LOST_INSTANCE'] = None\n if uuid not in mock.keys():\n # mock[uuid] = random.randint(1, 4)\n mock[uuid] = 8\n\n return mock[str(uuid)]\n\n @staticmethod\n def get_average_usage_instance_memory(uuid):\n mock = {}\n # node 0\n mock['INSTANCE_0'] = 2\n mock['INSTANCE_1'] = 5\n # node 1\n mock['INSTANCE_2'] = 5\n # node 2\n mock['INSTANCE_3'] = 8\n mock['INSTANCE_4'] = 5\n mock['INSTANCE_5'] = 16\n\n # node 3\n mock['INSTANCE_6'] = 8\n\n # node 4\n mock['INSTANCE_7'] = 4\n if uuid not in mock.keys():\n # mock[uuid] = random.randint(1, 4)\n mock[uuid] = 10\n\n return mock[str(uuid)]\n\n @staticmethod\n def get_average_usage_instance_disk(uuid):\n mock = {}\n # node 0\n mock['INSTANCE_0'] = 2\n mock['INSTANCE_1'] = 2\n # node 1\n mock['INSTANCE_2'] = 2\n # node 2\n mock['INSTANCE_3'] = 10\n mock['INSTANCE_4'] = 15\n mock['INSTANCE_5'] = 20\n\n # node 3\n mock['INSTANCE_6'] = 8\n\n # node 4\n mock['INSTANCE_7'] = 4\n\n if uuid not in mock.keys():\n # mock[uuid] = random.randint(1, 4)\n mock[uuid] = 4\n\n return mock[str(uuid)]\n","sub_path":"python-watcher-2.0.0/watcher/tests/decision_engine/model/ceilometer_metrics.py","file_name":"ceilometer_metrics.py","file_ext":"py","file_size_in_byte":9855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"386606555","text":"\"\"\"Tests for (almost) algorithm independent properties of maximize and minimize.\"\"\"\nimport numpy as np\nimport pandas as pd\nimport pytest\n\nfrom estimagic.examples.criterion_functions import sos_scalar_criterion\nfrom estimagic.optimization.optimize import maximize\nfrom estimagic.optimization.optimize import minimize\n\n\ndef test_sign_is_switched_back_after_maximization():\n params = pd.DataFrame()\n params[\"value\"] = [1, 2, 3]\n res = maximize(\n lambda params: 1 - params[\"value\"] @ params[\"value\"],\n params=params,\n algorithm=\"scipy_lbfgsb\",\n )\n\n assert np.allclose(res[\"solution_criterion\"], 1)\n\n\ndef test_warnings_with_old_bounds_names():\n base_params = pd.DataFrame()\n base_params[\"value\"] = [1, 2, 3]\n\n for wrong_name in \"lower\", \"upper\":\n params = base_params.copy()\n params[wrong_name] = 0\n with pytest.warns(UserWarning):\n maximize(\n lambda params: 1 - params[\"value\"] @ params[\"value\"],\n params=params,\n algorithm=\"scipy_lbfgsb\",\n )\n\n\ndef test_scipy_lbfgsb_actually_calls_criterion_and_derivative():\n params = pd.DataFrame(data=np.ones((10, 1)), columns=[\"value\"])\n\n def raising_crit_and_deriv(params):\n raise Exception()\n\n with pytest.raises(Exception):\n minimize(\n criterion=sos_scalar_criterion,\n params=params,\n algorithm=\"scipy_lbfgsb\",\n criterion_and_derivative=raising_crit_and_deriv,\n )\n","sub_path":"estimagic/tests/optimization/test_optimize.py","file_name":"test_optimize.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"558072754","text":"\"\"\" To find the most expensive goods and return a certain\nnumber of entries \"\"\"\n\ndef sorted_prices(limit, data):\n\n result = sorted(data, key=lambda x: x['price'], reverse=True)\n\n return result[:limit]\n\n\ngoods = [\n {\"name\": \"bread\", \"price\": 100},\n {\"name\": \"wine\", \"price\": 138},\n {\"name\": \"milk\", \"price\": 31},\n {\"name\": \"meat\", \"price\": 15},\n {\"name\": \"orange\", \"price\": 147},\n {\"name\": \"water\", \"price\": 1}\n ]\n\nprint(sorted_prices(3, goods))","sub_path":"sorted_prices.py","file_name":"sorted_prices.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"131888182","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.6-x86_64/egg/bibolamazi_gui/qtauto/ui_openbibfile.py\n# Compiled at: 2015-05-11 05:40:29\nfrom PyQt4 import QtCore, QtGui\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n\n def _fromUtf8(s):\n return s\n\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\n\n\nexcept AttributeError:\n\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\n\nclass Ui_OpenBibFile(object):\n\n def setupUi(self, OpenBibFile):\n OpenBibFile.setObjectName(_fromUtf8('OpenBibFile'))\n OpenBibFile.resize(787, 501)\n self.lyt = QtGui.QGridLayout(OpenBibFile)\n self.lyt.setObjectName(_fromUtf8('lyt'))\n self.btnGo = QtGui.QPushButton(OpenBibFile)\n self.btnGo.setMinimumSize(QtCore.QSize(0, 40))\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(':/pic/ok.png')), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.btnGo.setIcon(icon)\n self.btnGo.setObjectName(_fromUtf8('btnGo'))\n self.lyt.addWidget(self.btnGo, 1, 0, 1, 1)\n self.tabs = QtGui.QTabWidget(OpenBibFile)\n self.tabs.setTabPosition(QtGui.QTabWidget.South)\n self.tabs.setObjectName(_fromUtf8('tabs'))\n self.pageConfig = QtGui.QWidget()\n self.pageConfig.setObjectName(_fromUtf8('pageConfig'))\n self.verticalLayout_2 = QtGui.QVBoxLayout(self.pageConfig)\n self.verticalLayout_2.setSpacing(3)\n self.verticalLayout_2.setContentsMargins(0, 0, 0, 8)\n self.verticalLayout_2.setObjectName(_fromUtf8('verticalLayout_2'))\n self.splitEditConfig = QtGui.QSplitter(self.pageConfig)\n self.splitEditConfig.setOrientation(QtCore.Qt.Horizontal)\n self.splitEditConfig.setObjectName(_fromUtf8('splitEditConfig'))\n self.txtConfig = QtGui.QTextEdit(self.splitEditConfig)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(9)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.txtConfig.sizePolicy().hasHeightForWidth())\n self.txtConfig.setSizePolicy(sizePolicy)\n self.txtConfig.setAcceptRichText(False)\n self.txtConfig.setObjectName(_fromUtf8('txtConfig'))\n self.stackEditTools = QtGui.QStackedWidget(self.splitEditConfig)\n self.stackEditTools.setFrameShape(QtGui.QFrame.StyledPanel)\n self.stackEditTools.setFrameShadow(QtGui.QFrame.Raised)\n self.stackEditTools.setObjectName(_fromUtf8('stackEditTools'))\n self.toolspageBase = QtGui.QWidget()\n self.toolspageBase.setObjectName(_fromUtf8('toolspageBase'))\n self.verticalLayout_3 = QtGui.QVBoxLayout(self.toolspageBase)\n self.verticalLayout_3.setObjectName(_fromUtf8('verticalLayout_3'))\n self.lblFavorites = QtGui.QLabel(self.toolspageBase)\n self.lblFavorites.setPixmap(QtGui.QPixmap(_fromUtf8(':/pic/bookmark.png')))\n self.lblFavorites.setAlignment(QtCore.Qt.AlignCenter)\n self.lblFavorites.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)\n self.lblFavorites.setObjectName(_fromUtf8('lblFavorites'))\n self.verticalLayout_3.addWidget(self.lblFavorites)\n self.treeFavorites = QtGui.QTreeView(self.toolspageBase)\n font = QtGui.QFont()\n font.setItalic(True)\n self.treeFavorites.setFont(font)\n self.treeFavorites.setDragDropMode(QtGui.QAbstractItemView.InternalMove)\n self.treeFavorites.setRootIsDecorated(False)\n self.treeFavorites.setObjectName(_fromUtf8('treeFavorites'))\n self.treeFavorites.header().setVisible(False)\n self.verticalLayout_3.addWidget(self.treeFavorites)\n self.line = QtGui.QFrame(self.toolspageBase)\n self.line.setFrameShape(QtGui.QFrame.HLine)\n self.line.setFrameShadow(QtGui.QFrame.Sunken)\n self.line.setObjectName(_fromUtf8('line'))\n self.verticalLayout_3.addWidget(self.line)\n self.btnAddSourceList = QtGui.QPushButton(self.toolspageBase)\n self.btnAddSourceList.setObjectName(_fromUtf8('btnAddSourceList'))\n self.verticalLayout_3.addWidget(self.btnAddSourceList)\n self.btnAddFilter = QtGui.QPushButton(self.toolspageBase)\n self.btnAddFilter.setObjectName(_fromUtf8('btnAddFilter'))\n self.verticalLayout_3.addWidget(self.btnAddFilter)\n self.stackEditTools.addWidget(self.toolspageBase)\n self.toolspageSource = QtGui.QWidget()\n self.toolspageSource.setObjectName(_fromUtf8('toolspageSource'))\n self.verticalLayout_4 = QtGui.QVBoxLayout(self.toolspageSource)\n self.verticalLayout_4.setMargin(0)\n self.verticalLayout_4.setObjectName(_fromUtf8('verticalLayout_4'))\n self.sourceListEditor = SourceListEditor(self.toolspageSource)\n self.sourceListEditor.setObjectName(_fromUtf8('sourceListEditor'))\n self.verticalLayout_4.addWidget(self.sourceListEditor)\n self.stackEditTools.addWidget(self.toolspageSource)\n self.toolspageFilter = QtGui.QWidget()\n self.toolspageFilter.setObjectName(_fromUtf8('toolspageFilter'))\n self.verticalLayout_5 = QtGui.QVBoxLayout(self.toolspageFilter)\n self.verticalLayout_5.setMargin(0)\n self.verticalLayout_5.setObjectName(_fromUtf8('verticalLayout_5'))\n self.filterInstanceEditor = FilterInstanceEditor(self.toolspageFilter)\n self.filterInstanceEditor.setObjectName(_fromUtf8('filterInstanceEditor'))\n self.verticalLayout_5.addWidget(self.filterInstanceEditor)\n self.stackEditTools.addWidget(self.toolspageFilter)\n self.verticalLayout_2.addWidget(self.splitEditConfig)\n self.tabs.addTab(self.pageConfig, _fromUtf8(''))\n self.pageInfo = QtGui.QWidget()\n self.pageInfo.setObjectName(_fromUtf8('pageInfo'))\n self.verticalLayout = QtGui.QVBoxLayout(self.pageInfo)\n self.verticalLayout.setContentsMargins(0, 0, 0, 8)\n self.verticalLayout.setObjectName(_fromUtf8('verticalLayout'))\n self.txtInfo = QtGui.QTextBrowser(self.pageInfo)\n self.txtInfo.setTabChangesFocus(True)\n self.txtInfo.setOpenLinks(False)\n self.txtInfo.setObjectName(_fromUtf8('txtInfo'))\n self.verticalLayout.addWidget(self.txtInfo)\n self.tabs.addTab(self.pageInfo, _fromUtf8(''))\n self.pageBibEntries = QtGui.QWidget()\n self.pageBibEntries.setObjectName(_fromUtf8('pageBibEntries'))\n self.gridLayout_2 = QtGui.QGridLayout(self.pageBibEntries)\n self.gridLayout_2.setContentsMargins(0, 0, 0, 8)\n self.gridLayout_2.setObjectName(_fromUtf8('gridLayout_2'))\n self.txtBibEntries = QtGui.QTextBrowser(self.pageBibEntries)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8('Courier 10 Pitch'))\n self.txtBibEntries.setFont(font)\n self.txtBibEntries.setTabChangesFocus(True)\n self.txtBibEntries.setOpenLinks(False)\n self.txtBibEntries.setObjectName(_fromUtf8('txtBibEntries'))\n self.gridLayout_2.addWidget(self.txtBibEntries, 0, 0, 1, 1)\n self.tabs.addTab(self.pageBibEntries, _fromUtf8(''))\n self.pageLog = QtGui.QWidget()\n self.pageLog.setObjectName(_fromUtf8('pageLog'))\n self.gridLayout = QtGui.QGridLayout(self.pageLog)\n self.gridLayout.setContentsMargins(0, 0, 0, 8)\n self.gridLayout.setObjectName(_fromUtf8('gridLayout'))\n self.txtLog = QtGui.QTextBrowser(self.pageLog)\n self.txtLog.setTabChangesFocus(True)\n self.txtLog.setHtml(_fromUtf8('\\n\\n


'))\n self.txtLog.setAcceptRichText(False)\n self.txtLog.setOpenLinks(False)\n self.txtLog.setObjectName(_fromUtf8('txtLog'))\n self.gridLayout.addWidget(self.txtLog, 0, 0, 1, 2)\n self.lblVerbosity = QtGui.QLabel(self.pageLog)\n self.lblVerbosity.setObjectName(_fromUtf8('lblVerbosity'))\n self.gridLayout.addWidget(self.lblVerbosity, 1, 0, 1, 1)\n self.cbxVerbosity = QtGui.QComboBox(self.pageLog)\n self.cbxVerbosity.setObjectName(_fromUtf8('cbxVerbosity'))\n self.cbxVerbosity.addItem(_fromUtf8(''))\n self.cbxVerbosity.addItem(_fromUtf8(''))\n self.cbxVerbosity.addItem(_fromUtf8(''))\n self.cbxVerbosity.addItem(_fromUtf8(''))\n self.gridLayout.addWidget(self.cbxVerbosity, 1, 1, 1, 1)\n self.tabs.addTab(self.pageLog, _fromUtf8(''))\n self.lyt.addWidget(self.tabs, 2, 0, 1, 1)\n self.wHead = QtGui.QWidget(OpenBibFile)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.wHead.sizePolicy().hasHeightForWidth())\n self.wHead.setSizePolicy(sizePolicy)\n self.wHead.setObjectName(_fromUtf8('wHead'))\n self.horizontalLayout = QtGui.QHBoxLayout(self.wHead)\n self.horizontalLayout.setSpacing(3)\n self.horizontalLayout.setMargin(0)\n self.horizontalLayout.setObjectName(_fromUtf8('horizontalLayout'))\n self.lblFileName = QtGui.QLabel(self.wHead)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.lblFileName.sizePolicy().hasHeightForWidth())\n self.lblFileName.setSizePolicy(sizePolicy)\n self.lblFileName.setFrameShape(QtGui.QFrame.StyledPanel)\n self.lblFileName.setFrameShadow(QtGui.QFrame.Sunken)\n self.lblFileName.setMidLineWidth(1)\n self.lblFileName.setTextFormat(QtCore.Qt.PlainText)\n self.lblFileName.setAlignment(QtCore.Qt.AlignCenter)\n self.lblFileName.setObjectName(_fromUtf8('lblFileName'))\n self.horizontalLayout.addWidget(self.lblFileName)\n self.btnRefresh = QtGui.QToolButton(self.wHead)\n icon1 = QtGui.QIcon()\n icon1.addPixmap(QtGui.QPixmap(_fromUtf8(':/pic/refresh.png')), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.btnRefresh.setIcon(icon1)\n self.btnRefresh.setIconSize(QtCore.QSize(22, 22))\n self.btnRefresh.setObjectName(_fromUtf8('btnRefresh'))\n self.horizontalLayout.addWidget(self.btnRefresh)\n self.btnSave = QtGui.QToolButton(self.wHead)\n icon2 = QtGui.QIcon()\n icon2.addPixmap(QtGui.QPixmap(_fromUtf8(':/pic/save.png')), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.btnSave.setIcon(icon2)\n self.btnSave.setIconSize(QtCore.QSize(22, 22))\n self.btnSave.setObjectName(_fromUtf8('btnSave'))\n self.horizontalLayout.addWidget(self.btnSave)\n self.lyt.addWidget(self.wHead, 0, 0, 1, 1)\n self.retranslateUi(OpenBibFile)\n self.tabs.setCurrentIndex(0)\n self.stackEditTools.setCurrentIndex(0)\n self.cbxVerbosity.setCurrentIndex(1)\n QtCore.QMetaObject.connectSlotsByName(OpenBibFile)\n\n def retranslateUi(self, OpenBibFile):\n self.btnGo.setText(_translate('OpenBibFile', 'Run Bibolamazi !', None))\n self.btnAddSourceList.setText(_translate('OpenBibFile', 'add source list ...', None))\n self.btnAddFilter.setText(_translate('OpenBibFile', 'insert filter ...', None))\n self.tabs.setTabText(self.tabs.indexOf(self.pageConfig), _translate('OpenBibFile', 'Edit Bibolamazi Confguration', None))\n self.txtInfo.setHtml(_translate('OpenBibFile', '\\n\\n

<no file open>

', None))\n self.tabs.setTabText(self.tabs.indexOf(self.pageInfo), _translate('OpenBibFile', 'BIbolamazi File Info', None))\n self.tabs.setTabText(self.tabs.indexOf(self.pageBibEntries), _translate('OpenBibFile', 'Preview Bib Entries', None))\n self.lblVerbosity.setText(_translate('OpenBibFile', 'Log verbosity level (for next run):', None))\n self.cbxVerbosity.setItemText(0, _translate('OpenBibFile', 'Quiet', None))\n self.cbxVerbosity.setItemText(1, _translate('OpenBibFile', 'Information', None))\n self.cbxVerbosity.setItemText(2, _translate('OpenBibFile', 'Verbose', None))\n self.cbxVerbosity.setItemText(3, _translate('OpenBibFile', 'Very Verbose (for debugging)', None))\n self.tabs.setTabText(self.tabs.indexOf(self.pageLog), _translate('OpenBibFile', 'Messages', None))\n self.lblFileName.setText(_translate('OpenBibFile', 'some text here', None))\n return\n\n\nfrom ..filterinstanceeditor import FilterInstanceEditor\nfrom ..sourcelisteditor import SourceListEditor\nfrom . import bibolamazi_res_rc","sub_path":"pycfiles/bibolamazi_gui-3.0beta3-py2.7/ui_openbibfile.py","file_name":"ui_openbibfile.py","file_ext":"py","file_size_in_byte":13825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"616399902","text":"# Python bytecode 2.7 (decompiled from Python 2.7)\n# Embedded file name: e:\\jenkins\\workspace\\client_SERENITY\\branches\\release\\SERENITY\\packages\\trinutils\\driverutils.py\nimport trinity\n\nclass CannotIdentifyDriverException(Exception):\n\n def __init__(self, vendor, description='NA'):\n msg = str(\"Unable to retrieve info from %s card. Please ensure that you're using the right drivers or graphics card. /nDriver Description: %s\" % (vendor, description))\n super(Exception, self).__init__(self, msg)\n\n\ndef GetDriverVersion():\n adapter = trinity.adapters.GetAdapterInfo(trinity.adapters.DEFAULT_ADAPTER)\n if 'nvidia' not in adapter.description.lower():\n raise CannotIdentifyDriverException('Unknown', adapter.description)\n try:\n info = adapter.GetDriverInfo()\n except trinity.ALError:\n raise CannotIdentifyDriverException('NVidia', adapter.description)\n\n def getDriverVersionNumber(driverInfo):\n verInfo = driverInfo.driverVersionString.replace('.', '')\n return int(verInfo[-5:])\n\n return getDriverVersionNumber(info)","sub_path":"client/trinutils/driverutils.py","file_name":"driverutils.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"264178960","text":"from celery import shared_task\nfrom django.conf import settings\nfrom django.core.mail import send_mail\nfrom django.template.loader import render_to_string\nfrom django.utils.html import strip_tags\n\n\ndef enqueue_mail(recipient_list, subject, message=None, template='email/base.html', context={}, from_email=settings.DEFAULT_FROM_EMAIL):\n context.update({\n 'base_url' : settings.APP_URL,\n 'message' : message\n })\n html_message = render_to_string(template, context)\n if message is None:\n message = strip_tags(html_message).strip(' \\t\\n\\r')\n mail_task.delay(subject, message, recipient_list, html_message, from_email)\n\n\n@shared_task\ndef mail_task(subject, message, recipient_list, html_message=None, from_email=settings.DEFAULT_FROM_EMAIL):\n send_mail(subject, message, from_email, recipient_list, html_message)","sub_path":"app/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"210404821","text":"# Write an algorthm that picks between 3 colors pick, green and yellow randomly but the distribution is 0.25 pink 0.30 green and 0.45 yello\nfrom random import random\n\ncolors = [\"pink\", \"green\", \"yellow\", \"purple\"]\nprobabilities = [0.4, 0.1, 0.3, 0.2]\ntrials = 1000000\n\n\ndef non_uniform_random_picker(array, probabilities):\n rand_value = random()\n for i in range(len(array)):\n rand_value -= probabilities[i]\n if rand_value <= 0:\n return array[i]\n\n\nresults = dict()\n\nfor i in range(trials):\n value = non_uniform_random_picker(colors, probabilities)\n\n if results.get(value) == None:\n results[value] = 1\n else:\n results[value] += 1\n\n\nfor key in results:\n percentage = round(((results[key]/trials) * 100), 2)\n print(f\"{key}:{percentage}% \")\n","sub_path":"algorithms-step-by-step/numerical-algorithms/non-uniform-distr/non-uniform.py","file_name":"non-uniform.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"42532332","text":"import os\nos.chdir('F:\\GitHub-reuity\\Python\\PythonBase\\FileOps')\n\nfo = open(\"abc.csv\",\"r\",encoding=\"UTF-8-sig\") # sig删除文件开头\\ufeff\nls = []\nfor line in fo:\n line = line.replace(\"\\n\",\"\")\n ls = line.split(\",\")\n lns = \"\"\n for s in ls :\n lns += \"{}\\t\".format(s)\n print(lns)\nfo.close","sub_path":"PythonBase/FileOps/5.file_2d_format.py","file_name":"5.file_2d_format.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"76462747","text":"\ndef msg_processor(msg_code):\n '''\n msg_processor returns a msg object with 'msg', 'type'\n where 'msg' corresponds to the message user sees\n and 'type' is the color of the alert element\n\n codes:\n - 0 : Successfully added to database\n - 1 : User does not exist\n - 2 : Unable to retrieve tweets\n - 3 : Successfully deleted user\n '''\n\n msg_code = int(msg_code)\n\n msg_list = [\n (\n 'Successfully added to database',\n 'success'\n ),\n (\n 'User does not exist',\n 'warning'\n ),\n (\n 'Unable to retrieve tweets',\n 'warning'\n ),\n (\n 'Successfully deleted user',\n 'info'\n )\n ]\n\n return {\n 'msg':msg_list[msg_code][0],\n 'type':msg_list[msg_code][1]\n }\n","sub_path":"movie_app/utils/main_funcs.py","file_name":"main_funcs.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"128292424","text":"#!/usr/bin/python3\n# encoding: utf8\nprint ('')\n\nclass Animal(object):\n def run(self):\n print('Animal is running...')\n#当我们需要编写 Dog 和 Cat 类时,就可以直接从 Animal 类继承:\n#继承有什么好处?最大的好处是子类获得了父类的全部功能\nclass Dog0(Animal):\n pass\nclass Cat0(Animal):\n pass\n\ndog = Dog0()\ndog.run()\nprint(\"-----------------\")\ncat = Cat0()\ncat.run()\n\n'''\n继承的第二个好处需要我们对代码做一点改进。\n你看到了,无论是 Dog还是 Cat ,它们 run() 的时候,显示的都是 Animal is running... ,\n符合逻辑的做法是分别显示 Dog is running... 和 Cat is running... ,\n因此,对Dog 和 Cat 类改进如下:\n'''\n\n\nclass Dog(Animal):\n def run(self):\n print('Dog is running...')\nclass Cat(Animal):\n def run(self):\n print('Cat is running...')\n\nprint(\"-----------------\")\ndog = Dog()\ndog.run()\nprint(\"-----------------\")\ncat = Cat()\ncat.run()\n\n'''\n当子类和父类都存在相同的 run() 方法时,我们说,子类的 run() 覆盖了父类的 run() ,\n在代码运行的时候,总是会调用子类的 run() \n继承的另一个好处:多态\n'''\n\nprint (\"------------------------------\")\n\na = list() # a 是 list 类型\nb = Animal() # b 是 Animal 类型\nc = Dog() # c 是 Dog 类型\nprint (isinstance(a, list))\nprint (isinstance(b, Animal))\nprint (isinstance(c, Dog))\nprint (isinstance(c, Animal))#true\nprint (isinstance(c, object))#true\n\n'''\n要理解多态的好处,我们还需要再编写一个函数,这个函数接受一个Animal 类型的变量:\n\n当我们传入 Animal 的实例时, run_twice() 就打印出:\n'''\n#当我们传入 Animal 的实例时, run_twice() 就打印出:\ndef run_twice(animal):\n animal.run()\n animal.run()\n\nrun_twice(Animal())\n\n#当我们传入 Dog 的实例时, run_twice() 就打印出\nrun_twice(Dog())\n#当我们传入 Cat 的实例时, run_twice() 就打印出\nrun_twice(Cat())\n\n'''\n如果我们再定义一个 Tortoise类型,也从 Animal 派生:\n'''\nclass Tortoise(Animal):\n def run(self):\n print('Tortoise is running slowly...')\n\n\nrun_twice(Tortoise())\n'''\n新增一个 Animal 的子类,不必对 run_twice() 做任何修改,\n实际上,任何依赖 Animal 作为参数的函数或者方法都可以不加修改地正常运行,原因就在于多态\n\n对于一个变量,我们只需要知道它是 Animal 类型,无需确切地知道它的子类型,\n就可以放心地调用 run() 方法,而具体调用的 run() 方法是作用在 Animal 、 \nDog 、 Cat 还是 Tortoise 对象上,由运行时该对象的确切类型决定,\n这就是多态真正的威力:调用方只管调用,不管细节,而当我们新增一种 Animal 的子类时,\n只要确保 run() 方法编写正确,不用管原来的代码是如何调用的。这就是著名的“开闭”原则:\n 对扩展开放:允许新增 Animal 子类;\n 对修改封闭:不需要修改依赖 Animal 类型的 run_twice() 等函数。\n\n'''\n\n'''\n对于静态语言(例如 Java)来说,如果需要传入 Animal 类型,则传入的对象必须是 Animal 类型\n或者它的子类,否则,将无法调用 run() 方法。\n对于 Python 这样的动态语言来说,则不一定需要传入 Animal 类型。我们只需要保证传入的对象有一个 run() 方法就可以了:\nclass Timer(object):\n def run(self):\n print('Start...')\n这就是动态语言的“鸭子类型”,它并不要求严格的继承体系,一个对象只要“看起来像鸭子,走起路来像鸭子”,那它就可以被看做是鸭子。\nPython 的“file-like object“就是一种鸭子类型。对真正的文件对象,它有一个 read() 方法,返回其内容。\n但是,许多对象,只要有 read() 方法,都被视为“file-like object“。\n许多函数接收的参数就是“file-like object“,你不一定要传入真正的文件对象,完全可以传入任何实��了 read() 方法的对象。\n'''\nclass Timer(object):\n def run(self):\n print('Start...')\n\nrun_twice(Timer())\n\n\n\n\n\n\n\n","sub_path":"4-day/7-inherit.py","file_name":"7-inherit.py","file_ext":"py","file_size_in_byte":4135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"576150877","text":"import cv2\r\nimport numpy\r\n\r\nimport cv2\r\nimport numpy as np\r\n\r\n# opencv loads the image in BGR, convert it to RGB\r\nimg = cv2.cvtColor(cv2.imread('images\\imageToSave.jpg'),\r\n cv2.COLOR_BGR2RGB)\r\nlower_white = np.array([220, 220, 220], dtype=np.uint8)\r\nupper_white = np.array([255, 255, 255], dtype=np.uint8)\r\nmask = cv2.inRange(img, lower_white, upper_white) # could also use threshold\r\nmask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))) # \"erase\" the small white points in the resulting mask\r\nmask = cv2.bitwise_not(mask) # invert mask\r\n\r\n# load background (could be an image too)\r\nbk = np.full(img.shape, 255, dtype=np.uint8) # white bk\r\n\r\n# get masked foreground\r\nfg_masked = cv2.bitwise_and(img, img, mask=mask)\r\n\r\n# get masked background, mask must be inverted\r\nmask = cv2.bitwise_not(mask)\r\nbk_masked = cv2.bitwise_and(bk, bk, mask=mask)\r\n\r\n# combine masked foreground and masked background\r\nfinal = cv2.bitwise_or(fg_masked, bk_masked)\r\nmask = cv2.bitwise_not(mask) # revert mask to original\r\n\r\ncv2.imshow(\"mask\",final)\r\n\r\ncv2.waitKey(0)\r\ncv2.imwrite(\"images/vishal.jpg\",final)","sub_path":"imgprocess.py","file_name":"imgprocess.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"328131515","text":"# Import required modules\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom random import random, randint\nfrom collections import Counter, namedtuple, deque\nfrom math import hypot\nfrom abc import ABC, abstractmethod\nfrom vector import Vector\n \nEntities = namedtuple(\"Entities\", [\"population\", \"food\"])\n\ndef trial(chance):\n \"\"\" Returns the boolean outcome of a trial given it's chance of success.\"\"\"\n return random() <= chance\n\ndef distance(source, other):\n \"\"\" Returns the distance between two Entity objects.\"\"\"\n dx = source.x - other.x\n dy = source.y - other.y\n return hypot(dx, dy)\n\ndef collision(source, target):\n \"\"\" Detect whether two round objects are touching.\"\"\"\n if distance(source, target) <= source.radius + target.radius:\n return True\n return False\n\ndef resolve_collision(source, target):\n \"\"\" Test\n \"\"\"\n source.motion, target.motion = target.motion, source.motion\n\n\nclass Extent():\n \"\"\" The rectangular extent of a habitat\"\"\"\n\n def __init__(self, width, height):\n self.width = width\n self.height = height\n \n def contains(self, entity):\n \"\"\" Check whether entity is contained completely within bounds of extent\"\"\"\n return (entity.x <= (self.width - entity.radius) and\n entity.x >= (0 + entity.radius) and\n entity.y <= (self.height - entity.radius) and\n entity.y >= (0 + entity.radius))\n\n\nclass Entity(ABC):\n \"\"\" Abstract base class for entities. An entity is any interactable object in \n the Environment that has location (x, y) and radius.\n \"\"\"\n\n def __init__(self, x, y, radius):\n self.x = x\n self.y = y\n self.radius = radius\n self.patch = plt.Circle((x, y), radius) # matplotlib patch\n \n def __iadd__(self, vector):\n \"\"\" Update the location of self by Vector .\"\"\"\n self.x = self.x + vector.vx\n self.y = self.y + vector.vy\n return self\n \n @staticmethod\n @abstractmethod\n def spawn(extent):\n \"\"\" Every child of Entity must have a static spawn method.\"\"\"\n pass\n\n\nclass Organism(Entity):\n \"\"\" The Organism object represents a live entity.\n\n Parameters:\n x (int or float): x location of Organism.\n y (int or float): y location of Organism.\n radius (float): the radius of the Organism.\n motion (Vector): the speed and direction of Organism.\n Attributes:\n period (int): the current age of Organism.\n energy (int or float): the amount of energy stored by Organism. \n patch (matplotlib.patches.Circle): patch for visualization on plot.\n \"\"\"\n \n def __init__(self, x, y, radius = .25, motion = Vector(0, 0)):\n super().__init__(x, y, radius)\n self.motion = motion\n self.energy = 2\n self.period = 0\n\n def __str__(self):\n return f\"Organism < age: {self.period!r}, location({self.x!r}, {self.y!r})>\"\n \n def __repr__(self):\n return f\"{self.period!r}\"\n \n def __call__(self):\n \"\"\" advance the entity by one period.\"\"\"\n self += self.motion\n self.period += 1\n self.patch.center = (self.x, self.y)\n return self\n\n @staticmethod\n def spawn(extent):\n return Organism(\n x=random() * extent.width,\n y=random() * extent.height,\n motion=Vector.generate(0.2)\n )\n\n\nclass Food(Entity):\n \"\"\" The Food object provides energy for a live\n entity. This food object is stationary.\n\n Parameters:\n x (int or float): x location of Food.\n y (int or float): y location of Food.\n energy (float): The energy value of Food.\n Attributes:\n patch (matplotlib.patches.Circle): patch for visualization on plot.\n \"\"\"\n\n def __init__(self, x, y, radius = .1, energy = 1):\n super().__init__(x, y, radius)\n self.energy = energy\n self.patch.set_color(\"green\")\n \n def __repr__(self):\n return f\"Food \"\n\n @staticmethod\n def spawn(extent):\n return Food(\n x=random() * extent.width,\n y=random() * extent.height\n )\n\n\nclass Environment():\n \"\"\" The environment tracks the population and parameters of the simulation.\n\n Parameters:\n repro_chance (float): Chance of reproduction\n death_chance (float): Chance of death\n starting_pop (int): Starting population\n extent (iterable [width, height]): Extent of habitat\n \n TODO: Explain remaining attributes once fully established.\n \"\"\"\n\n def __init__(self, repro_chance, death_chance, starting_pop, starting_food, food_rate, extent):\n # Simulation arguments\n self.repro_chance = repro_chance\n self.death_chance = death_chance\n self.starting_pop = starting_pop\n self.starting_food = starting_food\n self.food_rate = food_rate\n self.extent = Extent(*extent)\n # Hard simluation parameters\n self.period_length = 25\n # Simulation data\n self.ents = Entities(population=[], food=[]) #Currently existing entities\n for i in range(0, self.starting_pop):\n self.ents.population.append(self.spawn(Organism))\n for i in range(0, self.starting_food):\n self.ents.food.append(self.spawn(Food))\n self.history = [starting_pop]\n self.mortuary = Counter()\n # Plot attributes\n self._fig, self._ax = plt.subplots(1, 1)\n self._ax.set_xlim(0, self.extent.width) #Set habitat plane x size\n self._ax.set_ylim(0, self.extent.height) #Set habitat plane y size\n self._ax.set_aspect('equal') #Make sure x and y scales equal\n\n def __repr__(self):\n return f\"Environment \"\n\n def __call__(self):\n \"\"\" Advance the simulation by one frame.\"\"\"\n # Simulate period\n # survive, expire, births = [], [], []\n\n # Update organism motion\n queue = deque(self.ents.population)\n while len(queue) > 0:\n # Organism collides with extent boundary\n organism = queue.pop()\n if (organism.x >= (self.extent.width - organism.radius) or \n organism.x <= (0 + organism.radius)\n ):\n organism.motion.vx = -organism.motion.vx\n if (organism.y >= (self.extent.height - organism.radius) or \n organism.y <= (0 + organism.radius)\n ):\n organism.motion.vy = -organism.motion.vy\n # organism collides with other organsim\n targets = (target for\n target in\n queue if\n target is not organism and collision(organism, target)\n )\n for target in targets:\n resolve_collision(organism, target)\n # Update organism position\n organism()\n\n \n # # Finally, update attributes\n # self.ents.population = survive + births\n # self.mortuary.update(expire)\n # self.history.append(len(self.population))\n\n def fig_init(self):\n for group in self.ents:\n for ent in group:\n self._ax.add_patch(ent.patch)\n \n def fig_animate(self, frame):\n self() #Advance simulation by one frame\n\n def run(self, n_period):\n return animation.FuncAnimation(self._fig,\n self.fig_animate,\n init_func=self.fig_init,\n frames=n_period)\n\n\n ##TODO\n ##PSEUDOCODE##\n \"\"\" \n for each iteration in range(0, n_iterations): #how many iterations to simulate total \n for each interval range(0, interval_size):\n for each cell in population:\n Cell moves and gathers food\n if cell energy <= 0:\n cell stops moving\n Update graphic\n -Evaluate cell success after interval-\n for each cell in population:\n if cell energy <= 0:\n remove cell from population and add to mortuary\n if cell energy >= repro_energy_requirement:\n add new cell to population, offset from original cell\n \n Update population line graph\n Update popualtion expiration histogram\n \"\"\"\n\n def spawn(self, entity):\n while True:\n ent = entity.spawn(self.extent)\n # Must spawn inside of habitat and must not overlap with others\n if self.extent.contains(ent):\n if not any(collision(ent, target) for group in self.ents \n for target in group):\n return ent \n \n","sub_path":"Section_3/simpop.py","file_name":"simpop.py","file_ext":"py","file_size_in_byte":9388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"605743155","text":"# -*- coding: UTF-8 -*-\n\nfrom hashlib import sha1\nfrom time import time\nfrom wx_pay import WxPay, WxPayError\n\napi_cert_path = \"/home/ubuntu/pem/apiclient_cert.pem\"\napi_key_path = \"/home/ubuntu/pem/apiclient_key.pem\"\n \ndef send_red_pack(openid,amount):\n \"\"\"\n 向个人用户发红包example\n \"\"\"\n data={'send_name':u'禾梓先生',\n 're_openid':openid,\n 'total_amount':amount,\n 'wishing':u'感谢使用本平台',\n 'client_ip':u'139.199.96.148',\n 'act_name':u'提现',\n 'remark':u'请12小时内领取红包'}\n wx_pay = WxPay(\n wx_app_id='wx61e83ce648e7b691',\n wx_mch_id='1507994731',\n wx_mch_key='b8uww0npq5b53m1bqfv6c4wi8kln4giv',\n wx_notify_url='http://www.example.com/pay/weixin/notify'\n )\n '''\n raw = wx_pay.send_red_pack(\n # 证书获取方法请阅读:https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=4_3\n # api_cert_path: 微信支付商户证书(apiclient_cert.pem)的本地保存路径\n api_cert_path='/home/ubuntu/pem/apiclient_cert.pem',\n # api_cert_path: 微信支付商户证书(apiclient_key.pem)的本地保存路径\n api_key_path='/home/ubuntu/pem/apiclient_key.pem',\n send_name=u'红包测试', # 红包名称\n re_openid=u'ot0Np01VZKOO3fz6ki6BA0VPCupc', # 要接收红包的用户openid\n total_amount=100, # total_fee 单位是 分, 100 = 1元, 最大499元\n wishing=u'***感谢参与测试***', # 祝福语\n client_ip=u'139.199.96.148', # 调用微信发红包接口服务器公网IP地址\n act_name=u'***微信支付测试系统***', # 活动名称\n remark=u'***感谢参与***' # 备注\n )\n '''\n raw = wx_pay.send_red_pack(api_cert_path,api_key_path,**data)\n print (WxPay.to_utf8(raw)) \n \nif __name__ == '__main__':\n print(requets.post('http://work-flow.cn:8964/pay_cash',{'open_id':'ot0Np0wsM94zW5wa83HpEZhletIM',money:100}).text)\n #send_red_pack('ot0Np05y9oxcc6Yavz0-zrOxIgrg',100)\n #send_red_pack('oWN6I06odGU-NfKEm97hQhuMjuNk',100)\n","sub_path":"util/pay_util.py","file_name":"pay_util.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"282928286","text":"import torch\nimport torch.nn as nn\n\n\nclass SimpleNet(nn.Module):\n \"\"\"Simple Network with atleast 2 conv2d layers and two linear layers.\"\"\"\n\n def __init__(self):\n \"\"\"\n Init function to define the layers and loss function\n\n Note: Use 'sum' reduction in the loss_criterion. Read Pytorch documention to understand what it means\n\n Hints:\n 1. Refer to https://pytorch.org/docs/stable/nn.html for layers\n 2. Remember to use non-linearities in your network. Network without\n non-linearities is not deep.\n 3. You will get 4D tensor for an image input from self.conv_layers. You need \n to process it and make it a compatible tensor input for self.fc_layers.\n \"\"\"\n super().__init__()\n\n self.conv_layers = nn.Sequential() # conv2d and supporting layers here\n self.fc_layers = nn.Sequential() # linear and supporting layers here\n self.loss_criterion = None\n\n ############################################################################\n # Student code begin\n ###########################################################################\n # initialie self.conv_layers\n self.loss_criterion = nn.CrossEntropyLoss(reduction = 'sum')\n self.conv_layers = nn.Sequential(\n nn.Conv2d(in_channels=1, out_channels=10, kernel_size=5, bias=False),\n nn.MaxPool2d(kernel_size=3, stride=3),\n nn.ReLU(),\n nn.Conv2d(in_channels=10, out_channels=20, kernel_size=5, bias=False),\n nn.MaxPool2d(kernel_size=3, stride=3),\n nn.ReLU()\n )\n self.fc_layers = nn.Sequential(\n nn.Flatten(),\n nn.Linear(500, 100),\n nn.Linear(100, 15),\n )\n\n ############################################################################\n # Student code end\n ############################################################################\n\n def forward(self, x: torch.tensor) -> torch.tensor:\n \"\"\"\n Perform the forward pass with the net\n\n Note: do not perform soft-max or convert to probabilities in this function\n\n Args:\n - x: the input image [Dim: (N,C,H,W)]\n Returns:\n - y: the output (raw scores) of the net [Dim: (N,15)]\n \"\"\"\n conv_features = None # output of x passed through convolution layers (4D tensor)\n flattened_conv_features = None # conv_features reshaped into 2D tensor using .reshape()\n model_output = None # output of flattened_conv_features passed through fully connected layers\n ############################################################################\n # Student code begin\n ############################################################################\n conv_out = self.conv_layers(x)\n model_output = self.fc_layers(conv_out)\n ############################################################################\n # Student code end\n ############################################################################\n\n return model_output\n","sub_path":"PS6_v1/proj6_code/simple_net.py","file_name":"simple_net.py","file_ext":"py","file_size_in_byte":3115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"106286191","text":"from __future__ import division, absolute_import, print_function\n\ntry:\n import unzip_requirements\nexcept ImportError:\n pass\n\"\"\"This submodule contains tools for creating svg files from paths and path\nsegments.\"\"\"\n\n# External dependencies:\nfrom math import ceil\nfrom custom_drawing import Drawing\nfrom svgwrite import text as txt\nfrom warnings import warn\nfrom colors import DEFAULT_COLORS\n\n# Internal dependencies\nfrom svgpathtools import Path, Line, is_path_segment\n\n# Used to convert a string colors (identified by single chars) to a list.\ncolor_dict = {'a': 'aqua',\n 'b': 'blue',\n 'c': 'cyan',\n 'd': 'darkblue',\n 'e': '',\n 'f': '',\n 'g': 'green',\n 'h': '',\n 'i': '',\n 'j': '',\n 'k': 'black',\n 'l': 'lime',\n 'm': 'magenta',\n 'n': 'brown',\n 'o': 'orange',\n 'p': 'pink',\n 'q': 'turquoise',\n 'r': 'red',\n 's': 'salmon',\n 't': 'tan',\n 'u': 'purple',\n 'v': 'violet',\n 'w': 'white',\n 'x': '',\n 'y': 'yellow',\n 'z': 'azure'}\n\n\ndef str2colorlist(s, default_color=None):\n color_list = [color_dict[ch] for ch in s]\n if default_color:\n for idx, c in enumerate(color_list):\n if not c:\n color_list[idx] = default_color\n return color_list\n\n\ndef is3tuple(c):\n return isinstance(c, tuple) and len(c) == 3\n\n\ndef big_bounding_box(paths_n_stuff):\n \"\"\"Finds a BB containing a collection of paths, Bezier path segments, and\n points (given as complex numbers).\"\"\"\n bbs = []\n for thing in paths_n_stuff:\n if is_path_segment(thing) or isinstance(thing, Path):\n bbs.append(thing.bbox())\n elif isinstance(thing, complex):\n bbs.append((thing.real, thing.real, thing.imag, thing.imag))\n else:\n try:\n complexthing = complex(thing)\n bbs.append((complexthing.real, complexthing.real,\n complexthing.imag, complexthing.imag))\n except ValueError:\n raise TypeError(\n \"paths_n_stuff can only contains Path, CubicBezier, \"\n \"QuadraticBezier, Line, and complex objects.\")\n xmins, xmaxs, ymins, ymaxs = list(zip(*bbs))\n xmin = min(xmins)\n xmax = max(xmaxs)\n ymin = min(ymins)\n ymax = max(ymaxs)\n return xmin, xmax, ymin, ymax\n\n\ndef davis_disvg(paths=None, colors=None, stroke_widths=None, nodes=None,\n node_colors=None, node_radii=None, margin_size=0.1,\n mindim=2000, dimensions=None, viewbox=None,\n text=None, text_path=None, font_size=None,\n attributes=None, svg_attributes=None, checksum=None, bg_color=DEFAULT_COLORS['bg_color']):\n \"\"\"Takes in a list of paths and creates an SVG file containing said paths.\n REQUIRED INPUTS:\n :param paths - a list of paths\n\n OPTIONAL INPUT:\n :param colors - specifies the path stroke color. By default all paths\n will be black (#000000). This paramater can be input in a few ways\n 1) a list of strings that will be input into the path elements stroke\n attribute (so anything that is understood by the svg viewer).\n 2) a string of single character colors -- e.g. setting colors='rrr' is\n equivalent to setting colors=['red', 'red', 'red'] (see the\n 'color_dict' dictionary above for a list of possibilities).\n 3) a list of rgb 3-tuples -- e.g. colors = [(255, 0, 0), ...].\n\n :param stroke_widths - a list of stroke_widths to use for paths\n (default is 0.5% of the SVG's width or length)\n\n :param nodes - a list of points to draw as filled-in circles\n\n :param node_colors - a list of colors to use for the nodes (by default\n nodes will be red)\n\n :param node_radii - a list of radii to use for the nodes (by default\n nodes will be radius will be 1 percent of the svg's width/length)\n\n :param text - string or list of strings to be displayed\n\n :param text_path - if text is a list, then this should be a list of\n path (or path segments of the same length. Note: the path must be\n long enough to display the text or the text will be cropped by the svg\n viewer.\n\n :param font_size - a single float of list of floats.\n\n :param margin_size - The min margin (empty area framing the collection\n of paths) size used for creating the canvas and background of the SVG.\n\n :param mindim - The minimum dimension (height or width) of the output\n SVG (default is 600).\n\n :param dimensions - The display dimensions of the output SVG. Using\n this will override the mindim parameter.\n\n :param viewbox - This specifies what rectangular patch of R^2 will be\n viewable through the outputSVG. It should be input in the form\n (min_x, min_y, width, height). This is different from the display\n dimension of the svg, which can be set through mindim or dimensions.\n\n :param attributes - a list of dictionaries of attributes for the input\n paths. Note: This will override any other conflicting settings.\n\n :param svg_attributes - a dictionary of attributes for output svg.\n Note 1: This will override any other conflicting settings.\n Note 2: Setting `svg_attributes={'debug': False}` may result in a\n significant increase in speed.\n\n :param checksum - a string to be used for the filename, or None\n If None, a checksum will be generated here\n\n :param bg_color - a hex code applied to the SVG. Defaults to white (#FFF)\n\n NOTES:\n -The unit of length here is assumed to be pixels in all variables.\n\n -If this function is used multiple times in quick succession to\n display multiple SVGs (all using the default filename), the\n svgviewer/browser will likely fail to load some of the SVGs in time.\n To fix this, use the timestamp attribute, or give the files unique\n names, or use a pause command (e.g. time.sleep(1)) between uses.\n \"\"\"\n\n try:\n _default_relative_node_radius = 5e-3\n _default_relative_stroke_width = 1e-3\n _default_path_color = DEFAULT_COLORS['color'] # black\n _default_node_color = DEFAULT_COLORS['node_colors'] # red\n _default_font_size = 12\n\n # check paths and colors are set\n if isinstance(paths, Path) or is_path_segment(paths):\n paths = [paths]\n if paths:\n if not colors:\n colors = [_default_path_color] * len(paths)\n else:\n assert len(colors) == len(paths)\n if isinstance(colors, str):\n colors = str2colorlist(colors,\n default_color=_default_path_color)\n elif isinstance(colors, list):\n for idx, c in enumerate(colors):\n if is3tuple(c):\n colors[idx] = \"rgb\" + str(c)\n\n # check nodes and nodes_colors are set (node_radii are set later)\n if nodes:\n if not node_colors:\n node_colors = [_default_node_color] * len(nodes)\n else:\n assert len(node_colors) == len(nodes)\n if isinstance(node_colors, str):\n node_colors = str2colorlist(node_colors,\n default_color=_default_node_color)\n elif isinstance(node_colors, list):\n for idx, c in enumerate(node_colors):\n if is3tuple(c):\n node_colors[idx] = \"rgb\" + str(c)\n\n # set up the viewBox and display dimensions of the output SVG\n # along the way, set stroke_widths and node_radii if not provided\n assert paths or nodes\n stuff2bound = []\n if viewbox:\n szx, szy = viewbox[2:4]\n else:\n if paths:\n stuff2bound += paths\n if nodes:\n stuff2bound += nodes\n if text_path:\n stuff2bound += text_path\n xmin, xmax, ymin, ymax = big_bounding_box(stuff2bound)\n dx = xmax - xmin\n dy = ymax - ymin\n\n if dx == 0:\n dx = 1\n if dy == 0:\n dy = 1\n\n # determine stroke_widths to use (if not provided) and max_stroke_width\n if paths:\n if not stroke_widths:\n sw = max(dx, dy) * _default_relative_stroke_width\n stroke_widths = [sw] * len(paths)\n max_stroke_width = sw\n else:\n assert len(paths) == len(stroke_widths)\n max_stroke_width = max(stroke_widths)\n else:\n max_stroke_width = 0\n\n # determine node_radii to use (if not provided) and max_node_diameter\n if nodes:\n if not node_radii:\n r = max(dx, dy) * _default_relative_node_radius\n node_radii = [r] * len(nodes)\n max_node_diameter = 2 * r\n else:\n assert len(nodes) == len(node_radii)\n max_node_diameter = 2 * max(node_radii)\n else:\n max_node_diameter = 0\n\n extra_space_for_style = max(max_stroke_width, max_node_diameter)\n xmin -= margin_size * dx + extra_space_for_style / 2\n ymin -= margin_size * dy + extra_space_for_style / 2\n dx += 2 * margin_size * dx + extra_space_for_style\n dy += 2 * margin_size * dy + extra_space_for_style\n viewbox = \"%s %s %s %s\" % (xmin, ymin, dx, dy)\n if dimensions:\n szx, szy = dimensions\n else:\n if dx > dy:\n szx = str(mindim) + 'px'\n szy = str(int(ceil(mindim * dy / dx))) + 'px'\n else:\n szx = str(int(ceil(mindim * dx / dy))) + 'px'\n szy = str(mindim) + 'px'\n\n # Create an SVG file\n if svg_attributes:\n dwg = Drawing(filename='no_name.svg', bg_color=bg_color, **svg_attributes)\n else:\n dwg = Drawing(filename='no_name.svg', size=(szx, szy), bg_color=bg_color, viewBox=viewbox)\n\n # add paths\n if paths:\n for i, p in enumerate(paths):\n if isinstance(p, Path):\n ps = p.d()\n elif is_path_segment(p):\n ps = Path(p).d()\n else: # assume this path, p, was input as a Path d-string\n ps = p\n\n if attributes:\n good_attribs = {'d': ps}\n for key in attributes[i]:\n val = attributes[i][key]\n if key != 'd':\n try:\n dwg.path(ps, **{key: val})\n good_attribs.update({key: val})\n except Exception as e:\n warn(str(e))\n\n dwg.add(dwg.path(**good_attribs))\n else:\n dwg.add(dwg.path(ps, stroke=colors[i],\n stroke_width=str(stroke_widths[i]),\n fill='none'))\n\n # add nodes (filled in circles)\n if nodes:\n for i_pt, pt in enumerate([(z.real, z.imag) for z in nodes]):\n dwg.add(dwg.circle(pt, node_radii[i_pt], fill=node_colors[i_pt]))\n\n # add texts\n if text:\n assert isinstance(text, str) or (isinstance(text, list) and\n isinstance(text_path, list) and\n len(text_path) == len(text))\n if isinstance(text, str):\n text = [text]\n if not font_size:\n font_size = [_default_font_size]\n if not text_path:\n pos = complex(xmin + margin_size * dx, ymin + margin_size * dy)\n text_path = [Line(pos, pos + 1).d()]\n else:\n if font_size:\n if isinstance(font_size, list):\n assert len(font_size) == len(text)\n else:\n font_size = [font_size] * len(text)\n else:\n font_size = [_default_font_size] * len(text)\n for idx, s in enumerate(text):\n p = text_path[idx]\n if isinstance(p, Path):\n ps = p.d()\n elif is_path_segment(p):\n ps = Path(p).d()\n else: # assume this path, p, was input as a Path d-string\n ps = p\n\n # paragraph = dwg.add(dwg.g(font_size=font_size[idx]))\n # paragraph.add(dwg.textPath(ps, s))\n pathid = 'tp' + str(idx)\n dwg.defs.add(dwg.path(d=ps, id=pathid))\n txter = dwg.add(dwg.text('', font_size=font_size[idx]))\n txter.add(txt.TextPath('#' + pathid, s))\n\n return dwg.save_to_s3(checksum=checksum)\n except Exception as e:\n raise e\n","sub_path":"custom_svg.py","file_name":"custom_svg.py","file_ext":"py","file_size_in_byte":13565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"222239219","text":"# -*- coding: utf-8 -*-\r\n\r\nimport pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LinearRegression\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.externals import joblib\r\nfrom sys import argv\r\n\r\n# 使用的特征列\r\nFEAT_COLS = []\r\n# 结果列\r\nRESULTCOL = []\r\n#资源文件\r\nRES_PATH = \"\"\r\n#模型文件\r\nMODEL_FILE = \"\"\r\n\r\n\"\"\"\r\n----------------------------------------\r\n-------通用逻辑回归算法-----------------\r\n- 参数要求:\r\n- 1:参数1为待分析资源文件路径(csv文件)\r\n- 2:参数2为模型文件存放位置\r\n- 3:参数3为文件资源的头部标题\r\n- 4:\r\n----------------------------------------\r\n\"\"\"\r\n\r\n\r\n\r\ndef build_param():\r\n \"\"\"\r\n 构建参数\r\n \"\"\"\r\n global RES_PATH\r\n #读取列信息\r\n global MODEL_FILE\r\n global FEAT_COLS\r\n global RESULTCOL\r\n RES_PATH = argv[1]\r\n MODEL_FILE = argv[2]\r\n heads=argv[3]\r\n FEAT_COLS = heads.split(',')\r\n RESULTCOL = FEAT_COLS[-1] \r\n del FEAT_COLS[-1]\r\n #print(\"RES_PATH:\",RES_PATH)\r\n #print(\"MODEL_FILE:\",MODEL_FILE)\r\n print(\"特征数据列:\",FEAT_COLS)\r\n print(\"结果列:\",RESULTCOL)\r\n\r\ndef show_feat(csv_data):\r\n \"\"\"\r\n 特征列和结果列的关系\r\n \"\"\"\r\n for feat in FEAT_COLS:\r\n X = csv_data[feat].values.reshape(-1, 1)\r\n y = csv_data[RESULTCOL].values\r\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1 / 3, random_state=10)\r\n linear_reg_model = LinearRegression()\r\n linear_reg_model.fit(X_train, y_train)\r\n r2_score = linear_reg_model.score(X_test, y_test)\r\n print('特征:{},R2值:{}'.format(feat, r2_score))\r\n\r\n\r\ndef main():\r\n \"\"\"\r\n 主函数\r\n \"\"\"\r\n #待生成的训练模型\r\n csv_data = pd.read_csv(RES_PATH, usecols=FEAT_COLS + [RESULTCOL])\r\n show_feat(csv_data)\r\n X = csv_data[FEAT_COLS].values\r\n y = csv_data[RESULTCOL].values\r\n\r\n # 分割数据集\r\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1 / 3, random_state=10)\r\n\r\n # 建立线性回归模型\r\n linear_reg_model = LinearRegression()\r\n \r\n # 模型训练\r\n linear_reg_model.fit(X_train, y_train) \r\n joblib.dump(linear_reg_model, MODEL_FILE)\r\n \r\n score = linear_reg_model.score(X_test, y_test)\r\n print('模型的R2值', score)\r\n \r\n i = 0\r\n # 第i行所有列(即一条数据的特征数据)\r\n single_test_feat = X_test[i, :]\r\n y_true = y_test[i]\r\n y_pred = linear_reg_model.predict([single_test_feat])\r\n print('样本特征:', single_test_feat)\r\n print('真实结果数据:{},预测结果数据:{}'.format(y_true, y_pred))\r\n print(FEAT_COLS,\"拟合函数对应权重如下依次对应,截距为最后一行参数:\")\r\n print(linear_reg_model.coef_) \r\n print(linear_reg_model.intercept_)\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n build_param()\r\n main()\r\n\r\n\r\n","sub_path":"WebRoot/WEB-INF/classes/py/custom_build_model.py","file_name":"custom_build_model.py","file_ext":"py","file_size_in_byte":2960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"257480090","text":"import os\nimport tempfile\nimport pytest\nfrom ccc.parameters import Specification, revision_warnings_errors\n\n\ndef test_create_specification_object():\n spec = Specification()\n assert spec\n\n\ndef test_update_specification_with_dict():\n cyr = 2020\n spec = Specification(year=cyr)\n new_spec_dict = {\n 'profit_rate': 0.4,\n 'm': 0.5\n }\n spec.update_specification(new_spec_dict)\n assert spec.profit_rate == 0.4\n assert spec.m == 0.5\n assert len(spec.errors) == 0\n\n\ndef test_update_specification_with_json():\n cyr = 2020\n spec = Specification(year=cyr)\n new_spec_json = \"\"\"\n {\n \"profit_rate\": [\n {\n \"year\": 2020,\n \"value\": 0.4\n }\n ],\n \"m\": [\n {\n \"year\": 2020,\n \"value\": 0.5\n }\n ]\n }\n \"\"\"\n spec.update_specification(new_spec_json)\n assert spec.profit_rate == 0.4\n assert spec.m == 0.5\n assert len(spec.errors) == 0\n\n\ndef test_update_bad_revision1():\n spec = Specification()\n # profit rate has an upper bound at 1.0\n revs = {\n 'profit_rate': [{'year': spec.year, 'value': 1.2}]\n }\n spec.update_specification(revs, raise_errors=False)\n assert len(spec.errors) > 0\n first_line = spec.errors['profit_rate'][0]\n print(first_line)\n expected_first_line =\\\n 'profit_rate[year=2019] 1.2 > max 1.0 '\n assert first_line == expected_first_line\n\n\ndef test_update_bad_revsions2():\n spec = Specification()\n # Pick a category for depreciation that is out of bounds\n revs = {\n 'profit_rate': 0.5,\n 'DeprecSystem_3yr': 'not_a_deprec_system'}\n spec.update_specification(revs, raise_errors=False)\n assert len(spec.errors) > 0\n first_line = spec.errors['DeprecSystem_3yr'][0]\n print('First line = ', first_line)\n expected_first_line = (\n 'DeprecSystem_3yr \"not_a_deprec_system\" must be in list of '\n 'choices GDS, ADS, Economic.'\n )\n assert first_line == expected_first_line\n\n\ndef test_revision_warnings_errors():\n revs_dict_good = {'profit_rate': [{'year': 2020, 'value': 0.30}]}\n e_w = revision_warnings_errors(revs_dict_good)\n assert len(e_w['warnings']) == 0\n assert len(e_w['errors']) == 0\n revs_dict_bad = {'profit_rate': [{'year': 2020, 'value': -0.10}]}\n e_w = revision_warnings_errors(revs_dict_bad)\n assert len(e_w['warnings']) == 0\n assert len(e_w['errors']) > 0\n","sub_path":"ccc/tests/test_parameters.py","file_name":"test_parameters.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"420484194","text":"from attention import AttentionLayer\r\nfrom keras.preprocessing.text import Tokenizer \r\nfrom keras.preprocessing.sequence import pad_sequences\r\nfrom keras import backend as K\r\nfrom tensorflow.keras.layers import Input, LSTM, Embedding, Dense, Concatenate, TimeDistributed\r\nfrom tensorflow.keras.models import Model\r\nfrom tensorflow.keras.callbacks import EarlyStopping\r\nfrom preprocessing import text_cleaner, convertSequence, getData\r\nimport numpy as np\r\nimport pandas as pd\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\n#load data\r\nx_tr,x_val,y_tr,y_val = getData()\r\nmax_text_len=30\r\nmax_summary_len=10\r\n#prepare a tokenizer for reviews on training data\r\nx_tokenizer = Tokenizer() \r\nx_tokenizer.fit_on_texts(list(x_tr))\r\nthresh=4\r\ncnt=0\r\ntot_cnt=0\r\nfreq=0\r\ntot_freq=0\r\nfor key,value in x_tokenizer.word_counts.items():\r\n tot_cnt=tot_cnt+1\r\n tot_freq=tot_freq+value\r\n if(value= (max_summary_len-1)):\r\n stop_condition = True\r\n # Update the target sequence (of length 1).\r\n target_seq = np.zeros((1,1))\r\n target_seq[0, 0] = sampled_token_index\r\n # Update internal states\r\n e_h, e_c = h, c\r\n return decoded_sentence\r\n\r\n\r\ndef seq2summary(input_seq):\r\n newString=''\r\n for i in input_seq:\r\n if((i!=0 and i!=target_word_index['sostok']) and i!=target_word_index['eostok']):\r\n newString=newString+reverse_target_word_index[i]+' '\r\n return newString\r\n\r\ndef seq2text(input_seq):\r\n newString=''\r\n for i in input_seq:\r\n if(i!=0):\r\n newString=newString+reverse_source_word_index[i]+' '\r\n return newString\r\n\r\ndef getSummary(data): \r\n max_text_len=30\r\n x_pred = [text_cleaner(data,0)]\r\n x_pred = convertSequence(x_pred,x_tokenizer)\r\n print(data)\r\n print(x_pred)\r\n print(decode_sequence(x_pred.reshape(1,max_text_len)))\r\n \r\ngetSummary('''I have bought several of the Vitality canned dog food products and have found them all to be of good quality. The product looks more like a stew than a processed meat and it smells better. My Labrador is finicky and she appreciates this product better than most.\r\n''')\r\n\r\n\r\n","sub_path":"test_predict.py","file_name":"test_predict.py","file_ext":"py","file_size_in_byte":8633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"524490674","text":"from collections import defaultdict\r\nimport math\r\nimport time\r\nimport random\r\nimport dynet as dy\r\nimport numpy as np\r\n\r\nN=2 #length of window on each side (so N=2 gives a total window size of 5, as in t-2 t-1 t t+1 t+2)\r\nEMB_SIZE = 128 # The size of the embedding\r\n\r\nembeddings_location = \"embeddings.txt\" #the file to write the word embeddings to\r\nlabels_location = \"labels.txt\" #the file to write the labels to\r\n\r\n# We reuse the data reading from the language modeling class\r\nw2i = defaultdict(lambda: len(w2i))\r\nS = w2i[\"\"]\r\nUNK = w2i[\"\"]\r\ndef read_dataset(filename):\r\n with open(filename, \"r\") as f:\r\n for line in f:\r\n yield [w2i[x] for x in line.strip().split(\" \")]\r\n\r\n# Read in the data\r\ntrain = list(read_dataset(\"../data/ptb/train.txt\"))\r\nw2i = defaultdict(lambda: UNK, w2i)\r\ndev = list(read_dataset(\"../data/ptb/valid.txt\"))\r\ni2w = {v: k for k, v in w2i.items()}\r\nnwords = len(w2i)\r\n\r\nwith open(labels_location, 'w') as labels_file:\r\n for i in range(nwords):\r\n labels_file.write(i2w[i] + '\\n')\r\n\r\n# Start DyNet and define trainer\r\nmodel = dy.Model()\r\ntrainer = dy.SimpleSGDTrainer(model, learning_rate=0.1)\r\n\r\n# Define the model\r\nW_c_p = model.add_lookup_parameters((nwords, EMB_SIZE)) # Word weights at each position\r\nW_w_p = model.add_parameters((nwords, EMB_SIZE)) # Weights of the softmax\r\n\r\n# Calculate the loss value for the entire sentence\r\ndef calc_sent_loss(sent):\r\n # Create a computation graph\r\n dy.renew_cg()\r\n \r\n #add padding to the sentence equal to the size of the window\r\n #as we need to predict the eos as well, the future window at that point is N past it \r\n padded_sent = [S] * N + sent + [S] * N\r\n padded_emb = [W_c_p[x] for x in padded_sent]\r\n\r\n W_w = dy.parameter(W_w_p)\r\n\r\n # Step through the sentence\r\n all_losses = [] \r\n for i in range(N,len(sent)+N):\r\n c = dy.esum(padded_emb[i-N:i] + padded_emb[i+1:i+N+1])\r\n s = W_w * c\r\n all_losses.append(dy.pickneglogsoftmax(s, padded_sent[i]))\r\n return dy.esum(all_losses)\r\n\r\nMAX_LEN = 100\r\n\r\nfor ITER in range(100):\r\n print(\"started iter %r\" % ITER)\r\n # Perform training\r\n random.shuffle(train)\r\n train_words, train_loss = 0, 0.0\r\n start = time.time()\r\n for sent_id, sent in enumerate(train):\r\n my_loss = calc_sent_loss(sent)\r\n train_loss += my_loss.value()\r\n train_words += len(sent)\r\n my_loss.backward()\r\n trainer.update()\r\n if (sent_id+1) % 5000 == 0:\r\n print(\"--finished %r sentences\" % (sent_id+1))\r\n print(\"iter %r: train loss/word=%.4f, ppl=%.4f, time=%.2fs\" % (ITER, train_loss/train_words, math.exp(train_loss/train_words), time.time()-start))\r\n # Evaluate on dev set\r\n dev_words, dev_loss = 0, 0.0\r\n start = time.time()\r\n for sent_id, sent in enumerate(dev):\r\n my_loss = calc_sent_loss(sent)\r\n dev_loss += my_loss.value()\r\n dev_words += len(sent)\r\n trainer.update()\r\n print(\"iter %r: dev loss/word=%.4f, ppl=%.4f, time=%.2fs\" % (ITER, dev_loss/dev_words, math.exp(dev_loss/dev_words), time.time()-start))\r\n\r\n print(\"saving embedding files\")\r\n with open(embeddings_location, 'w') as embeddings_file:\r\n W_w_np = W_w_p.as_array()\r\n for i in range(nwords):\r\n ith_embedding = '\\t'.join(map(str, W_w_np[i]))\r\n embeddings_file.write(ith_embedding + '\\n')\r\n","sub_path":"MachineLearning/NLP/cmu-nlp-notes/nn4nlp-code/03-wordemb/wordemb-cbow.py","file_name":"wordemb-cbow.py","file_ext":"py","file_size_in_byte":3249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"431707393","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Wei, Shuowen\n\nhttps://leetcode.com/problems/gas-station/\n\nhttps://labuladong.gitee.io/algo/3/27/106/\n\nLC134\n\"\"\"\nclass Solution(object):\n def canCompleteCircuit(self, gas, cost):\n \"\"\"\n :type gas: List[int]\n :type cost: List[int]\n :rtype: int\n \"\"\"\n n = len(gas)\n runningSum, minSum = 0, 0\n start = 0\n for i in range(n):\n runningSum += gas[i] - cost[i]\n if runningSum < minSum:\n start = i + 1 \n minSum = runningSum\n if runningSum < 0:\n return -1 \n return start if start!=n else 0\n\n","sub_path":"Medium/LC134.py","file_name":"LC134.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"405880558","text":"import networkx as nx\nimport numpy as np\nimport osmnx as ox\nimport random\nimport matplotlib.pyplot as plt\nfrom haversine import haversine, Unit\nimport pandas as pd\nimport googlemaps\nfrom datetime import datetime\nimport pickle\nimport math\nfrom itertools import islice\n\nox.config(log_console=True, use_cache=True)\nox.__version__\n\n\nclass RunApp():\n def __init__(self,api_key,run_distance,address,difficulty = 'hard',graph = None):\n self.api_key = api_key\n self.difficulty = difficulty\n self.run_distance = run_distance\n self.address = address\n self.address_lat_lon = ox.geocode(address)\n if graph is None:\n self.G = self.render_graph()\n self.add_alt_grades()\n else:\n self.G = graph\n self.add_alt_grades()\n self.home_node = ox.get_nearest_node(self.G, self.address_lat_lon)\n\n def render_graph(self):\n Graph = ox.graph_from_address(self.address, network_type='walk', distance = self.run_distance / 2)\n Graph = ox.add_node_elevations(Graph, api_key=self.api_key)\n Graph = ox.add_edge_grades(Graph)\n return Graph\n\n\n def add_alt_grades(self):\n min_value = math.inf\n if self.difficulty == 'hard':\n for _,_,data in self.G.edges(keys=False, data=True):\n data['alt_grade'] = (float(data['grade']) * -1)\n for _,_,data in self.G.edges(keys=False, data=True):\n if data['alt_grade'] < min_value:\n min_value = float(data['alt_grade'])\n for _,_,data in self.G.edges(keys=False, data=True):\n data['alt_grade'] += abs(min_value)\n elif self.difficulty == 'easy':\n for _,_,data in self.G.edges(keys=False, data=True):\n if float(data['grade']) < min_value:\n min_value = float(data['grade'])\n for _,_,data in my_graph.edges(keys=False, data=True):\n data['alt_grade'] = float(data['grade']) + abs(min_value)\n\n\n def nearest_node_to_address(self):\n ll = ox.geocode(self.address)\n begin_lat, begin_lon = ll[0], ll[1]\n\n return ox.get_nearest_node(self.G, (begin_lat, begin_lon))\n\n def plot_edge_elevation(self):\n G_proj = ox.project_graph(self.G)\n ec = ox.get_edge_colors_by_attr(G_proj, 'grade_abs', cmap='plasma', num_bins=100)\n fig, ax = ox.plot_graph(G_proj, fig_height=6, edge_color=ec, edge_linewidth=0.8, node_size=0)\n\n def plot_node_elevation(self):\n G_proj = ox.project_graph(self.G)\n nc = ox.get_node_colors_by_attr(G_proj, 'elevation', cmap='plasma', num_bins=20)\n fig, ax = ox.plot_graph(G_proj, fig_height=6, node_color=nc, node_size=12, node_zorder=2, edge_color='#dddddd')\n\n def point_inside_radius(self,lat1,lon1,lat2, lon2,radius):\n beginning_point = (lat1,lon1)\n ending_point = (lat2,lon2)\n distance = haversine(beginning_point, ending_point, unit=Unit.METERS)\n if distance <= radius:\n return True\n else:\n return False\n\n def select_random_node(self):\n s_node_id = random.choice(list(self.G.nodes()))\n s_node_lat,s_node_lon = self.G.node[s_node_id]['y'] , self.G.node[s_node_id]['x']\n return s_node_id,s_node_lat,s_node_lon\n\n def plot_points(self,list_of_ll):\n fig, ax = ox.plot_graph(self.G, fig_height=10, fig_width=10, show=False, close=False, edge_color='black')\n for ll in list_of_ll:\n lon1 = ll[1]\n lat1 = ll[0]\n ax.scatter(lon1, lat1, s=100, cmap=plt.cm.get_cmap('Dark2'))\n plt.show()\n\n def google_grab_road_details(self,start_lat, start_lon, end_lat, end_lon):\n gmaps = googlemaps.Client(key=self.api_key)\n now = datetime.now()\n\n directions_result = gmaps.directions((start_lat,start_lon),\n (end_lat,end_lon),\n mode=\"driving\",\n departure_time=now)\n\n length_of_trip = len(directions_result[0]['legs'][0]['steps'])\n distance = directions_result[0]['legs'][0]['distance']['text']\n duration = directions_result[0]['legs'][0]['duration']['text']\n duration_in_traffic = directions_result[0]['legs'][0]['duration_in_traffic']['text']\n\n return length_of_trip, distance, duration, duration_in_traffic\n\n def google_add_edge_traffic(self):\n for start,end,data in self.G.edges(keys=False, data=True):\n try:\n start_lat, start_lon, end_lat, end_lon = self.G.node[start]['y'], self.G.node[start]['x'], self.G.node[end]['y'], self.G.node[end]['x']\n length_of_trip, distance, duration, duration_in_traffic = self.grab_road_details(start_lat, start_lon, end_lat, end_lon)\n if length_of_trip == 1:\n print(\"Adding data for edge from {} to {}\".format(start,end))\n data['drive_distance'] = distance\n data['duration'] = duration\n data['duration_in_traffic'] = duration_in_traffic\n elif length_of_trip > 1:\n print(\"Adding data for edge from {} to {} with zero duration\".format(start,end))\n data['drive_distance'] = distance\n data['duration'] = 0\n data['duration_in_traffic'] = 0\n else:\n print(\"Error\")\n exit()\n except:\n print(\"Error\")\n\n def shortest_path_grade(self,orig_node,target_node):\n # route = nx.shortest_path(G=self.G, source=orig_node, target=target_node, weight='alt_grade')\n route = nx.dijkstra_path(self.G, orig_node, target_node, weight='alt_grade')\n return route\n\n def cut_similar_paths(self,df,percentage = 75.0):\n for i in range(len(df)):\n for n in range(len(df)):\n if df.iloc[i]['Node'] == -1:\n pass\n else:\n if df.iloc[n]['Node'] == -1:\n pass\n else:\n if i == n:\n pass\n else:\n i_path, n_path = df.iloc[i]['Path'], df.iloc[n]['Path']\n setA, setB = set(i_path), set(n_path)\n\n overlap = setA & setB\n\n if len(setA) >= len(setB):\n result = (len(overlap) / len(setA)) * 100\n else:\n result = (len(overlap) / len(setB)) * 100\n if result >= percentage:\n i_d = df.iloc[n]['ID']\n non_i_d = df.iloc[i]['ID']\n print('Node {} has been eliminated since node {} and {} are {}% similar'.format(i_d,non_i_d,i_d,result))\n df.loc[i_d, 'Node'] = -1\n\n df = df[df.Node != -1]\n\n return df\n\n def find_hardest_easiest_routes(self):\n df_list = []\n count = 0\n for node in self.G.nodes():\n if node != self.home_node:\n leave_path = self.shortest_path_grade(self.home_node,node)\n return_path = self.shortest_path_grade(node,self.home_node)\n overall_path = leave_path + return_path[1:]\n print(\"____________\")\n print(leave_path)\n print(\"____________\")\n exit()\n distance = 0\n grade = 0\n for i in range(len(overall_path)-1):\n val = self.G[overall_path[i]][overall_path[i+1]][0]\n distance += val['length']\n grade += round(float(val['grade']),4)\n\n avg_grade = round(grade / len(overall_path) ,4)\n df_list.append([count,node,overall_path,leave_path,return_path,len(overall_path),int(distance),round(grade,4),avg_grade])\n count+=1\n df = pd.DataFrame(df_list, columns = ['ID','Node','Path','Leave_Path','Return_Path','Path_Length','Distance','Grade','Avg_Grade'])\n df = df.drop(df[df.Distance <= (self.run_distance) - 25].index | df[df.Distance >= (self.run_distance) +25].index)\n\n if self.difficulty == 'hard':\n df.sort_values(by=['Grade'], inplace = True, ascending = False)\n df = self.cut_similar_paths(df,50.0)\n df = df.head(5)\n elif self.difficulty == 'easy':\n df.sort_values(by=['Grade'], inplace = True, ascending = True)\n print(df)\n df = self.cut_similar_paths(df,50.0)\n df = df.head(5)\n self.map_routes(df)\n\n @staticmethod\n def lower_grade_road(m):\n min_val = min(x[0] for x in m)\n for val in m:\n if val[0] == min_val:\n return val\n\n def testing_paths(self):\n df_list = []\n count = 0\n for node in self.G.nodes():\n if node != self.home_node:\n leave_path = self.shortest_path_grade(self.home_node,node)\n return_path = self.shortest_path_grade(node,self.home_node)\n overall_path = leave_path + return_path[1:]\n distance = 0\n grade = 0\n for i in range(len(overall_path)-1):\n potential_grades = []\n val = self.G[overall_path[i]][overall_path[i+1]]\n for n in range(len(val)):\n potential_grades.append([float(val[n]['grade']),val[n]['length']])\n lgr = self.lower_grade_road(potential_grades)\n distance += lgr[1]\n grade += round(lgr[0],4)\n\n avg_grade = round(grade / len(overall_path) ,4)\n df_list.append([count,node,overall_path,leave_path,return_path,len(overall_path),int(distance),round(grade,4),avg_grade])\n count+=1\n df = pd.DataFrame(df_list, columns = ['ID','Node','Path','Leave_Path','Return_Path','Path_Length','Distance','Grade','Avg_Grade'])\n df = df.drop(df[df.Distance <= (self.run_distance) - 25].index | df[df.Distance >= (self.run_distance) +25].index)\n\n if self.difficulty == 'hard':\n df.sort_values(by=['Grade'], inplace = True, ascending = False)\n print(df)\n df = self.cut_similar_paths(df,50.0)\n df = df.head(5)\n elif self.difficulty == 'easy':\n df.sort_values(by=['Grade'], inplace = True, ascending = False)\n print(df)\n df = self.cut_similar_paths(df,50.0)\n df = df.head(5)\n self.map_routes(df)\n\n def map_routes(self,df):\n routes = []\n for i in range(len(df)):\n r = df.iloc[i]['Path']\n routes.append(r)\n\n colors = ['r','b','y','m','c']\n colors = colors[0:len(routes)]\n\n route_colors = []\n count = 0\n for i in range(len(routes)):\n if count != len(routes) - 1:\n route_colors += ([colors[i]]*(len(routes[i])-1))\n count +=1\n else:\n route_colors += ([colors[i]]*len(routes[i]))\n\n node_colors = []\n for i in range(len(routes)):\n node_colors += (['k']+[colors[i]])\n\n\n fig, ax = ox.plot_graph_routes(my_graph, routes, route_color=route_colors, orig_dest_node_color=node_colors, node_size=0)\n\n\n\ndef save_object(obj, filename):\n with open(filename, 'wb') as output: # Overwrites any existing file.\n pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)\n\ndef load_object(filename):\n with open(filename, \"rb\") as input_file:\n e = pickle.load(input_file)\n return e\n\ndef save_map(graph,filename):\n #File format should be like EX: 'mississauga.graphml'\n ox.save_load.save_graphml(graph,filename)\n\ndef load_map(filename):\n return ox.save_load.load_graphml(filename)\n","sub_path":"RunningApplication.py","file_name":"RunningApplication.py","file_ext":"py","file_size_in_byte":12423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"138479639","text":"import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport math\r\nimport statistics\r\n\r\n#Imports\r\n#Redwood City\r\ndfrc=pd.read_csv(r'Redwood_City\\Apartment(Redwood_City).csv',index_col=0)\r\nbdrc=pd.read_csv(r'Redwood_City\\Bedroom(Redwood_City).csv',index_col=0)\r\n#Menlo Park\r\ndfmp=pd.read_csv(r'Menlo_Park\\Apartment(Menlo_Park).csv',index_col=0)\r\nbdmp=pd.read_csv(r'Menlo_Park\\Bedroom(Menlo_Park).csv',index_col=0)\r\n#Mountain View\r\ndfmv=pd.read_csv(r'Mountain_View\\Apartment(Mountain_View).csv',index_col=0)\r\nbdmv=pd.read_csv(r'Mountain_View\\Bedroom(Mountain_View).csv',index_col=0)\r\n#San Mateo\r\ndfsm=pd.read_csv(r'San_Mateo\\Apartment(San_Mateo).csv',index_col=0)\r\nbdsm=pd.read_csv(r'San_Mateo\\Bedroom(San_Mateo).csv',index_col=0)\r\n\r\n#Total Sum of Square\r\n#Population\r\nframe=[bdrc,bdmp,bdmv,bdsm]\r\nresult=pd.concat(frame)\r\npopPrices=result[\"Price\"]\r\npop=sorted(popPrices)\r\ntrimpop=pop[52:-52]\r\n\r\n#Grand Mean\r\nxpop=sum(trimpop)/len(trimpop) #Cannot use trimpop.mean() due to Error Attr.\r\nprint(xpop) #2678.76\r\n\r\n#Sum of Square Total\r\nss=[math.pow(popsq-xpop,2) for popsq in trimpop]\r\nprint(sum(ss)) #14601392.93\r\n\r\n#Sum of Square Within\r\nbdrcPrice=bdrc['Price']\r\nbdmpPrice=bdmp['Price']\r\nbdmvPrice=bdmv['Price']\r\nbdsmPrice=bdsm['Price']\r\n\r\n#Sorted in Order\r\nRC=sorted(bdrcPrice)\r\nMP=sorted(bdmpPrice)\r\nMV=sorted(bdmvPrice)\r\nSM=sorted(bdsmPrice)\r\n\r\n#Trimming at 5%\r\ntrimrc=RC[12:-12]\r\ntrimmp=MP[9:-9]\r\ntrimmv=MV[15:-15]\r\ntrimsm=SM[15:-15]\r\n\r\n#Cities Mean Square\r\nxrc=sum(trimrc)/len(trimrc)\r\nxmp=sum(trimmp)/len(trimmp)\r\nxmv=sum(trimmv)/len(trimmv)\r\nxsm=sum(trimsm)/len(trimsm)\r\nssrc=[math.pow(poprc-xrc,2) for poprc in trimrc]\r\nssmp=[math.pow(popmp-xmp,2) for popmp in trimmp]\r\nssmv=[math.pow(popmv-xmv,2) for popmv in trimmv]\r\nsssm=[math.pow(popsm-xsm,2) for popsm in trimsm]\r\n\r\nprint(sum(ssrc))#3582756.46\r\nprint(sum(ssmp))#5501637.61\r\nprint(sum(ssmv))#3071955.37\r\nprint(sum(sssm))#4264498.19\r\n","sub_path":"supplementals/Sum_Squared/SSWITHIN25%.py","file_name":"SSWITHIN25%.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"366743709","text":"# Next Prime Number\n\"\"\"\n Have the program find prime numbers until the user chooses to stop asking for the next one.\n \n 让程序找到质数,直到用户选择不再要求下一个。\n \n referer:\n https://github.com/turlapatykaushik/Programs-and-codes/blob/master/problems/prime_number_generator.py\n https://github.com/MrBlaise/learnpython/blob/master/Numbers/next_prime.py\n\"\"\"\n\n\ndef is_prime(x):\n \"\"\" Checks whether the given number x is prime or not \"\"\"\n if x == 2 and x % 2 != 0:\n return True\n\n for i in range(3, int(x**0.5)+1, 2):\n if x % i == 0:\n return False\n return True\n\n\ndef all_prime_numbers(maximum=100):\n start = 1\n while start < maximum:\n # all([]) --> True\n if all(start % i != 0 for i in range(2, start//2 + 1)):\n print(start)\n start += 1\n\n\ndef main():\n all_prime_numbers()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Python3.6.5/Numbers/prime_next.py","file_name":"prime_next.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"259865658","text":"from __future__ import (division, print_function)\n\nfrom yahmm.yahmm import *\nfrom nose.tools import with_setup\n\ndef setup_model():\n\n\trandom.seed(0)\n\n\ts1 = State(UniformDistribution(0.0, 1.0), name=\"S1\")\n\ts2 = State(UniformDistribution(0.5, 1.5), name=\"S2\")\n\ts3 = State(UniformDistribution(-1.0, 1.0), name=\"S3\")\n\n\t# Make a simple 2-state model\n\tglobal model_a\n\tmodel_a = Model(name=\"A\")\n\tmodel_a.add_state(s1)\n\tmodel_a.add_state(s2)\n\tmodel_a.add_transition(s1, s1, 0.70)\n\tmodel_a.add_transition(s1, s2, 0.25)\n\tmodel_a.add_transition(s1, model_a.end, 0.05)\n\tmodel_a.add_transition(s2, s2, 0.70)\n\tmodel_a.add_transition(s2, s1, 0.25)\n\tmodel_a.add_transition(s2, model_a.end, 0.05)\n\tmodel_a.add_transition(model_a.start, s1, 0.5)\n\tmodel_a.add_transition(model_a.start, s2, 0.5)\n\n\t# Make another model with that model as a component\n\tglobal model_b\n\tmodel_b = Model(name=\"B\")\n\tmodel_b.add_state(s3)\n\tmodel_b.add_transition(model_b.start, s3, 1.0)\n\tmodel_b.add_model(model_a)\n\tmodel_b.add_transition(s3, model_a.start, 1.0)\n\tmodel_b.add_transition(model_a.end, model_b.end, 1.0)\n\tmodel_b.bake()\n\ndef teardown_model():\n\tpass # just pass for now\n\n@with_setup(setup_model, teardown_model)\ndef test_sampling():\n\n\tsample = model_b.sample()\n\n\tassert all([val in sample for val in [0.515908805880605, 1.0112747213686086,\n\t\t1.2837985890347725, 0.9765969541523558, 1.4081128851953353,\n\t\t0.7818378443997038, 0.6183689966753316]]) , \"Sampling check\"\n\n@with_setup(setup_model, teardown_model)\ndef test_viterbi():\n\t# This sequence should work\n\tviterbi_output = model_b.viterbi([-0.5, 0.2, 0.2])\n\n\tassert viterbi_output[0] == -4.738701578612614, \"Viterbi check\"\n\n\t# This one should not\n\tviterbi_output = model_b.viterbi([-0.5, 0.2, 0.2 -0.5])\n\tassert str(viterbi_output) == \"(-inf, None)\", \"Impossible sequence Viterbi check\"\n\n@with_setup(setup_model, teardown_model)\ndef test_training():\n\ttraining_improvement = model_b.train([[-0.5, 0.2, 0.2], [-0.5, 0.2, 1.2, 0.8]],\n\t\t transition_pseudocount=1)\n\n\tassert str(training_improvement) == str(4.13320746579), \"Model training improvement\"\n","sub_path":"tests/test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"57052877","text":"import RPi.GPIO as GPIO\nimport time\nleds = [ 21, 20, 16, 12, 7, 8, 25, 24 ]\ndac = [ 26, 19, 13, 6, 5, 11, 9, 10 ]\naux = [ 22,23,27,18,15,14,3,2]\n\n\np0 = [0,0,0,0 ,0,0,0,0]\npd = p0\nGPIO.setmode(GPIO.BCM)\n\nGPIO.setup(leds, GPIO.OUT)\nGPIO.setup(dac, GPIO.OUT)\nGPIO.setup(aux, GPIO.IN)\n\nGPIO.output(leds, p0)\nGPIO.output(dac, p0)\n\nwhile 0==0:\n for i in range(8):\n pd[i] = GPIO.input(aux[i])\n GPIO.output(leds, pd)\n time.sleep(1)\n GPIO.output(leds,p0)\n\nGPIO.output(leds, p0)\nGPIO.output(dac, p0)\n\nGPIO.cleanup()","sub_path":"2_3.py","file_name":"2_3.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"353641479","text":"import urllib.request\nimport json\nendpoint = 'https://maps.googleapis.com/maps/api/directions/json'\napi_key = 'AIzaSyAzOGcqN1rq2PgdYgiNHFV089pXKJ-2L1o'\norigin = input('Where are you?').replace(' ','+')\ndestination = input('Where do you want to go?').replace(' ','+')\n\nnav_request = 'origin=()&destination=()&key=()'.format(origin,destination,api_key)\nrequest = endpoint + nav_request\nresponse = urllib.request.urlopen(request).read()\ndirections = json.loads(response)\nprint(directions)","sub_path":"googleapi.py","file_name":"googleapi.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"176776904","text":"from factory_test import *\n\n\ndef Patent():\n profile_type = input(\"whitch profile u'd like to create? [LinkedIn or FaceBook]\")\n profile = eval(profile_type.lower())()\n print(\"Creating Profile...\",type(profile).__name__)\n print(\"Profile has section --\",profile.getSections())\n\ndef Pizza():\n pizza = PizzaStore()\n req = input(\"which kind of Pizza u'd like to choose? [Indian or US]\")\n pizza.makePizza(req.lower())\n\nif __name__ == '__main__':\n Pizza()\n\n","sub_path":"client_test.py","file_name":"client_test.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"385306299","text":"import aesara\nimport aesara.tensor as at\nimport numpy as np\nimport pytest\n\nfrom aesara.compile import SharedVariable\nfrom aesara.graph import graph_inputs\n\nimport pymc as pm\n\nfrom pymc.sampling_jax import (\n get_jaxified_logp,\n replace_shared_variables,\n sample_numpyro_nuts,\n)\n\n\ndef test_transform_samples():\n aesara.config.on_opt_error = \"raise\"\n np.random.seed(13244)\n\n obs = np.random.normal(10, 2, size=100)\n obs_at = aesara.shared(obs, borrow=True, name=\"obs\")\n with pm.Model() as model:\n a = pm.Uniform(\"a\", -20, 20)\n sigma = pm.HalfNormal(\"sigma\")\n b = pm.Normal(\"b\", a, sigma=sigma, observed=obs_at)\n\n trace = sample_numpyro_nuts(chains=1, random_seed=1322, keep_untransformed=True)\n\n log_vals = trace.posterior[\"sigma_log__\"].values\n\n trans_vals = trace.posterior[\"sigma\"].values\n assert np.allclose(np.exp(log_vals), trans_vals)\n\n assert 8 < trace.posterior[\"a\"].mean() < 11\n assert 1.5 < trace.posterior[\"sigma\"].mean() < 2.5\n\n obs_at.set_value(-obs)\n with model:\n trace = sample_numpyro_nuts(chains=2, random_seed=1322, keep_untransformed=False)\n\n assert -11 < trace.posterior[\"a\"].mean() < -8\n assert 1.5 < trace.posterior[\"sigma\"].mean() < 2.5\n\n\ndef test_replace_shared_variables():\n x = aesara.shared(5, name=\"shared_x\")\n\n new_x = replace_shared_variables([x])\n shared_variables = [var for var in graph_inputs(new_x) if isinstance(var, SharedVariable)]\n assert not shared_variables\n\n x.default_update = x + 1\n with pytest.raises(ValueError, match=\"shared variables with default_update\"):\n replace_shared_variables([x])\n\n\ndef test_get_jaxified_logp():\n with pm.Model() as m:\n x = pm.Flat(\"x\")\n y = pm.Flat(\"y\")\n pm.Potential(\"pot\", at.log(at.exp(x) + at.exp(y)))\n\n jax_fn = get_jaxified_logp(m)\n # This would underflow if not optimized\n assert not np.isinf(jax_fn((np.array(5000.0), np.array(5000.0))))\n","sub_path":"pymc/tests/test_sampling_jax.py","file_name":"test_sampling_jax.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"511770380","text":"from src.text_interpreter import Nutritionix\nfrom src.db import Sheety\nfrom src.decorators import log\n\nclass ExerciseBot:\n\tdef __init__(self, gender: str, weight: float, height: float, age: int) -> None:\n\n\t\tself.nutr = Nutritionix()\n\t\tself.db = Sheety()\n\n\t\tself.gender = gender\n\t\tself.weight = weight\n\t\tself.height = height\n\t\tself.age = age\n\n\tdef add_exercise(self, sentence: str) -> None:\n\t\tdata = self.get_exercise_info(sentence=sentence)\n\t\tself.db.add_data(data=data)\n\n\t@log(\"nut_info\")\n\tdef get_exercise_info(self, sentence: str) -> list[dict]:\n\t\treturn self.nutr.get_exercise_info(\n\t\t\tsentence=sentence,\n\t\t\tgender=self.gender,\n\t\t\tweight=self.weight,\n\t\t\theight=self.height,\n\t\t\tage=self.age\n\t\t\t)\n\ndef main() -> None:\n\tbot = ExerciseBot(\n\t\tgender=\"male\",\n\t\tweight=80.5,\n\t\theight=179.0,\n\t\tage=20\n\t\t)\n\n\tsentence = input(\"Describe your execise: \")\n\n\tbot.add_exercise(sentence=sentence)\n\n\t\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"exercise_bot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"555125504","text":"def parking(param) -> int:\n stores = list(map(int, param.split()))\n return (max(stores) - min(stores)) * 2\n\ndef test_1():\n assert parking('24 13 89 37') == 152\n\nif __name__ == '__main__':\n num_cases = int(input())\n for case in range(num_cases):\n input()\n print(parking(input()))","sub_path":"python/1_to_2/parking2.py","file_name":"parking2.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"648601422","text":"#!/usr/bin/env python\nimport numpy as np\nimport sys\nimport matplotlib.pyplot as plt\nfrom lmfit import Model, Parameters, minimize, fit_report, Minimizer\nfrom numpy import log10\nfrom scipy.integrate import simps\nimport pickle as cPickle\nimport os.path\nimport random\nfrom astropy.io import fits\nimport string\nimport timeit\n\n# import from custom codes\nfrom .function import check_line_man, check_line_cz_man, filconv, calc_Dn4, savecpkl\nfrom .zfit import check_redshift\nfrom .plot_Zevo import *\nfrom .plot_sfh import plot_sfh_pcl2\n\n\n############################\npy_v = (sys.version_info[0])\nif py_v > 2:\n try:\n raw_input = input\n except NameError:\n pass\n\n#################\n# Physical params\n#################\nc = 3.e18 # A/s\nmag0 = 25.0 # Magnitude zeropoint set.\nd = 10**(73.6/2.5) # From [ergs/s/cm2/A] to [ergs/s/cm2/Hz]\n\n\n################\n# Line library\n################\nLN = ['Mg2', 'Ne5', 'O2', 'Htheta', 'Heta', 'Ne3', 'Hdelta', 'Hgamma', 'Hbeta', 'O3L', 'O3H', 'Mgb', 'Halpha', 'S2L', 'S2H']\nLW = [2800, 3347, 3727, 3799, 3836, 3869, 4102, 4341, 4861, 4960, 5008, 5175, 6563, 6717, 6731]\nfLW = np.zeros(len(LW), dtype='int') # flag.\n\n\n################\n# RF colors.\n################\nhome = os.path.expanduser('~')\n#fil_path = home + '/eazy-v1.01/PROG/FILT/'\nfil_path = home + '/Dropbox/FILT/'\neaz_path = home + '/Dropbox/OUTPUT_M1149/' # From which z-prior is taken.\n\n\n#####################\n# Function fo MCMC\n#####################\nclass Mainbody():\n def __init__(self, inputs):\n self.inputs = inputs\n\n def get_lines(self, LW0):\n fLW = np.zeros(len(LW0), dtype='int')\n LW = LW0\n return LW, fLW\n\n def main(self, ID0, PA0, zgal, flag_m, zprev, Cz0, Cz1, mcmcplot=1, fzvis=1, specplot=1, fneld=0, ntemp=5): # flag_m related to redshift error in redshift check func.\n\n start = timeit.default_timer()\n\n inputs = self.inputs\n DIR_TMP = inputs['DIR_TEMP']\n\n if os.path.exists(DIR_TMP) == False:\n os.mkdir(DIR_TMP)\n\n #\n # Age\n #\n age = inputs['AGE']\n age = [float(x.strip()) for x in age.split(',')]\n nage = np.arange(0,len(age),1)\n\n #\n # Metallicity\n #\n Zmax, Zmin = float(inputs['ZMAX']), float(inputs['ZMIN'])\n delZ = float(inputs['DELZ'])\n Zall = np.arange(Zmin, Zmax, delZ) # in logZsun\n\n # For minimizer.\n delZtmp = delZ\n #delZtmp = 0.4 # to increase speed.\n\n # For z prior.\n delzz = 0.001\n zlimu = 6.\n snlim = 1\n zliml = zgal - 0.5\n\n\n # N of param:\n try:\n ndim = int(inputs['NDIM'])\n except:\n if int(inputs['ZEVOL']) == 1:\n ndim = int(len(nage) * 2 + 1)\n else:\n ndim = int(len(nage) + 1 + 1)\n\n pass\n\n #\n # Line\n #\n LW0 = inputs['LINE']\n LW0 = [float(x.strip()) for x in LW0.split(',')]\n\n #\n # Params for MCMC\n #\n nmc = int(inputs['NMC'])\n nwalk = int(inputs['NWALK'])\n nmc_cz = int(inputs['NMCZ'])\n nwalk_cz = int(inputs['NWALKZ'])\n f_Zevol = int(inputs['ZEVOL'])\n #f_zvis = int(inputs['ZVIS'])\n\n #\n # Tau for MCMC parameter; not as fitting parameters.\n #\n tau0 = inputs['TAU0']\n tau0 = [float(x.strip()) for x in tau0.split(',')]\n #tau0 = [0.1,0.2,0.3] # Gyr\n\n\n from .function_class import Func\n from .basic_func import Basic\n fnc = Func(Zall, nage) # Set up the number of Age/ZZ\n bfnc = Basic(Zall)\n\n from .writing import Analyze\n wrt = Analyze(inputs) # Set up for input\n\n\n # Open ascii file and stock to array.\n #lib = open_spec(ID0, PA0)\n lib = fnc.open_spec_fits(ID0, PA0, fall=0, tau0=tau0)\n lib_all = fnc.open_spec_fits(ID0, PA0, fall=1, tau0=tau0)\n\n #####################\n # Model templates.\n #####################\n chimax = 1.\n\n #################\n # Observed Data\n #################\n\n ##############\n # Spectrum\n ##############\n dat = np.loadtxt(DIR_TMP + 'spec_obs_' + ID0 + '_PA' + PA0 + '.cat', comments='#')\n NR = dat[:,0]\n x = dat[:,1]\n fy00 = dat[:,2]\n ey00 = dat[:,3]\n\n con0 = (NR<1000)\n fy0 = fy00[con0] * Cz0\n ey0 = ey00[con0] * Cz0\n con1 = (NR>=1000) & (NR<10000)\n fy1 = fy00[con1] * Cz1\n ey1 = ey00[con1] * Cz1\n con2 = (NR>=10000) # BB\n fy2 = fy00[con2]\n ey2 = ey00[con2]\n\n fy01 = np.append(fy0,fy1)\n fy = np.append(fy01,fy2)\n ey01 = np.append(ey0,ey1)\n ey = np.append(ey01,ey2)\n\n wht = 1./np.square(ey)\n sn = fy/ey\n\n ##############\n # Broadband\n ##############\n dat = np.loadtxt(DIR_TMP + 'bb_obs_' + ID0 + '_PA' + PA0 + '.cat', comments='#')\n NRbb = dat[:, 0]\n xbb = dat[:, 1]\n fybb = dat[:, 2]\n eybb = dat[:, 3]\n exbb = dat[:, 4]\n wht2 = check_line_man(fy, x, wht, fy, zprev,LW0)\n\n #####################\n # Function fo MCMC\n #####################\n def residual(pars): # x, y, wht are taken from out of the definition.\n vals = pars.valuesdict()\n Av = vals['Av']\n ######################\n '''\n for aa in range(len(age)):\n if aa == 0:\n mod0, x1 = fnc.tmp03(ID0, PA0, vals['A'+str(aa)], Av, aa, vals['Z'+str(aa)], zprev, lib, tau0)\n model = mod0\n else:\n mod0, xxbs = fnc.tmp03(ID0, PA0, vals['A'+str(aa)], Av, aa, vals['Z'+str(aa)], zprev, lib, tau0)\n model += mod0\n '''\n model, x1 = fnc.tmp04(ID0, PA0, vals, zprev, lib, tau0=tau0)\n ######################\n if fy is None:\n print('Data is none')\n return model\n else:\n return (model - fy) * np.sqrt(wht2) # i.e. residual/sigma\n\n def lnprob(pars):\n vals = pars.valuesdict()\n Av = vals['Av']\n resid = residual(pars)\n s = 1. #pars['f']\n resid *= 1 / s\n resid *= resid\n resid += np.log(2 * np.pi * s**2)\n if Av<0:\n return -np.inf\n else:\n respr = np.log(1)\n return -0.5 * np.sum(resid) + respr\n\n\n ###############################\n # Add parameters\n ###############################\n fit_params = Parameters()\n for aa in range(len(age)):\n if age[aa] == 99:\n fit_params.add('A'+str(aa), value=0, min=0, max=0.01)\n else:\n fit_params.add('A'+str(aa), value=1, min=0, max=400)\n\n #fit_params.add('Av', value=1., min=0, max=4.0)\n fit_params.add('Av', value=0.2, min=0, max=4.0)\n #fit_params.add('Z', value=0, min=np.min(Zall), max=np.max(Zall))\n for aa in range(len(age)):\n if age[aa] == 99:\n fit_params.add('Z'+str(aa), value=1, min=0, max=0.01)\n else:\n fit_params.add('Z'+str(aa), value=0, min=np.min(Zall), max=np.max(Zall))\n\n ##################################\n # Metallicity determination\n ##################################\n chidef = 1e5\n Zbest = 0\n\n fwz = open('Z_' + ID0 + '_PA' + PA0 + '.cat', 'w')\n fwz.write('# ID Zini chi/nu AA Av Zbest\\n')\n\n nZtmp = int((Zmax-Zmin)/delZtmp)\n\n if fneld == 1:\n for zz in range(0,nZtmp,1):\n #for zz in range(2,7,2):\n ZZ = zz * delZtmp + np.min(Zall)\n for aa in range(len(age)):\n fit_params['Z'+str(aa)].value = ZZ\n\n out_tmp = minimize(residual, fit_params, method='nelder') # nelder is the most efficient.\n #print(ZZ, bfnc.Z2NZ(ZZ))\n #print(fit_report(out_tmp))\n #print('\\n')\n\n keys = fit_report(out_tmp).split('\\n')\n csq = 99999\n rcsq = 99999\n for key in keys:\n if key[4:7] == 'chi':\n skey = key.split(' ')\n csq = float(skey[14])\n if key[4:7] == 'red':\n skey = key.split(' ')\n rcsq = float(skey[7])\n\n fitc = [csq, rcsq] # Chi2, Reduced-chi2\n\n fwz.write('%s %.2f %.5f'%(ID0, ZZ, fitc[1]))\n\n AA_tmp = np.zeros(len(age), dtype='float32')\n ZZ_tmp = np.zeros(len(age), dtype='float32')\n for aa in range(len(age)):\n AA_tmp[aa] = out_tmp.params['A'+str(aa)].value\n fwz.write(' %.5f'%(AA_tmp[aa]))\n\n Av_tmp = out_tmp.params['Av'].value\n fwz.write(' %.5f'%(Av_tmp))\n for aa in range(len(age)):\n ZZ_tmp[aa] = out_tmp.params['Z'+str(aa)].value\n fwz.write(' %.5f'%(ZZ_tmp[aa]))\n\n fwz.write('\\n')\n if fitc[1]snlim)\n fy_cz = fy[con_cz]\n ey_cz = ey[con_cz]\n x_cz = x[con_cz] # Observed range\n NR_cz = NR[con_cz]\n\n xm_s = xm_tmp / (1+zprev) * (1+zrecom)\n fm_s = np.interp(x_cz, xm_s, fm_tmp)\n\n\n if fzvis==1:\n plt.plot(x_cz/(1+zprev)*(1.+zrecom),fm_s,'gray', linestyle='--', linewidth=0.5, label='Default ($z=%.5f$)'%(zprev)) # Model based on input z.\n plt.plot(x_cz, fy_cz,'b', linestyle='-', linewidth=0.5, label='Obs.') # Observation\n plt.errorbar(x_cz, fy_cz, yerr=ey_cz, color='b', capsize=0, linewidth=0.5) # Observation\n\n\n if flag_m == 0:\n dez = 0.5\n else:\n dez = 0.2\n\n #\n # For Eazy\n #\n '''\n dprob = np.loadtxt(eaz_path + 'photz_' + str(int(ID0)) + '.pz', comments='#')\n zprob = dprob[:,0]\n cprob = dprob[:,1]\n\n zz_prob = np.arange(0,13,delzz)\n cprob_s = np.interp(zz_prob, zprob, cprob)\n prior_s = 1/cprob_s\n prior_s /= np.sum(prior_s)\n '''\n\n zz_prob = np.arange(0,13,delzz)\n prior_s = zz_prob * 0 + 1.\n prior_s /= np.sum(prior_s)\n\n print('################\\nStart MCMC for redshift fit\\n################')\n res_cz, fitc_cz = check_redshift(fy_cz,ey_cz,x_cz,fm_tmp,xm_tmp/(1+zprev),zprev,dez,prior_s,NR_cz, zliml, zlimu, delzz, nmc_cz, nwalk_cz)\n z_cz = np.percentile(res_cz.flatchain['z'], [16,50,84])\n scl_cz0 = np.percentile(res_cz.flatchain['Cz0'], [16,50,84])\n scl_cz1 = np.percentile(res_cz.flatchain['Cz1'], [16,50,84])\n\n zrecom = z_cz[1]\n Czrec0 = scl_cz0[1]\n Czrec1 = scl_cz1[1]\n\n xm_s = xm_tmp / (1+zprev) * (1+zrecom)\n fm_s = np.interp(x_cz, xm_s, fm_tmp)\n\n whtl = 1/np.square(ey_cz)\n wht2, ypoly = check_line_cz_man(fy_cz, x_cz, whtl, fm_s, zrecom, LW0)\n con_line = (wht2==0)\n\n\n print('\\n\\n')\n print('Recommended redshift, Cz0 and Cz1, %.5f %.5f %.5f, with chi2/nu=%.3f'%(zrecom, Cz0 * Czrec0, Cz1 * Czrec1, fitc_cz[1]))\n print('\\n\\n')\n\n if fzvis==1:\n plt.plot(x_cz, fm_s, 'r', linestyle='-', linewidth=0.5, label='Updated model ($z=%.5f$)'%(zrecom)) # Model based on recomended z.\n plt.plot(x_cz[con_line], fm_s[con_line], color='orange', marker='o', linestyle='', linewidth=3.)\n\n # Plot lines for reference\n for ll in range(len(LW)):\n conpoly = (x_cz>12000) & (x_cz<16500)\n yline = np.max(ypoly[conpoly])\n yy = np.arange(yline/1.02, yline*1.1)\n xxpre = yy * 0 + LW[ll] * (1.+zprev)\n xx = yy * 0 + LW[ll] * (1.+zrecom)\n plt.plot(xxpre, yy/1.02, linewidth=0.5, linestyle='--', color='gray')\n plt.text(LW[ll] * (1.+zprev), yline/1.05, '%s'%(LN[ll]), fontsize=8, color='gray')\n plt.plot(xx, yy, linewidth=0.5, linestyle='-', color='orangered')\n plt.text(LW[ll] * (1.+zrecom), yline, '%s'%(LN[ll]), fontsize=8, color='orangered')\n\n plt.plot(xbb, fybb, '.r', linestyle='', linewidth=0, zorder=4, label='Obs.(BB)')\n plt.plot(xm_tmp, fm_tmp, color='gray', marker='.', ms=0.5, linestyle='', linewidth=0.5, zorder=4, label='Model')\n xmin, xmax = np.min(x_cz)/1.1,np.max(x_cz)*1.1\n plt.xlim(xmin,xmax)\n plt.ylim(0,yline*1.1)\n plt.xlabel('Wavelength ($\\mathrm{\\AA}$)')\n plt.ylabel('$F_\\\\nu$ (arb.)')\n plt.legend(loc=0)\n\n zzsigma = ((z_cz[2] - z_cz[0])/2.)/zprev\n zsigma = np.abs(zprev-zrecom) / (zprev)\n C0sigma = np.abs(Czrec0-Cz0)/Cz0\n eC0sigma = ((scl_cz0[2]-scl_cz0[0])/2.)/Cz0\n C1sigma = np.abs(Czrec1-Cz1)/Cz1\n eC1sigma = ((scl_cz1[2]-scl_cz1[0])/2.)/Cz1\n\n print('Input redshift is %.3f per cent agreement.'%((1.-zsigma)*100))\n print('Error is %.3f per cent.'%(zzsigma*100))\n print('Input Cz0 is %.3f per cent agreement.'%((1.-C0sigma)*100))\n print('Error is %.3f per cent.'%(eC0sigma*100))\n print('Input Cz1 is %.3f per cent agreement.'%((1.-C1sigma)*100))\n print('Error is %.3f per cent.'%(eC1sigma*100))\n\n plt.show()\n\n #\n # Ask interactively;\n #\n flag_z = raw_input('Do you want to continue with original redshift, Cz0 and Cz1, %.5f %.5f %.5f? ([y]/n/m) '%(zprev, Cz0, Cz1))\n else:\n flag_z = 'y'\n\n\n #################################################\n # Gor for mcmc phase\n #################################################\n if flag_z == 'y' or flag_z == '':\n zrecom = zprev\n Czrec0 = Cz0\n Czrec1 = Cz1\n\n ##############################\n # Save fig of z-distribution.\n ##############################\n fig = plt.figure(figsize=(6.5,2.5))\n fig.subplots_adjust(top=0.96, bottom=0.16, left=0.09, right=0.99, hspace=0.15, wspace=0.25)\n ax1 = fig.add_subplot(111)\n n, nbins, patches = ax1.hist(res_cz.flatchain['z'], bins=200, normed=False, color='gray',label='')\n\n yy = np.arange(0,np.max(n),1)\n xx = yy * 0 + z_cz[1]\n ax1.plot(xx,yy,linestyle='-',linewidth=1,color='orangered',label='$z=%.5f_{-%.5f}^{+%.5f}$\\n$C_z0=%.3f$\\n$C_z1=%.3f$'%(z_cz[1],z_cz[1]-z_cz[0],z_cz[2]-z_cz[1], Czrec0, Czrec1))\n xx = yy * 0 + z_cz[0]\n ax1.plot(xx,yy,linestyle='--',linewidth=1,color='orangered')\n xx = yy * 0 + z_cz[2]\n ax1.plot(xx,yy,linestyle='--',linewidth=1,color='orangered')\n xx = yy * 0 + zprev\n ax1.plot(xx,yy,linestyle='-',linewidth=1,color='royalblue')\n ax1.set_xlabel('Redshift')\n ax1.set_ylabel('$dn/dz$')\n ax1.legend(loc=0)\n plt.savefig('zprob_' + ID0 + '_PA' + PA0 + '.pdf', dpi=300)\n plt.close()\n\n ##############################\n print('\\n\\n')\n print('Input redshift is adopted.')\n print('Starting long journey in MCMC.')\n print('\\n\\n')\n #################\n # Initialize mm.\n #################\n mm = 0\n # add a noise parameter\n # out.params.add('f', value=1, min=0.001, max=20)\n wht2 = wht\n\n\n ################################\n print('Defined Minimizer\\n')\n mini = Minimizer(lnprob, out.params)\n print('################\\nStarting emcee\\n################\\n')\n import multiprocessing\n ncpu0 = int(multiprocessing.cpu_count()/2)\n try:\n ncpu = int(inputs['NCPU'])\n if ncpu > ncpu0:\n print('!!! NCPU is larger than No. of CPU. !!!')\n #print('Now set to %d'%(ncpu0))\n #ncpu = ncpu0\n except:\n ncpu = ncpu0\n pass\n print('No. of CPU is set to %d'%(ncpu))\n start_mc = timeit.default_timer()\n res = mini.emcee(burn=int(nmc/2), steps=nmc, thin=10, nwalkers=nwalk, params=out.params, is_weighted=True, ntemps=ntemp, workers=ncpu)\n stop_mc = timeit.default_timer()\n tcalc_mc = stop_mc - start_mc\n print('#######################\\nMCMC part took %.1f sec\\n#######################'%(tcalc_mc))\n\n\n #----------- Save pckl file\n #-------- store chain into a cpkl file\n import corner\n burnin = int(nmc/2)\n savepath = './'\n cpklname = 'chain_' + ID0 + '_PA' + PA0 + '_corner.cpkl'\n savecpkl({'chain':res.flatchain,\n 'burnin':burnin, 'nwalkers':nwalk,'niter':nmc,'ndim':ndim},\n savepath+cpklname) # Already burn in\n\n Avmc = np.percentile(res.flatchain['Av'], [16,50,84])\n #Zmc = np.percentile(res.flatchain['Z'], [16,50,84])\n\n Avpar = np.zeros((1,3), dtype='float32')\n Avpar[0,:] = Avmc\n\n out = res\n ##############################\n # Best parameters\n Amc = np.zeros((len(age),3), dtype='float32')\n Ab = np.zeros(len(age), dtype='float32')\n Zmc = np.zeros((len(age),3), dtype='float32')\n Zb = np.zeros(len(age), dtype='float32')\n NZbest = np.zeros(len(age), dtype='int')\n f0 = fits.open(DIR_TMP + 'ms_' + ID0 + '_PA' + PA0 + '.fits')\n sedpar = f0[1]\n ms = np.zeros(len(age), dtype='float32')\n for aa in range(len(age)):\n Ab[aa] = out.params['A'+str(aa)].value\n Amc[aa,:] = np.percentile(res.flatchain['A'+str(aa)], [16,50,84])\n Zb[aa] = out.params['Z'+str(aa)].value\n Zmc[aa,:] = np.percentile(res.flatchain['Z'+str(aa)], [16,50,84])\n NZbest[aa]= bfnc.Z2NZ(Zb[aa])\n ms[aa] = sedpar.data['ML_' + str(NZbest[aa])][aa]\n\n Avb = out.params['Av'].value\n\n ####################\n # MCMC corner plot.\n ####################\n if mcmcplot == 1:\n fig1 = corner.corner(res.flatchain, labels=res.var_names, label_kwargs={'fontsize':16}, quantiles=[0.16, 0.84], show_titles=False, title_kwargs={\"fontsize\": 14}, truths=list(res.params.valuesdict().values()), plot_datapoints=False, plot_contours=True, no_fill_contours=True, plot_density=False, levels=[0.68, 0.95, 0.997], truth_color='gray', color='#4682b4')\n fig1.savefig('SPEC_' + ID0 + '_PA' + PA0 + '_corner.pdf')\n plt.close()\n\n\n #########################\n msmc0 = 0\n for aa in range(len(age)):\n msmc0 += res.flatchain['A'+str(aa)]*ms[aa]\n\n msmc = np.percentile(msmc0, [16,50,84])\n\n # Do analysis on MCMC results.\n # Write to file.\n stop = timeit.default_timer()\n tcalc = stop - start\n\n wrt.get_param(res, lib_all, zrecom, Czrec0, Czrec1, z_cz[:], scl_cz0[:], scl_cz1[:], fitc[:], tau0=tau0, tcalc=tcalc)\n\n\n ##########\n # Plot\n ##########\n if specplot == 1:\n plt.close()\n try:\n DIR_FILT = inputs['DIR_FILT']\n except:\n DIR_FILT = './'\n\n plot_sed_Z(ID0, PA0, Zall, age, tau0=tau0, fil_path=DIR_FILT)\n plot_sfh_pcl2(ID0, PA0, Zall, age, f_comp=ftaucomp, fil_path=DIR_FILT)\n\n\n return 0, zrecom, Czrec0, Czrec1\n\n ###################################################################\n elif flag_z == 'm':\n zrecom = float(raw_input('What is your manual input for redshift? '))\n Czrec0 = float(raw_input('What is your manual input for Cz0? '))\n Czrec1 = float(raw_input('What is your manual input for Cz1? '))\n print('\\n\\n')\n print('Generate model templates with input redshift and Scale.')\n print('\\n\\n')\n return 1, zrecom, Czrec0, Czrec1\n\n else:\n print('\\n\\n')\n print('Terminated because of redshift estimate.')\n print('Generate model templates with recommended redshift.')\n print('\\n\\n')\n\n flag_gen = raw_input('Do you want to make templates with recommended redshift, Cz0, and Cz1 , %.5f %.5f %.5f? ([y]/n) '%(zrecom, Czrec0, Czrec1))\n if flag_gen == 'y' or flag_gen == '':\n #return 1, zrecom, Cz0 * Czrec0, Cz1 * Czrec1\n return 1, zrecom, Czrec0, Czrec1\n else:\n print('\\n\\n')\n print('There is nothing to do.')\n print('\\n\\n')\n return 0, zprev, Czrec0, Czrec1\n","sub_path":"gsf/tmp/fitting.py","file_name":"fitting.py","file_ext":"py","file_size_in_byte":24674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"93481548","text":"#!/usr/bin/env python3\nimport os\nimport sys\nimport argparse\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Download m3u8 to mp4')\n parser.add_argument('-l', default=r'', help='视频列表')\n parser.add_argument('-d', default=r'', help='下载目录')\n args = parser.parse_args()\n video_list = os.path.abspath(args.l)\n\n if args.d == '':\n video_dir = os.path.dirname(video_list)\n else:\n video_dir = os.path.abspath(args.d)\n\n with open(video_list) as f:\n lines = f.readlines()\n lines = [_.strip() for _ in lines if _ != '\\n']\n for line in lines:\n name,url = line.split('\\t')\n print(name,url)\n os.system('ffmpeg -i \"{}\" -c copy -bsf:a aac_adtstoasc \"{}\"'\\\n .format(url,os.path.join(video_dir,name)))","sub_path":"download_m3u8.py","file_name":"download_m3u8.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"72553624","text":"######################################################################\n# Author: Sama Manalai\n# Username: manalais\n#\n\n# Assignment: A02: Loopy Language\n# Purpose: Draws an Ice cream and a square\n######################################################################\nimport turtle\n\ndef icecream_cone(cone):\n cone.penup()\n cone.pensize(3)\n cone.setpos(25, 25)\n cone.color('tan')\n cone.pendown()\n cone.fillcolor('tan')\n cone.begin_fill()\n cone.right(70)\n cone.forward(102)\n cone.left(70)\n cone.forward(40)\n cone.right(-75)\n cone.forward(100)\n cone.left(105)\n cone.forward(100)\n cone.end_fill()\ndef icecream_circle(circle):\n circle.penup()\n circle.setpos(75, 100)\n circle.pensize(3)\n circle.color('pink')\n circle.pendown()\n circle.fillcolor('pink')\n circle.begin_fill()\n circle.circle(-52)\n circle.end_fill()\ndef random0(random):\n random.penup()\n random.setpos(-45,40)\n random.pensize(6)\n random.color('blue')\n random.pendown()\n random.fillcolor('blue')\n random.begin_fill()\n for side in range(2):\n random.forward(60)\n random.right(90)\n random.forward(60)\n random.right(90)\n random.end_fill()\n\n\ndef main():\n wn = turtle.Screen()\n cone = turtle.Turtle()\n circle = turtle.Turtle()\n random = turtle.Turtle()\n icecream_cone(cone)\n icecream_circle(circle)\n random0(random)\n wn.exitonclick()\n\nmain()\n","sub_path":"a02_manalais.py","file_name":"a02_manalais.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"204462822","text":"# Copyright 2021 Huawei Technologies Co., Ltd\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'''train.py'''\nimport os\nimport datetime\nfrom time import time\n\nimport mindspore\nimport mindspore.nn as nn\nfrom mindspore import context\nfrom mindspore.train import Model\nfrom mindspore.common import set_seed\nfrom mindspore.dataset import config\nfrom mindspore.common.tensor import Tensor\nfrom mindspore.context import ParallelMode\nfrom mindspore import load_checkpoint, load_param_into_net\nfrom mindspore.communication.management import init, get_rank, get_group_size\nfrom mindspore.train.callback import TimeMonitor, LossMonitor, CheckpointConfig, ModelCheckpoint\n\nfrom src.logger import get_logger\nfrom src.dataset import create_VideoDataset\nfrom src.models import get_r2plus1d_model\nfrom src.utils import TempLoss, AccuracyMetric, EvalCallBack\nfrom src.config import config as cfg\n\ndef copy_data_from_obs():\n '''copy_data_from_obs'''\n if cfg.use_modelarts:\n import moxing as mox\n import zipfile\n cfg.logger.info(\"copying dataset from obs to cache....\")\n mox.file.copy_parallel(cfg.dataset_root_path, 'cache/dataset')\n cfg.logger.info(\"copying dataset finished....\")\n cfg.dataset_root_path = 'cache/dataset/'\n cfg.logger.info(\"starting unzip file to cache....\")\n zFile = zipfile.ZipFile(os.path.join(cfg.dataset_root_path, cfg.pack_file_name), \"r\")\n for fileM in zFile.namelist():\n zFile.extract(fileM, cfg.dataset_root_path)\n zFile.close()\n cfg.dataset_root_path = os.path.join(cfg.dataset_root_path, cfg.pack_file_name.split(\".\")[0])\n cfg.logger.info(\"unzip finished....\")\n if cfg.pretrain_path:\n cfg.logger.info(\"copying pretrain checkpoint from obs to cache....\")\n mox.file.copy_parallel(cfg.pretrain_path, 'cache/pretrain')\n cfg.logger.info(\"copying pretrain checkpoint finished....\")\n cfg.pretrain_path = 'cache/pretrain/'\n\n if cfg.resume_path:\n cfg.logger.info(\"copying resume checkpoint from obs to cache....\")\n mox.file.copy_parallel(cfg.resume_path, 'cache/resume_path')\n cfg.logger.info(\"copying resume checkpoint finished....\")\n cfg.resume_path = 'cache/resume_path/'\n\ndef copy_data_to_obs():\n if cfg.use_modelarts:\n import moxing as mox\n cfg.logger.info(\"copying files from cache to obs....\")\n mox.file.copy_parallel(cfg.save_dir, cfg.outer_path)\n cfg.logger.info(\"copying finished....\")\n\ndef get_lr(steps_per_epoch, max_epoch, init_lr):\n lr_each_step = []\n while max_epoch > 0:\n tem = min(10, max_epoch)\n for _ in range(steps_per_epoch*tem):\n lr_each_step.append(init_lr)\n max_epoch -= tem\n init_lr /= 10\n return lr_each_step\n\ndef train():\n '''train'''\n train_dataset, cfg.steps_per_epoch = create_VideoDataset(cfg.dataset_root_path, cfg.dataset_name, \\\n mode='train', clip_len=16, batch_size=cfg.batch_size, \\\n device_num=cfg.group_size, rank=cfg.rank, shuffle=True)\n cfg.logger.info(\"cfg.steps_per_epoch: %s\", str(cfg.steps_per_epoch))\n f_model = get_r2plus1d_model(cfg.num_classes, cfg.layer_num)\n\n if cfg.pretrain_path and not cfg.resume_path:\n # we execute either pretrain or resume\n cfg.pretrain_path = os.path.join(cfg.pretrain_path, cfg.ckpt_name)\n cfg.logger.info('loading pretrain checkpoint %s into network', str(cfg.pretrain_path))\n param_dict = load_checkpoint(cfg.pretrain_path)\n del param_dict['fc.weight']\n del param_dict['fc.bias']\n load_param_into_net(f_model, param_dict)\n cfg.logger.info('loaded pretrain checkpoint %s into network', str(cfg.pretrain_path))\n\n # resume checkpoint if needed\n if cfg.resume_path:\n cfg.resume_path = os.path.join(cfg.resume_path, cfg.resume_name)\n cfg.logger.info('loading resume checkpoint %s into network', str(cfg.resume_path))\n load_param_into_net(f_model, load_checkpoint(cfg.resume_path))\n cfg.logger.info('loaded resume checkpoint %s into network', str(cfg.resume_path))\n\n f_model.set_train()\n\n # lr scheduling\n lr_list = get_lr(cfg.steps_per_epoch, cfg.epochs, cfg.lr)\n lr_list = lr_list[cfg.steps_per_epoch*cfg.resume_epoch:]\n # optimizer\n optimizer = nn.SGD(params=f_model.trainable_params(), momentum=cfg.momentum,\n learning_rate=Tensor(lr_list, mindspore.float32), weight_decay=cfg.weight_decay)\n loss_fn = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='sum')\n model = Model(f_model, loss_fn, optimizer, amp_level=\"auto\")\n # define callbacks\n callbacks = []\n if cfg.rank == 0:\n time_cb = TimeMonitor(data_size=cfg.steps_per_epoch)\n loss_cb = LossMonitor(1)\n callbacks = [time_cb, loss_cb]\n if cfg.rank_save_ckpt_flag:\n ckpt_config = CheckpointConfig(save_checkpoint_steps=cfg.steps_per_epoch*cfg.save_every,\n keep_checkpoint_max=cfg.ckpt_save_max)\n save_ckpt_path = os.path.join(cfg.save_dir, 'ckpt_' + str(cfg.rank) + '/')\n ckpt_cb = ModelCheckpoint(config=ckpt_config,\n directory=save_ckpt_path,\n prefix='rank_'+str(cfg.rank))\n callbacks.append(ckpt_cb)\n\n if cfg.eval_while_train:\n loss_f = TempLoss()\n val_dataloader, val_data_size = create_VideoDataset(cfg.dataset_root_path, cfg.dataset_name, \\\n mode=cfg.val_mode, clip_len=16, batch_size=cfg.batch_size, \\\n device_num=1, rank=0, shuffle=False)\n network_eval = Model(f_model, loss_fn=loss_f, metrics={\"AccuracyMetric\": \\\n AccuracyMetric(val_data_size*cfg.batch_size)})\n eval_cb = EvalCallBack(network_eval, val_dataloader, interval=cfg.eval_steps, \\\n eval_start_epoch=max(0, cfg.eval_start_epoch-cfg.resume_epoch), \\\n ckpt_directory=cfg.save_dir, save_best_ckpt=True, \\\n best_ckpt_name=str(cfg.rank)+\"_best_map.ckpt\", \\\n f_model=f_model)\n callbacks.append(eval_cb)\n\n cfg.logger.info(\"training started....\")\n start_time = time()\n model.train(cfg.epochs-cfg.resume_epoch, train_dataset, callbacks=callbacks, dataset_sink_mode=True)\n total_time = int(time() - start_time)\n print(f\"Time taken: {total_time // 60} min {total_time % 60} sec\")\n cfg.logger.info(\"training finished....\")\n\nif __name__ == '__main__':\n set_seed(1)\n if not (cfg.device_target in [\"Ascend\", \"GPU\"]):\n raise NotImplementedError(\"Training implemented only on GPU and Ascend target devices\")\n cfg.save_dir = os.path.join(cfg.output_path, datetime.datetime.now().strftime('%Y-%m-%d_time_%H_%M_%S'))\n if not cfg.use_modelarts and not os.path.exists(cfg.save_dir):\n os.makedirs(cfg.save_dir)\n device_id = int(os.getenv('DEVICE_ID', '0'))\n context.set_context(mode=context.GRAPH_MODE,\n device_target=cfg.device_target, save_graphs=False)\n if cfg.is_distributed:\n if cfg.device_target == \"Ascend\":\n context.set_context(device_id=device_id)\n init(\"hccl\")\n elif cfg.device_target == \"GPU\":\n init(\"nccl\")\n cfg.rank = get_rank()\n cfg.group_size = get_group_size()\n device_num = cfg.group_size\n context.reset_auto_parallel_context()\n context.set_auto_parallel_context(device_num=device_num, parallel_mode=ParallelMode.DATA_PARALLEL)\n else:\n if cfg.device_target in [\"Ascend\", \"GPU\"]:\n context.set_context(device_id=device_id)\n config.set_enable_shared_mem(False) # we may get OOM when it set to 'True'\n cfg.logger = get_logger(cfg.save_dir, \"R2plus1D\", cfg.rank)\n cfg.logger.save_args(cfg)\n cfg.rank_save_ckpt_flag = not (cfg.is_save_on_master and cfg.rank)\n copy_data_from_obs()\n train()\n copy_data_to_obs()\n cfg.logger.info('All task finished!')\n","sub_path":"research/cv/r2plus1d/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":8691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"95628916","text":"import numpy as np\n\ndef fconst(x):\n\n r\"\"\"Constant function.\n\n Parameters\n ----------\n x : float, array_like\n Independent variable.\n\n Returns\n -------\n 1 : float, scalar\n Output value, always 1.\n\n \"\"\"\n\n return 1.\n\ndef ffexp(x):\n\n r\"\"\"A function symmetric around :math:`\\pi/2`, which is also the value\n associated with the function's minimum.\n\n Parameters\n ----------\n x : float, array_like\n Independent variable.\n\n Returns\n -------\n y : float, ndarray\n Output value whose shape is the same as `x`.\n\n \"\"\"\n y = 1/3.17739*np.cosh(0.5*(x - np.pi/2.))*((x - np.pi/2.)**2 + 1.)\n return y\n\n# Sinfying a function :P:\ndef fct_sin(x, sfct, *args, **kwargs):\n\n r\"\"\"Multiply a function by :math:`\\sin{(x)}`.\n\n Parameters\n ----------\n x : float, array_like\n Independent variable.\n sfct : function\n The chosen function to be multiplied by :math:`\\sin{(x)}`.\n *args \n Arguments to be passed to `sfct`.\n **kwargs\n Keyword-only arguments to be passed to `sfct`.\n\n Returns\n -------\n y : float, ndarray\n Output value associated with multiplying `sfct` by :math:`\\sin{(x)}`.\n Its shape is the same as `x`.\n\n Notes\n -----\n When picking a random polar point from a function defined on a sphere, \n just using `sfct` will not yield the right result. It is therefore \n necessary to pick a point from :math:`\\sin{(x)}`*`sfct(x)`. For a more\n detailed explanation, check 'Sphere Point Picking' on the internet or\n a text book. \n\n \"\"\"\n\n y = sfct(x, *args, **kwargs)*np.sin(x)\n return y\n\n# Function based on Flow Fourier expansion; order n\ndef fphi_psi(x, vns=None, psis=None):\n\n r\"\"\"A function (Fourier expansion) based on the flow ansatz used in\n heavy-ion studies [1]_ [2]_. It has the following expression:\n\n .. math:: h(x) = \\frac{1}{2\\pi} \\left[ 1 + 2\\sum_{n = 1}^{\\infty} v_n \\cos[n(x - \\Psi_n)] \\right],\n\n where :math:`v_n,\\Psi_n` are the amplitude and phase, respectively.\n\n Parameters\n ----------\n x : float, array_like\n Independent variable.\n vns : float, array_like, optional\n Amplitudes of the Fourier expansion. If not given, it will be\n taken as zero. Default: *None*.\n psis : float, array_like, optional\n Phases of the Fourier expansion. If not given, it will be taken\n as zero. Default: *None*.\n\n Returns\n -------\n y : float, array_like\n Output of the function. It has the same shape as `x`.\n\n\n References\n ----------\n .. [1] S. Voloshin and Y. Zhang, \"Flow study in relativistic nuclear collisions by Fourier expansion of azimuthal particle distributions\", Z. Phys. **C70**, 665 (1996).\n .. [2] A.M. Poskanzer and S.A. Voloshin, \"Methods for analyzing flow in relativistic nuclear collisions\", Phys. Rev. **C58**, 1671 (1998).\n\n \"\"\"\n\n if (vns is None) and (psis is None):\n return 1./(2.*np.pi)*np.ones_like(x)\n elif psis is None:\n n = len(vns)\n psis = np.zeros(n)\n elif vns is None:\n n = len(psis)\n vns = np.zeros(n)\n else:\n n = len(vns)\n psis = np.asarray(psis)\n psis = psis[:, np.newaxis]\n\n y = 1/(2*np.pi)*(1. + 2*np.sum(vns*np.cos(np.arange(1, n + 1)*(x - psis).T), axis=1))\n return y\n\ndef isodist(mult, etacut=None):\n\n r\"\"\"Create an isotropic particle distribution with specified \n multiplicity and limitation in :math:`\\theta`.\n\n Parameters\n ----------\n mult : int, scalar\n Multiplicity or size of the output sample.\n etacut : float, scalar, optional\n Limit imposed on pseudorapidity (or polar angle), i.e.,\n :math:`|\\eta|` < `etacut`. Default: *None*.\n\n Returns\n -------\n angs : float, ndarray\n A 2-D array with shape (`mult`, 2). Under column 0 are the\n azimuthal angles, while under column 1 are the polar angles.\n\n Notes\n -----\n In order to pick a random number on the surface of a sphere, \n azimuthal and polar angles are drawn, respectively, from the \n following expressions:\n\n .. math:: \\phi = 2\\pi u,\\\\\n .. math:: \\theta = \\arccos{(2v - 1)},\n\n where :math:`u,v` are random variables within the interval (0, 1). \n\n \"\"\"\n\n angs = np.zeros((mult, 2))\n angs[:, 0] = np.random.uniform(0., 2*np.pi, size=mult)\n\n if etacut:\n\n qi = 2*np.arctan(np.exp(-etacut))\n qf = 2*np.arctan(np.exp(etacut))\n\n vi = (1 + np.cos(qf))/2.\n vf = (1 + np.cos(qi))/2.\n\n angs[:, 1] = np.arccos(2*np.random.uniform(vi, vf, size=mult) - 1)\n\n else:\n angs[:, 1] = np.random.uniform(size=mult)\n angs[:, 1] = np.arccos(2.*angs[:, 1] - 1.)\n\n return angs\n\ndef from_fct(fct, size, xmin=0., xmax=1., *args, **kwargs):\n\n r\"\"\"Draw random values according to a chosen 1-D function within a\n specified interval.\n\n Parameters\n ----------\n fct : function\n Chosen function.\n size : int, scalar\n Desired number of samples.\n xmin : float, scalar, optional\n Lower boundary of the interval. Default: 0.\n xmax : float, scalar, optional\n Upper boundary of the interval. Output values will be less than\n `xmax`. Default: 1.\n *args\n Arguments to be passed to `fct`.\n **kwargs\n Keyword-only arguments to be passed to `fct`.\n\n Returns\n -------\n samples : float, ndarray\n A 1-D array whose length is determined by `size`. It contains\n random values distributed according to `fct`.\n\n \"\"\"\n\n samples = np.array([])\n ymax = np.max(fct(np.linspace(xmin, xmax, 1000), *args, **kwargs))\n \n ii = 0\n while ii == 0:\n siz0 = size - len(samples)\n ux = np.random.uniform(xmin, xmax, size=3*siz0)\n uy = np.random.uniform(0., 2*ymax, size=3*siz0)\n \n samples = np.append(samples, ux[uy <= fct(ux, *args, **kwargs)])\n \n if len(samples) >= size:\n samples = samples[:size]\n ii += 1\n \n return samples\n","sub_path":"build/lib/powspechi/monte_carlos.py","file_name":"monte_carlos.py","file_ext":"py","file_size_in_byte":6024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"102849011","text":"# -*- coding: utf-8 -*-\n\"\"\"Functions to call when running the function.\n\nThis module should contain a function called `run_module`, that is executed\nwhen the module is run with `python -m MODULE_NAME`.\n\"\"\"\nimport glob\nimport multiprocessing as mp\nimport subprocess\nfrom functools import partial\nfrom os.path import join\n\nimport pandas as pd\nfrom delphi_utils import read_params\n\nfrom .process import process\n\n\nMETRICS = [\n # signal_name, naics_code, wip\n ('bars_visit', 722410, False),\n ('restaurants_visit', 722511, False),\n]\nVERSIONS = [\n # relaese version, access dir\n (\"202004\", \"weekly-patterns/v2\", \"main-file/*.csv.gz\"),\n (\"202006\", \"weekly-patterns-delivery/weekly\", \"patterns/*/*/*\")\n]\nSENSORS = [\n \"num\",\n \"prop\"\n]\nGEO_RESOLUTIONS = [\n \"county\",\n \"hrr\",\n \"msa\",\n \"state\",\n \"hhs\",\n \"nation\"\n]\n\n\ndef run_module():\n \"\"\"Run module for Safegraph patterns data.\"\"\"\n params = read_params()\n export_dir = params[\"export_dir\"]\n raw_data_dir = params[\"raw_data_dir\"]\n n_core = int(params[\"n_core\"])\n aws_endpoint = params[\"aws_endpoint\"]\n static_file_dir = params[\"static_file_dir\"]\n\n env_vars = {\n 'AWS_ACCESS_KEY_ID': params[\"aws_access_key_id\"],\n 'AWS_SECRET_ACCESS_KEY': params[\"aws_secret_access_key\"],\n 'AWS_DEFAULT_REGION': params[\"aws_default_region\"],\n }\n\n for ver in VERSIONS:\n # Update raw data\n # Why call subprocess rather than using a native Python client, e.g. boto3?\n # Because boto3 does not have a simple rsync-like call that can perform\n # the following behavior elegantly.\n if params[\"sync\"]:\n subprocess.run(\n f'aws s3 sync s3://sg-c19-response/{ver[1]}/ '\n f'{raw_data_dir}/{ver[1]}/ --endpoint {aws_endpoint}',\n env=env_vars,\n shell=True,\n check=True\n )\n\n brand_df = pd.read_csv(\n join(static_file_dir, f\"brand_info/brand_info_{ver[0]}.csv\")\n )\n\n files = glob.glob(f'{raw_data_dir}/{ver[1]}/{ver[2]}',\n recursive=True)\n\n process_file = partial(process, brand_df=brand_df,\n metrics=METRICS,\n sensors=SENSORS,\n geo_resolutions=GEO_RESOLUTIONS,\n export_dir=export_dir,\n )\n\n with mp.Pool(n_core) as pool:\n pool.map(process_file, files)\n","sub_path":"safegraph_patterns/delphi_safegraph_patterns/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"286148144","text":"from django.conf.urls import url\r\nfrom django.urls import include, path\r\n\r\nfrom . import views\r\n\r\napp_name = 'basic_app'\r\n\r\nurlpatterns = [\r\n url(r'^$', views.index, name='index'),\r\n url('^', include('django.contrib.auth.urls')),\r\n url(r'^consultation/$', views.consultation, name='consultation'),\r\n url(r'^stories/$', views.stories, name='stories'),\r\n url(r'^font_changing/$', views.font_changing, name='font_changing'),\r\n url(r'^Videos/$', views.Videos, name='Videos'),\r\n url(r'^settings/Review/$', views.Review, name='Review'),\r\n url(r'^about/$', views.about, name='about'),\r\n path('stories/detail//', views.detail, name='detail'),\r\n path('stories/edit_story//', views.edit_story, name='edit_story'),\r\n path('delete_story//', views.delete_story, name='delete_story'),\r\n\r\n]\r\n","sub_path":"basic_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"597885321","text":"# -*- mode: python ; coding: utf-8 -*-\nimport os\nimport platform\n\nOS = platform.system()\n\nblock_cipher = None\n\nbinaries = [(os.path.join('tools', str.lower(OS), '*'), '.')]\n\na = Analysis(['KodularStarter.py', 'utils.py'],\n pathex=['.'],\n binaries=binaries,\n datas=[],\n hiddenimports=[],\n hookspath=[],\n runtime_hooks=[],\n excludes=[],\n win_no_prefer_redirects=False,\n win_private_assemblies=False,\n cipher=block_cipher,\n noarchive=False)\n\npyz = PYZ(a.pure,\n a.zipped_data,\n cipher=block_cipher)\n\nexe = EXE(pyz,\n a.scripts,\n a.binaries,\n a.zipfiles,\n a.datas,\n [],\n name='KodularStarter',\n debug=False,\n bootloader_ignore_signals=False,\n strip=False,\n upx=True,\n upx_exclude=[],\n runtime_tmpdir=None,\n console=True,\n icon='icon.ico')\n\ncoll = COLLECT(exe,\n a.binaries,\n a.zipfiles,\n a.datas,\n strip=False,\n upx=False,\n name='KodularStarter')\n\nif OS == 'Darwin':\n info_plist = {\n 'NSHighResolutionCapable': 'True',\n 'NSPrincipalClass': 'NSApplication',\n 'CFBundleName': 'KodularStarter',\n 'CFBundleDisplayName': 'Kodular Starter',\n 'CFBundleIdentifier': 'io.kodular.starter',\n 'CFBundleVersion': '1',\n 'CFBundleShortVersionString': '1',\n 'LSMinimumSystemVersion': '10.12',\n }\n app = BUNDLE(coll,\n name='KodularStarter.app',\n icon='icon.icns',\n bundle_identifier=None,\n info_plist=info_plist\n )","sub_path":"KodularStarter.spec","file_name":"KodularStarter.spec","file_ext":"spec","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"297600523","text":"#!/usr/bin/env_python\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\nimport pylab\n\ndata = pd.read_csv('OneDimHighPayoff.txt', sep=\"\\t\", header = None)\n\nfig=plt.figure()\nax=fig.gca(projection='3d')\n\nax.set_ylabel('Time (Years)')\nax.set_xlabel('Stock Price ($)')\nax.set_zlabel('Option Value ($)')\nplt.title('Evolution of High Estimator Put Option Values')\n\nx=data['X.1']\nz=data['X.2']\ny=data['X.3']\n\n\nax.scatter(y,x,z,c=z)\n\n#pylab.xlim([0,200])\n#ax.plot_wireframe(x,y,z)\n#fig.colorbar(surf,shrink=0.5, aspect=5)\n\n#NOTE THIS CHANGES THE POSITION OF Z AXIS\ntmp_planes = ax.zaxis._PLANES \nax.zaxis._PLANES = ( tmp_planes[2], tmp_planes[3], \n tmp_planes[0], tmp_planes[1], \n tmp_planes[4], tmp_planes[5])\nview_1 = (25, -135)\nview_2 = (25, -45)\ninit_view = view_2\nax.view_init(elev=20, azim=320)\npylab.xlim([0,200])\nplt.savefig('OptValEvolPut1.png')\n\n#ax.plot(x,y,z)\n\n\n","sub_path":"cuda_dir/CUDA_Implementation_of_the_Stochastic_Mesh_Method/Thesis_CodeA/OneDimPayoff.py","file_name":"OneDimPayoff.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"565136266","text":"from django.contrib import admin\nfrom wagtail.contrib.modeladmin.options import(\n\n ModelAdmin,\n modeladmin_register,\n ModelAdminGroup,\n)\nfrom .models import Reviews,OfferRequests,ContactRequest,WorkspaceRequest\n\nclass ReviewsAdmin(ModelAdmin):\n model=Reviews\n menu_label='Review'\n menu_icon=\"placeholder\"\n menu_order=1\n add_to_settings_menu=False\n exclude_from_explorer=False\n list_display=(\"name\",\"company\",\"comment\")\n search_fields=(\"name\",\"company\",\"comment\")\nclass OfferRequestsAdmin(ModelAdmin):\n model=OfferRequests\n menu_label='Offer Requests'\n menu_icon=\"placeholder\"\n menu_order=1\n add_to_settings_menu=False\n exclude_from_explorer=False\n list_display=(\"services\",\"name\",\"message\")\n search_fields=(\"services\",\"name\")\nclass ContactRequestsAdmin(ModelAdmin):\n model=ContactRequest\n menu_label='Contact Requests'\n menu_icon=\"placeholder\"\n menu_order=1\n add_to_settings_menu=False\n exclude_from_explorer=False\n list_display=(\"name\",\"message\")\n search_fields=(\"name\")\nclass WorkspaceRequestsAdmin(ModelAdmin):\n model=WorkspaceRequest\n menu_label='Workspace Requests'\n menu_icon=\"placeholder\"\n menu_order=1\n add_to_settings_menu=False\n exclude_from_explorer=False\n list_display=(\"name\",\"date\",\"paymentStatus\")\n search_fields=(\"name\",\"date\")\n\nmodeladmin_register(ReviewsAdmin)\nmodeladmin_register(WorkspaceRequestsAdmin)\nmodeladmin_register(OfferRequestsAdmin)\nmodeladmin_register(ContactRequestsAdmin)","sub_path":"appforms/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"537020767","text":"# vim: set ts=8 sw=4 sts=4 et ai:\nfrom functools import update_wrapper\n\nfrom django.contrib.auth import REDIRECT_FIELD_NAME\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.http import HttpResponseRedirect\nfrom django.utils.http import urlquote\n\n\nclass _CheckAuthenticatableContactLogin(object):\n '''\n Copied from the _CheckLogin from django.contrib.auth.decorators and\n customized to fit exactly one need.\n '''\n def __init__(self, view_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):\n if not login_url:\n from django.conf import settings\n login_url = settings.LOGIN_URL\n self.view_func = view_func\n self.login_url = login_url\n self.redirect_field_name = redirect_field_name\n\n # We can't blindly apply update_wrapper because it updates __dict__ and\n # if the view function is already a _CheckLogin object then\n # self.test_func and friends will get stomped. However, we also can't\n # *not* update the wrapper's dict because then view function attributes\n # don't get updated into the wrapper. So we need to split the\n # difference: don't let update_wrapper update __dict__, but then update\n # the (parts of) __dict__ that we care about ourselves.\n update_wrapper(self, view_func, updated=())\n for k in view_func.__dict__:\n if k not in self.__dict__:\n self.__dict__[k] = view_func.__dict__[k]\n\n def __get__(self, obj, cls=None):\n view_func = self.view_func.__get__(obj, cls)\n return _CheckAuthenticatableContactLogin(view_func, self.login_url, self.redirect_field_name)\n\n def __call__(self, request, *args, **kwargs):\n if not request.user.is_authenticated():\n path = urlquote(request.get_full_path())\n tup = self.login_url, self.redirect_field_name, path\n return HttpResponseRedirect('%s?%s=%s' % tup)\n\n if hasattr(request, 'active_relation'):\n relation = request.active_relation\n else:\n try:\n contact = request.user.authenticatablecontact\n except ObjectDoesNotExist:\n relation = None\n else:\n relation = contact.relation\n\n assert relation, 'User %s has no profile / no relation!' % (request.user,)\n return self.view_func(relation, request.user, request, *args, **kwargs)\n\n\ndef login_with_company_profile_required(func):\n '''\n Decorator for views that checks that the user is logged in and checks that\n the user has a valid profile and, which that checked, adds the company and\n user to the view function as first and second parameters, before the request\n object.\n '''\n return _CheckAuthenticatableContactLogin(func)\n","sub_path":"osso/relation/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"132350245","text":"import csv\nimport Divergence\nimport statistics\nimport random\nimport scipy.stats as stats\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport math\nimport sys\n\n\nreader = csv.reader(open(\"Correct/92.csv\", 'r'))\ndata = list(int(row[2]) for row in reader)\nreader = csv.reader(open(\"Centralized/92.csv\", 'r'))\ndata_cen = list(int(row[2]) for row in reader)\nstep = 1403\n\ndropped, dist = Divergence.histogram(data, step)\ndropped, dist_cen = Divergence.histogram(data_cen, step)\n\nfigure = plt.figure(figsize=(1500/300, 900/300), dpi=300)\nacc = 0\nx = []\necdf = []\nfor i in range(60):\n if i in dist:\n acc += dist[i]\n x += [i, i+1]\n ecdf += [acc, acc]\nplt.plot(x, ecdf, 'k', label=\"Correct\")\n\nacc = 0\nx = []\necdf = []\nfor i in range(60):\n if i in dist_cen:\n acc += dist_cen[i]\n x += [i, i+1]\n ecdf += [acc, acc]\nplt.plot(x, ecdf, 'r', label=\"Cheated\")\nplt.legend()\nplt.grid()\nfigure.savefig(\"ECDF.png\")","sub_path":"OldStory/Synthetic/tmp.py","file_name":"tmp.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"282598383","text":"from deep_space_trader.transaction_dialogs import Buy, Sell, PlayerToWarehouse, WarehouseToPlayer\nfrom deep_space_trader import constants as const\nfrom deep_space_trader.utils import errorDialog\n\nfrom PyQt5 import QtWidgets, QtCore, QtGui\n\n\nclass ItemBrowser(QtWidgets.QWidget):\n def __init__(self, parent):\n super(ItemBrowser, self).__init__(parent)\n\n self.parent = parent\n self.mainLayout = QtWidgets.QVBoxLayout(self)\n self.buttonLayout = QtWidgets.QHBoxLayout()\n\n self.table = QtWidgets.QTableWidget()\n self.table.verticalHeader().setVisible(False)\n self.table.setSelectionBehavior(QtWidgets.QTableView.SelectRows)\n self.table.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)\n self.table.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)\n\n self.setupHeader()\n self.populateTable()\n self.mainLayout.addLayout(self.buttonLayout)\n self.mainLayout.addWidget(self.table)\n\n self.table.resizeColumnsToContents()\n self.update()\n\n def setupHeader(self):\n self.table.setColumnCount(2)\n self.table.setHorizontalHeaderLabels(['Item type', 'Quantity'])\n header = self.table.horizontalHeader()\n header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)\n header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)\n\n def update(self):\n self.populateTable()\n super(ItemBrowser, self).update()\n\n def add_button(self, text, on_click):\n b = QtWidgets.QPushButton(text)\n b.clicked.connect(on_click)\n self.buttonLayout.addWidget(b)\n\n def addRow(self, itemname):\n raise NotImplementedError()\n\n def populateTable(self):\n raise NotImplementedError()\n\n\nclass PlayerItemBrowser(ItemBrowser):\n def __init__(self, *args, **kwargs):\n super(PlayerItemBrowser, self).__init__(*args, **kwargs)\n\n self.add_button(\"Sell item\", self.sellButtonClicked)\n self.add_button(\"Add to warehouse\", self.warehouseButtonClicked)\n\n def sellButtonClicked(self):\n selectedRow = self.table.currentRow()\n if selectedRow < 0:\n errorDialog(self, message=\"Please select an item to sell first!\")\n return\n\n itemname = self.table.item(selectedRow, 0).text()\n if itemname not in self.parent.state.current_planet.items.items:\n errorDialog(self, message=\"%s is not currently in demand on %s\"\n % (itemname, self.parent.state.current_planet.full_name))\n return\n\n dialog = Sell(self.parent, itemname)\n dialog.setWindowModality(QtCore.Qt.ApplicationModal)\n dialog.exec_()\n\n def warehouseButtonClicked(self):\n if self.parent.state.warehouse_puts == const.WAREHOUSE_PUTS_PER_DAY:\n errorDialog(self, \"Warehouse\", message=\"You cannot put anything else \"\n \"in the warehouse until tomorrow\")\n return\n\n selectedRow = self.table.currentRow()\n if selectedRow < 0:\n errorDialog(self, message=\"Please select an item first!\")\n return\n\n itemname = self.table.item(selectedRow, 0).text()\n dialog = PlayerToWarehouse(self.parent, itemname)\n dialog.setWindowModality(QtCore.Qt.ApplicationModal)\n dialog.exec_()\n\n def addRow(self, itemname):\n nextFreeRow = self.table.rowCount()\n self.table.insertRow(nextFreeRow)\n collection = self.parent.state.items\n\n item1 = QtWidgets.QTableWidgetItem(itemname)\n item2 = QtWidgets.QTableWidgetItem(str(collection.items[itemname].quantity))\n\n item2.setTextAlignment(QtCore.Qt.AlignHCenter)\n\n self.table.setItem(nextFreeRow, 0, item1)\n self.table.setItem(nextFreeRow, 1, item2)\n\n def populateTable(self):\n self.table.setRowCount(0)\n for name in self.parent.state.items.items:\n self.addRow(name)\n\n\nclass PlanetItemBrowser(ItemBrowser):\n def __init__(self, *args, **kwargs):\n super(PlanetItemBrowser, self).__init__(*args, **kwargs)\n\n self.add_button(\"Buy item\", self.buyButtonClicked)\n\n def setupHeader(self):\n self.table.setColumnCount(3)\n self.table.setHorizontalHeaderLabels(['Item type', 'Quantity', 'Value'])\n header = self.table.horizontalHeader()\n header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)\n header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)\n header.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)\n\n def buyButtonClicked(self):\n selectedRow = self.table.currentRow()\n if selectedRow < 0:\n errorDialog(self, \"No item selected\",\n message=\"Please select an item to buy first!\")\n return\n\n itemname = self.table.item(selectedRow, 0).text()\n if self.parent.state.current_planet.items.items[itemname].quantity == 0:\n errorDialog(self, \"None available\",\n message=\"%s has no %s left to sell\" %\n (self.parent.state.current_planet.full_name, itemname))\n return\n\n dialog = Buy(self.parent, itemname)\n dialog.setWindowModality(QtCore.Qt.ApplicationModal)\n dialog.exec_()\n\n def addRow(self, itemname):\n nextFreeRow = self.table.rowCount()\n self.table.insertRow(nextFreeRow)\n collection = self.parent.state.current_planet.items\n\n item1 = QtWidgets.QTableWidgetItem(itemname)\n item2 = QtWidgets.QTableWidgetItem(str(collection.items[itemname].quantity))\n item3 = QtWidgets.QTableWidgetItem(str(collection.items[itemname].value))\n\n item2.setTextAlignment(QtCore.Qt.AlignHCenter)\n item3.setTextAlignment(QtCore.Qt.AlignHCenter)\n\n self.table.setItem(nextFreeRow, 0, item1)\n self.table.setItem(nextFreeRow, 1, item2)\n self.table.setItem(nextFreeRow, 2, item3)\n\n def populateTable(self):\n self.table.setRowCount(0)\n for name in self.parent.state.current_planet.items.items:\n self.addRow(name)\n\n\nclass WarehouseItemBrowser(ItemBrowser):\n def __init__(self, *args, **kwargs):\n super(WarehouseItemBrowser, self).__init__(*args, **kwargs)\n\n self.add_button(\"Retrieve from warehouse\", self.removeButtonClicked)\n\n def removeButtonClicked(self):\n if self.parent.state.warehouse_gets == const.WAREHOUSE_GETS_PER_DAY:\n errorDialog(self, \"Warehouse\", message=\"You cannot take anything else \"\n \"from the warehouse until tomorrow\")\n return\n\n selectedRow = self.table.currentRow()\n if selectedRow < 0:\n errorDialog(self, message=\"Please select an item first!\")\n return\n\n itemname = self.table.item(selectedRow, 0).text()\n dialog = WarehouseToPlayer(self.parent, itemname)\n dialog.setWindowModality(QtCore.Qt.ApplicationModal)\n dialog.exec_()\n\n\n def addRow(self, itemname):\n nextFreeRow = self.table.rowCount()\n self.table.insertRow(nextFreeRow)\n collection = self.parent.state.warehouse\n\n item1 = QtWidgets.QTableWidgetItem(itemname)\n item2 = QtWidgets.QTableWidgetItem(str(collection.items[itemname].quantity))\n\n item2.setTextAlignment(QtCore.Qt.AlignHCenter)\n\n self.table.setItem(nextFreeRow, 0, item1)\n self.table.setItem(nextFreeRow, 1, item2)\n\n def populateTable(self):\n self.table.setRowCount(0)\n for name in self.parent.state.warehouse.items:\n self.addRow(name)\n","sub_path":"deep_space_trader/item_browsers.py","file_name":"item_browsers.py","file_ext":"py","file_size_in_byte":7673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"122762023","text":"# Import required modules\nimport cv2 as cv\nimport math\nimport argparse\nimport os \nimport time\nimport datetime\n#agiunto il deltatime : guestdatalogger\nfrom datetime import timedelta\nimport tkinter as tk\nfrom tkinter import *\nfrom PIL import Image, ImageTk\n#aggiunto l'importazione del json : guestdatalogger\nimport json\n#aggiunto l'importazione del request : guestdatalogger\nimport requests\nimport threading as thread\nfrom multiprocessing import *\nimport StartWindow\nimport CameraWindow\nimport sys\n\n#il metodo get() della classe Queue, di default ha un parametro block settato a true che blocca il flusso del programma fino a quando la coda si riempie.\n\nclass SenderData (thread.Thread):\n def __init__(self, q, api_key, ex):\n thread.Thread.__init__(self)\n self._stopevent = thread.Event()\n self.q = q\n self.api_key = api_key\n self.ex = ex\n \n def run(self):\n condizione = self.checkEx()\n while condizione:\n self.send_data()\n condizione = self.checkEx()\n print(\"Fuori dal run\")\n #sys.exit()\n return\n \n def join (self, timeout = None):\n self._stopevent.set()\n\n def checkEx(self):\n if(self.ex.get(False)['exit']):\n print(\"exit now\")\n return False\n else:\n print(\"FALSE exit\")\n self.ex.put({'exit': False})\n return True\n \n #Permette l'aggiunta di dati al database\n #@param date Data corrente nel formato mm-dd-YY\n #@param hours Ora attuale.\n #@param minutes Minuti attuali.\n #@param secs Secondi attuali.\n def dataToJSON(self):\n try:\n v = self.q.get(True, 3)\n myJson = {\n \"data\":v[\"time\"],\n \"num_persone\": v[\"count\"],\n \"api_key\":self.api_key\n }\n return myJson\n except:\n print(\"dataToJSON: exception\")\n\n #----------------------------------------------------------------------------- \n\n #----------------------------------------------------------------------------- \n\n #bisogna fare il controllo se la chiave inserita sia veritiera\n\n #verifica se i dati utente inseriti sono validi, per farlo utilizza un try & catch\n # che verifica se l'host o l'utente inserito esistano.\n #@param host Host da testare.\n #@param user User da testare.\n #@param password Password dell'utente da testare.\n\n def send_data(self):\n url = 'http://localhost:8080/GuestDataLogger/scripts/insertStat.php'\n #url = 'http://127.0.0.1'\n req = requests.post(url, json= self.dataToJSON())\n print(req.text)\n\n#----------------------------------------------------------------------------------------\n\nif __name__ == '__main__':\n ex = Queue()\n ex.put({'exit':False})\n q = Queue()\n mw = StartWindow.StartWindow(q)\n api_key = q.get()[\"api_key\"]\n sd = SenderData(q, api_key, ex)\n sd.start()\n cw = CameraWindow.CameraWindow(q, ex)\n while sd.is_alive():\n time.sleep(0.5)\n print(\"Thread morta\")\n # NOTA: IDLE cattura tutte le eccezioni, compresa la SystemExit.\n # Provare senza IDLE.\n sys.exit(\"sys.exit()\")\n #exit()","sub_path":"src/GDL/src/old_version/TestFaceRec.py","file_name":"TestFaceRec.py","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"620583415","text":"def add_matrix():\n if r1==r2 and c1==c2:\n print(\"Addition Matrix of Given matrices is:\")\n for i in range(r1):\n for j in range(c1):\n print(m1[i][j]+m2[i][j], end=\" \")\n print()\n else:\n print(\"Error! Can't Add them!!\")\n\nr1=int(input(\"Enter no of rows in the matrix 1: \"))\nc1=int(input(\"Enter no of columns in the matrix 1: \"))\nm1=[[int(input(\"Enter element: \")) for j in range(c1)] for i in range(r1)]\nfor i in range(r1):\n for j in range(c1):\n print(m1[i][j], end=\" \")\n print()\n\n \nr2=int(input(\"\\nEnter no of rows in the matrix 2: \"))\nc2=int(input(\"Enter no of columns in the matrix 2: \"))\nm2=[[int(input(\"Enter element: \")) for j in range(c2)] for i in range(r2)]\n\nfor i in range(r2):\n for j in range(c2):\n print(m2[i][j], end=\" \")\n print()\nadd_matrix()\n","sub_path":"Python_Programs/addition_of_matrices.py","file_name":"addition_of_matrices.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"129714723","text":"# -*- coding: utf-8 -*-\nfrom abc import ABCMeta\nfrom abc import abstractmethod\nfrom datetime import datetime\nfrom logging import getLogger\nfrom typing import Dict\nfrom typing import Generator\nfrom typing import Iterator\nfrom typing import List\n\nfrom moneybot.market.history import MarketHistory\nfrom moneybot.market.state import MarketState\nfrom moneybot.strategy import ProposedTrade\n\n\nlogger = getLogger(__name__)\n\n\nclass MarketAdapter(metaclass=ABCMeta):\n\n def __init__(\n self,\n history: MarketHistory,\n initial_balances: Dict[str, float],\n fiat: str,\n ) -> None:\n self.market_history = history\n self.balances = initial_balances\n self.fiat = fiat\n\n @abstractmethod\n def get_balances(self):\n raise NotImplementedError\n\n @abstractmethod\n def execute(\n self,\n proposed_trades: Iterator[ProposedTrade],\n market_state: MarketState,\n ):\n raise NotImplementedError\n\n def get_market_state(self, time: datetime) -> MarketState:\n # Get the latest chart data from the market\n charts = self.market_history.latest(time)\n balances = self.get_balances()\n # We wrap these data in a MarketState,\n # which provides some convenience methods.\n market_state = MarketState(charts, balances, time, self.fiat)\n return market_state\n\n def filter_legal(\n self,\n proposed_trades: List[ProposedTrade],\n market_state: MarketState,\n ) -> Generator[ProposedTrade, None, None]:\n '''\n Takes a list of ProposedTrade objects.\n Checks that each is a legal trade by the rules of our market.\n '''\n for proposed in proposed_trades:\n if self.is_legal(proposed, market_state):\n yield proposed\n\n def is_legal(\n self,\n proposed: ProposedTrade,\n market_state: MarketState,\n ) -> bool:\n # TODO This is pretty Poloniex specific, so we might move it\n # to a PoloniexMarketAdapter if we ever add more exchanges.\n\n # Check that proposed bid has a price:\n if not proposed.price:\n logger.warning(\n f'Filtering out proposed trade (has no price): {proposed}.'\n )\n return False\n\n # Check that we have enough to sell\n held_amount = market_state.balances[proposed.from_coin]\n if proposed.bid_amount > held_amount:\n logger.warning(\n \"Filtering out proposed trade (can't sell more than is held): \"\n f\"{proposed}. Holding {held_amount} {proposed.from_coin}.\"\n )\n return False\n\n # Check that we are trading a positive amount for a positive amount\n if proposed.bid_amount < 0 or proposed.ask_amount < 0:\n logger.warning(\n 'Filtering out proposed trade (bid or ask amount < 0): '\n f'{proposed}.'\n )\n return False\n\n # Check that the proposed trade exceeds minimum fiat trade amount.\n if (\n (proposed.from_coin == proposed.fiat and proposed.bid_amount < 0.0001) or\n (proposed.to_coin == proposed.fiat and proposed.ask_amount < 0.0001)\n ):\n logger.warning(\n 'Filtering out proposed trade (transaction too small): '\n f'{proposed}.'\n )\n return False\n\n # Check that the trade is on a market that exists.\n if proposed.market_name not in market_state.chart_data.keys():\n logger.warning(\n f'Filtering out proposed trade (unknown market): {proposed}.'\n )\n return False\n\n return True\n","sub_path":"moneybot/market/adapters/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"15504167","text":"###\n# Copyright 2015-2021, Institute for Systems Biology\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\nfrom builtins import str\nimport time\nimport json\nfrom json.decoder import JSONDecodeError\nimport logging\nimport sys\nimport datetime\nimport re\nimport copy\n\nfrom django.conf import settings\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.cache import never_cache\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom django.contrib import messages\nfrom django.utils.html import escape\n\nfrom google_helpers.stackdriver import StackDriverLogger\nfrom cohorts.models import Cohort, Cohort_Perms\nfrom idc_collections.models import Program, DataSource, Collection, ImagingDataCommonsVersion, Attribute, Attribute_Tooltips, DataSetType\nfrom idc_collections.collex_metadata_utils import build_explorer_context, get_collex_metadata, create_file_manifest\nfrom allauth.socialaccount.models import SocialAccount\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.http import HttpResponse, JsonResponse\nfrom django.contrib.auth.signals import user_login_failed\nfrom django.dispatch import receiver\nfrom idc.models import User_Data\n\n\ndebug = settings.DEBUG\nlogger = logging.getLogger('main_logger')\n\nBQ_ATTEMPT_MAX = 10\nWEBAPP_LOGIN_LOG_NAME = settings.WEBAPP_LOGIN_LOG_NAME\n\n\n# The site's homepage\n@never_cache\ndef landing_page(request):\n collex = Collection.objects.filter(active=True, subject_count__gt=6,\n collection_type=Collection.ORIGINAL_COLLEX, species='Human',\n access=\"Public\").values()\n idc_info = ImagingDataCommonsVersion.objects.get(active=True)\n\n sapien_counts = {}\n\n changes = {\n 'Head': 'Head and Neck',\n 'Head-Neck': 'Head and Neck',\n 'Head-and-Neck': 'Head and Neck',\n 'Colon': 'Colorectal',\n 'Rectum': 'Colorectal',\n \"Marrow, Blood\": \"Blood\",\n \"Testicles\": \"Testis\",\n \"Adrenal Glands\": \"Adrenal Gland\",\n \"Adrenal\": \"Adrenal Gland\"\n }\n\n skip = [\n 'Extremities',\n 'Abdomen, Mediastinum',\n 'Abdomen, Pelvis',\n 'Abdomen',\n 'Ear',\n 'Pelvis, Prostate, Anus',\n \"Intraocular\",\n \"Mesothelium\",\n \"Chest-Abdomen-Pelvis, Leg, TSpine\",\n \"Abdomen, Arm, Bladder, Chest, Head-Neck, Kidney, Leg, Retroperitoneum, Stomach, Uterus\"\n ]\n\n for collection in collex:\n loc = collection['location']\n if re.search(r'[Pp]hantom',loc) or re.search('[Vv]arious',loc) or loc in skip:\n continue\n if collection['location'] in changes:\n loc = changes[collection['location']]\n if loc not in sapien_counts:\n sapien_counts[loc] = 0\n sapien_counts[loc] += collection['subject_count']\n\n ex_tooltips = {\n '1.3.6.1.4.1.14519.5.2.1.6279.6001.224985459390356936417021464571': '

Patient ID: LIDC-IDRI-0834

Modality: CT

',\n '1.3.6.1.4.1.14519.5.2.1.1706.4001.149500105036523046215258942545': '

Patient ID: TCGA-02-0006

Modality: MR

',\n '1.3.6.1.4.1.14519.5.2.1.2744.7002.950936925946327395356711739684': '

Patient ID: QIN-HEADNECK-01-0228

Modality: PET

'\n }\n\n return render(request, 'idc/landing.html', {\n 'request': request,\n 'case_counts': [{'site': x, 'cases': sapien_counts[x], 'fileCount': 0} for x in sapien_counts.keys()],\n 'example_tooltips': ex_tooltips,\n 'idc_info': idc_info\n })\n\n\n# Displays the privacy policy\ndef privacy_policy(request):\n return render(request, 'idc/privacy.html', {'request': request, })\n\n\n# Displays the page of collaborators\ndef collaborators(request):\n return render(request, 'idc/collaborators.html', {'request': request, })\n\n\n# News page (loads from Discourse)\ndef news_page(request):\n return render(request, 'idc/news.html')\n\n\n# User details page\n@login_required\ndef user_detail(request, user_id):\n if debug: logger.debug('Called ' + sys._getframe().f_code.co_name)\n\n if int(request.user.id) == int(user_id):\n\n user = User.objects.get(id=user_id)\n try:\n social_account = SocialAccount.objects.get(user_id=user_id, provider='google')\n except Exception as e:\n # This is a local account\n social_account = None\n user_details = {\n 'date_joined': user.date_joined,\n 'email': user.email,\n 'id': user.id,\n 'last_login': user.last_login\n }\n\n if social_account:\n user_details['extra_data'] = social_account.extra_data if social_account else None\n user_details['first_name'] = user.first_name\n user_details['last_name'] = user.last_name\n else:\n user_details['username'] = user.username\n\n return render(request, 'idc/user_detail.html',\n {'request': request,\n 'user': user,\n 'user_details': user_details,\n 'unconnected_local_account': bool(social_account is None),\n 'social_account': bool(social_account is not None)\n })\n else:\n return render(request, '403.html')\n\n\n# Callback method for logs of failed logins\n@receiver(user_login_failed)\ndef user_login_failed_callback(sender, credentials, **kwargs):\n try:\n # Write log entry\n st_logger = StackDriverLogger.build_from_django_settings()\n log_name = WEBAPP_LOGIN_LOG_NAME\n st_logger.write_text_log_entry(\n log_name,\n '[WEBAPP LOGIN] Login FAILED for: {credentials}'.format(credentials=credentials)\n )\n\n except Exception as e:\n logger.exception(e)\n\n\n# Extended login view so we can track user logins, redirects to data exploration page\ndef extended_login_view(request):\n try:\n # Write log entry\n st_logger = StackDriverLogger.build_from_django_settings()\n log_name = WEBAPP_LOGIN_LOG_NAME\n user = User.objects.get(id=request.user.id)\n st_logger.write_text_log_entry(\n log_name,\n \"[WEBAPP LOGIN] User {} logged in to the web application at {}\".format(user.email,\n datetime.datetime.utcnow())\n )\n\n except Exception as e:\n logger.exception(e)\n\n return redirect(reverse('explore_data'))\n\n\n# Health check callback\n#\n# Because the match for vm_ is always done regardless of its presence in the URL\n# we must always provide an argument slot for it\ndef health_check(request, match):\n return HttpResponse('')\n\n\n# Quota page for the viewer\ndef quota_page(request):\n return render(request, 'idc/quota.html', {'request': request, 'quota': settings.IMG_QUOTA})\n\n\n@login_required\ndef save_ui_hist(request):\n status = 200\n try:\n req = request.POST or request.GET\n hist = req['his']\n try:\n user_data = User_Data.objects.get(user_id=request.user.id)\n user_data.history = hist\n user_data.save()\n\n except ObjectDoesNotExist:\n user_data_dict = {'user_id': request.user.id, \"history\": hist}\n User_Data.objects.update_or_create(**user_data_dict)\n except Exception as e:\n logger.error(\"[ERROR] While trying to save the user's UI preferences:\")\n logger.exception(e)\n status = 500\n\n return JsonResponse({}, status=status)\n\n\n# Method for obtaining the records displayed in the tables on the right-hand side of the explore data page\n@login_required\ndef populate_tables(request):\n response = {}\n status = 200\n tableRes = []\n try:\n req = request.GET if request.GET else request.POST\n path_arr = [nstr for nstr in request.path.split('/') if nstr]\n table_type = path_arr[len(path_arr)-1]\n fields = None\n collapse_on = None\n filters = json.loads(req.get('filters', '{}'))\n offset = int(req.get('offset', '0'))\n limit = int(req.get('limit', '500'))\n if limit > settings.MAX_SOLR_RECORD_REQUEST:\n logger.warning(\"[WARNING] Attempt to request more than MAX_SOLR_RECORD_REQUEST! ({})\".format(limit))\n limit = settings.MAX_SOLR_RECORD_REQUEST\n sort = req.get('sort', 'PatientID')\n sortdir = req.get('sortdir', 'asc')\n checkIds = json.loads(req.get('checkids', '[]'))\n #table_data = get_table_data(filters, table_type)\n diffA = []\n\n sources = ImagingDataCommonsVersion.objects.get(active=True).get_data_sources(\n active=True, source_type=DataSource.SOLR,\n aggregate_level=\"SeriesInstanceUID\" if table_type == 'series' else \"StudyInstanceUID\"\n )\n\n sortByField = True\n #idsReq=[]\n custom_facets = None\n custom_facets_order = None\n if table_type == 'cases':\n custom_facets = {\"per_id\": {\"type\": \"terms\", \"field\": \"PatientID\", \"limit\": limit,\n \"facet\": {\"unique_study\": \"unique(StudyInstanceUID)\",\n \"unique_series\": \"unique(SeriesInstanceUID)\"}}\n }\n tableIndex = 'PatientID'\n fields = ['collection_id', 'PatientID','access']\n facetfields=['unique_study', 'unique_series']\n\n if sort == 'collection_id':\n sortByField = True\n sort_arg = 'collection_id '+sortdir\n\n elif sort == 'PatientID':\n sort_arg = 'PatientID ' + sortdir\n\n elif sort == 'StudyInstanceUID':\n sortByField = False\n sort_arg = 'unique_study ' + sortdir\n custom_facets_order = {\n \"tot\": \"unique(PatientID)\",\n \"per_id\": {\n \"type\": \"terms\",\n \"field\": \"PatientID\",\n \"sort\": sort_arg,\n \"offset\": offset,\n \"limit\": limit,\n \"facet\": {\n \"unique_study\": \"unique(StudyInstanceUID)\",\n \"unique_series\": \"unique(SeriesInstanceUID)\"\n }\n }\n }\n elif sort == 'SeriesInstanceUID':\n sortByField=False\n sort_arg = 'unique_series '+sortdir\n custom_facets_order = {\n \"tot\": \"unique(PatientID)\",\n \"per_id\": {\n \"type\": \"terms\", \"field\": \"PatientID\", \"sort\": sort_arg, \"offset\": offset, \"limit\": limit,\n \"facet\": {\n \"unique_study\": \"unique(StudyInstanceUID)\",\n \"unique_series\": \"unique(SeriesInstanceUID)\"\n }\n }\n }\n\n if table_type == 'studies':\n custom_facets = {\"per_id\": {\"type\": \"terms\", \"field\": \"StudyInstanceUID\", \"limit\": limit,\n \"facet\": {\"unique_series\": \"unique(SeriesInstanceUID)\"}}\n }\n tableIndex = 'StudyInstanceUID'\n fields = ['collection_id','PatientID','StudyInstanceUID','StudyDescription','Modality','StudyDate','access']\n facetfields = ['unique_series']\n sort_arg = 'PatientID asc, StudyDate asc'\n\n if sort in ['PatientID','StudyInstanceUID', 'StudyDescription', 'StudyDate']:\n sortByField = True\n sort_arg = \"{} {}\".format(sort, sortdir)\n if sort == 'PatientID':\n sort_arg = sort_arg+', StudyDate asc'\n #elif sort == 'StudyInstanceUID':\n # sort_arg = sort_arg + 'StudyDate asc'\n elif sort == 'SeriesInstanceUID':\n sortByField = False\n sort_arg = 'unique_series '+sortdir\n\n custom_facets_order = {\"tot\": \"unique(SeriesInstanceUID)\",\n \"per_id\": {\"type\": \"terms\", \"field\": \"StudyInstanceUID\",\n \"sort\": sort_arg,\"offset\": offset, \"limit\": limit,\n \"facet\": {\"unique_series\": \"unique(SeriesInstanceUID)\"}\n }\n }\n\n if table_type == 'series':\n custom_facets = {}\n tableIndex = 'SeriesInstanceUID'\n fields = ['collection_id', 'SeriesInstanceUID', 'StudyInstanceUID', 'SeriesDescription', 'SeriesNumber',\n 'BodyPartExamined', 'Modality', 'access', 'crdc_series_uuid','gcs_bucket','aws_bucket']\n facetfields = []\n sortByField = True\n\n sort_arg = 'StudyInstanceUID asc, SeriesNumber asc' if not sort else \"{} {}, SeriesNumber asc\".format(\n sort, sortdir\n )\n\n if sort == 'SeriesDescription':\n custom_facets_order = {}\n\n order = {}\n curInd = 0\n idsFilt = []\n\n # check that any selected ids are still valid after the filter is updated. ids that are not longer valid are\n # then deselected on the front end\n if len(checkIds)>0:\n selFilters=copy.deepcopy(filters)\n selFilters[tableIndex] = checkIds\n newCheckIds = get_collex_metadata(\n selFilters, [tableIndex], record_limit=len(checkIds)+1,sources=sources, records_only=True,\n collapse_on=tableIndex, counts_only=False, filtered_needed=False, sort=tableIndex+' asc'\n )\n\n nset = set([x[tableIndex] for x in newCheckIds['docs']])\n diffA = [x for x in checkIds if x not in nset]\n\n if sortByField:\n idsReq = get_collex_metadata(\n filters, fields, record_limit=limit, sources=sources, offset=offset, records_only=True,\n collapse_on=tableIndex, counts_only=False, filtered_needed=False, sort=sort_arg\n )\n\n cnt = idsReq['total']\n for rec in idsReq['docs']:\n id = rec[tableIndex]\n idsFilt.append(id)\n order[id] = curInd\n newRow = {}\n for field in fields:\n if field in rec:\n newRow[field] = rec[field]\n else:\n newRow[field] = ''\n tableRes.append(newRow)\n curInd = curInd + 1\n filters[tableIndex]=idsFilt\n if not table_type == 'series':\n cntRecs = get_collex_metadata(\n filters, fields, record_limit=limit, sources=sources, collapse_on=tableIndex, counts_only=True,\n records_only=False, filtered_needed=False, custom_facets=custom_facets, raw_format=True\n )\n\n for rec in cntRecs['facets']['per_id']['buckets']:\n id = rec['val']\n tableRow = tableRes[order[id]]\n for facet in facetfields:\n if facet in rec:\n tableRow[facet] = rec[facet]\n else:\n tableRow[facet] = 0\n else:\n idsReq = get_collex_metadata(\n filters, fields, record_limit=limit, sources=sources, offset=offset, records_only=False,\n collapse_on=tableIndex, counts_only=True, filtered_needed=False, custom_facets=custom_facets_order,\n raw_format=True\n )\n cnt = idsReq['facets']['tot']\n for rec in idsReq['facets']['per_id']['buckets']:\n id = rec['val']\n idsFilt.append(id)\n order[id] = curInd\n newRow = {tableIndex: id}\n for facet in facetfields:\n if facet in rec:\n newRow[facet]=rec[facet]\n else:\n newRow[facet] = 0\n tableRes.append(newRow)\n curInd = curInd + 1\n filters[tableIndex] = idsFilt\n fieldRecs = get_collex_metadata(\n filters, fields, record_limit=limit, sources=sources, records_only=True, collapse_on=tableIndex,\n counts_only=False, filtered_needed=False\n )\n for rec in fieldRecs['docs']:\n id = rec[tableIndex]\n tableRow = tableRes[order[id]]\n for field in fields:\n if not field == tableIndex:\n if field in rec:\n tableRow[field] = rec[field]\n else:\n tableRow[field] = ''\n\n response[\"res\"] = tableRes\n response[\"cnt\"] = cnt\n response[\"diff\"] = diffA\n\n except Exception as e:\n logger.error(\"[ERROR] While attempting to populate the table:\")\n logger.exception(e)\n messages.error(\n request,\n \"Encountered an error when attempting to populate the page - please contact the administrator.\"\n )\n status = 400\n\n return JsonResponse(response, status=status)\n\n\n# Data exploration and cohort creation page\n@login_required\ndef explore_data_page(request, filter_path=False, path_filters=None):\n context = {'request': request}\n is_json = False\n wcohort = False\n status = 200\n\n try:\n req = request.GET or request.POST\n is_dicofdic = (req.get('is_dicofdic', \"False\").lower() == \"true\")\n source = req.get('data_source_type', DataSource.SOLR)\n versions = json.loads(req.get('versions', '[]'))\n filters = json.loads(req.get('filters', '{}'))\n disk_size = (req.get('disk_size', 'False').lower() == \"true\")\n\n fields = json.loads(req.get('fields', '[]'))\n order_docs = json.loads(req.get('order_docs', '[]'))\n counts_only = (req.get('counts_only', \"False\").lower() == \"true\")\n with_related = (req.get('with_clinical', \"True\").lower() == \"true\")\n with_derived = (req.get('with_derived', \"True\").lower() == \"true\")\n collapse_on = req.get('collapse_on', 'SeriesInstanceUID')\n if len(Attribute.objects.filter(name=collapse_on)) <= 0:\n logger.error(\"[ERROR] Attempt to collapse on an invalid field: {}\".format(collapse_on))\n collapse_on='SeriesInstanceUID'\n is_json = (req.get('is_json', \"False\").lower() == \"true\")\n uniques = json.loads(req.get('uniques', '[]'))\n totals = json.loads(req.get('totals', '[]'))\n\n cohort_id = int(req.get('cohort_id', '-1'))\n\n cohort_filters = {}\n if cohort_id > 0:\n cohort = Cohort.objects.get(id=cohort_id, active=True)\n cohort.perm = cohort.get_perm(request)\n if cohort.perm:\n wcohort = True\n cohort_filters_dict = cohort.get_filters_as_dict()\n cohort_filters_list = cohort_filters_dict[0]['filters']\n for cohort in cohort_filters_list:\n cohort_filters[cohort['name']] = cohort['values']\n if filter_path and is_json:\n filters = path_filters\n\n if wcohort and is_json:\n filters = cohort_filters\n\n versions = ImagingDataCommonsVersion.objects.filter(\n version_number__in=versions\n ).get_data_versions(active=True) if len(versions) else ImagingDataCommonsVersion.objects.filter(\n active=True\n ).get_data_versions(active=True)\n\n context = build_explorer_context(\n is_dicofdic, source, versions, filters, fields, order_docs, counts_only, with_related, with_derived,\n collapse_on, is_json, uniques=uniques, totals=totals, disk_size=disk_size\n )\n\n if not is_json:\n # These are filters to be loaded *after* a page render\n if wcohort:\n context['filters_for_load'] = cohort_filters_dict\n elif filter_path:\n context['filters_for_load'] = path_filters\n else:\n filters_for_load = req.get('filters_for_load', None)\n if filters_for_load:\n blacklist = re.compile(settings.BLACKLIST_RE, re.UNICODE)\n if blacklist.search(filters_for_load):\n logger.warning(\"[WARNING] Saw bad filters in filters_for_load:\")\n logger.warning(filters_for_load)\n filters_for_load = {}\n messages.error(\n request,\n \"There was a problem with some of your filters - please ensure they're properly formatted.\"\n )\n status = 400\n else:\n filters_for_load = json.loads(filters_for_load)\n else:\n filters_for_load = None\n context['filters_for_load'] = filters_for_load\n context['hist'] = ''\n try:\n user_data = User_Data.objects.get(user_id=request.user.id)\n context['history'] = json.loads(user_data.history)\n except ObjectDoesNotExist:\n pass\n\n except JSONDecodeError as e:\n logger.error(\"[ERROR] While attempting to load the search page:\")\n logger.error(\"Invalid JSON format received.\")\n logger.exception(e)\n messages.error(\n request,\n \"The filters supplied contained invalid JSON.\"\n )\n status = 400\n except Exception as e:\n logger.error(\"[ERROR] While attempting to load the search page:\")\n logger.exception(e)\n messages.error(\n request,\n \"Encountered an error when attempting to load the page - please contact the administrator.\"\n )\n status = 500\n\n if is_json:\n # In the case of is_json=True, the 'context' is simply attr_by_source\n return JsonResponse(context, status=status)\n\n return render(request, 'idc/explore.html', context)\n\n\ndef explorer_manifest(request):\n req = request.GET or request.POST\n if req.get('manifest-type', 'file-manifest') == 'bq-manifest' :\n messages.error(request, \"BigQuery export requires a cohort! Please save your filters as a cohort.\")\n return JsonResponse({'msg': 'BigQuery export requires a cohort.'}, status=400)\n return create_file_manifest(request)\n\n\n# Given a set of filters in a GET request, parse the filter set out into a filter set recognized\n# by the explore_data_page method and forward it on to that view, returning its response.\ndef parse_explore_filters(request):\n try:\n if not request.GET:\n raise Exception(\"This call only supports GET!\")\n raw_filters = {x: request.GET.getlist(x) for x in request.GET.keys()}\n filters = {}\n filter_ops = {}\n for x in raw_filters:\n if re.search('_op', x):\n filter_ops[x[:x.rfind('_')]] = raw_filters[x][0]\n else:\n filters[x] = raw_filters[x]\n # determine if any of the filters are misnamed\n filter_name_map = {(x[:x.rfind('_')] if re.search('_[gl]te?|_e?btwe?', x) else x): x for x in filters.keys()}\n attr_names = filter_name_map.keys()\n attrs = Attribute.objects.filter(name__in=attr_names)\n attr_map = {x.name: {\"id\": x.id, \"filter\": filter_name_map[x.name]} for x in attrs}\n not_found = [x for x in attr_names if x not in attr_map.keys()]\n blacklist = re.compile(settings.BLACKLIST_RE, re.UNICODE)\n if blacklist.search(str(filters)):\n logger.warning(\"[WARNING] Saw bad filters in filters_for_load:\")\n logger.warning(filters)\n messages.error(\n request,\n \"There was a problem with some of your filters - please ensure they're properly formatted.\"\n )\n else:\n if len(not_found) > 0:\n not_rec = \"{}\".format(\"; \".join(not_found))\n logger.warning(\"[WARNING] Saw invalid filters while parsing explore/filters call:\")\n logger.warning(not_rec)\n messages.warning(request, \"The following attribute names are not recognized: {}\".format(escape(not_rec)))\n else:\n if len(attrs) > 0:\n filters = [{\n \"id\": attr_map[x]['id'],\n \"values\": filters[attr_map[x]['filter']],\n \"op\": filter_ops.get(x, 'OR')\n } for x in attr_map]\n return explore_data_page(request, filter_path=True, path_filters=[{\"filters\": filters}])\n\n except Exception as e:\n logger.error(\"[ERROR] While parsing filters for the explorer page:\")\n logger.exception(e)\n\n return redirect(reverse('explore_data'))\n\n\n# Callback for recording the user's agreement to the warning popup\ndef warn_page(request):\n request.session['seenWarning'] = True;\n return JsonResponse({'warning_status': 'SEEN'}, status=200)\n\n\n# About page\ndef about_page(request):\n return render(request, 'idc/about.html', {'request': request})\n\n\n# User dashboard, where saved cohorts (and, in the future, uploaded/indexed data) are listed\n@login_required\ndef dashboard_page(request):\n context = {'request': request}\n\n try:\n # Cohort List\n cohort_perms = list(set(Cohort_Perms.objects.filter(user=request.user).values_list('cohort', flat=True)))\n # TODO: Add in 'date created' and sort on that\n context['cohorts'] = Cohort.objects.filter(id__in=cohort_perms, active=True).order_by('-name')\n\n except Exception as e:\n logger.error(\"[ERROR] While attempting to load the dashboard:\")\n logger.exception(e)\n\n return render(request, 'idc/dashboard.html', context)\n","sub_path":"idc/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":26547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"128202785","text":"class Solution:\n def solveSudoku(self, board: List[List[str]]) -> None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n \"\"\"\n colDict = [defaultdict(int) for _ in range(9)]\n rowDict = [defaultdict(int) for _ in range(9)]\n boxDict = [defaultdict(int) for _ in range(9)]\n for i in range(9):\n for j in range(9):\n if board[i][j] != '.':\n x = int(board[i][j])\n boxIdx = self.getBoxIdx(i, j)\n rowDict[i][x] = 1\n colDict[j][x] = 1\n boxDict[boxIdx][x] = 1\n def fill(row, col, colDict, rowDict, boxDict):\n nextRow =row + (col + 1)//9\n nextCol = (col + 1)%9\n if row == 9: return True\n boxIdx = self.getBoxIdx(row, col)\n nextBoxIdx = self.getBoxIdx(nextRow, nextCol)\n #print(row, col)\n if board[row][col] != '.':\n return fill(nextRow, nextCol, colDict, rowDict, boxDict)\n for i in range(1, 10):\n if colDict[col][i] + rowDict[row][i] + boxDict[boxIdx][i] == 0:\n board[row][col] = str(i)\n colDict[col][i] = 1\n rowDict[row][i] = 1\n boxDict[boxIdx][i] = 1\n if fill(nextRow, nextCol, colDict, rowDict, boxDict): \n return True\n colDict[col][i] = 0\n rowDict[row][i] = 0\n boxDict[boxIdx][i] = 0\n board[row][col] = '.'\n return False\n fill(0, 0, colDict, rowDict, boxDict)\n return board\n \n def getBoxIdx(self, row, col):\n return 3*(row//3) + col//3\n ","sub_path":"37. Sudoku Solver.py","file_name":"37. Sudoku Solver.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"638321299","text":"class treeNode:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None \n\nclass BinaryTree:\n def __init__(self, cmpFnc):\n self.top = treeNode(None)\n self.cmpFnc = cmpFnc\n\n def recursiveFind(self, key, node):\n if (self.cmpFnc(key,node.value) == 0):\n return True\n elif (self.cmpFnc(key,node.value) < 0):\n if (node.left is None):\n return False\n else:\n return self.recursiveFind(key,node.left)\n elif (self.cmpFnc(key,node.value) > 0):\n if (node.right is None):\n return False\n else:\n return self.recursiveFind(key,node.right)\n else:\n print(\"oh no\")\n return False\n\n def find(self, key):\n return self.recursiveFind(key, self.top) \n\n def recursiveInsert(self, key, node):\n if (self.cmpFnc(key,node.value) == 0):\n #do nothing, it is already there\n waste = 0\n elif (self.cmpFnc(key,node.value) < 0):\n if (node.left is None):\n newNode = treeNode(key)\n node.left = newNode\n else:\n self.recursiveInsert(key, node.left)\n elif (self.cmpFnc(key,node.value) > 0):\n if (node.right is None):\n newNode = treeNode(key)\n node.right = newNode\n else:\n self.recursiveInsert(key, node.right)\n else:\n print(\"how??\")\n return False\n\n def insert(self, key):\n if self.top.value == None:\n self.top.value = key\n print(\"insert top\")\n else:\n self.recursiveInsert(key, self.top)\n print(\"insert value\")\n\n def inOrderTraversal(self, node, rvList):\n if (node.left is not None) :\n self.inOrderTraversal(node.left, rvList)\n rvList.append(node.value)\n if (node.left is not None) :\n self.inOrderTraversal(node.right, rvList)\n\n def traverse(self):\n newList = []\n self.inOrderTraversal(self.top, newList)\n return newList\n\n \n \n\n\n","sub_path":"Semester4_Spring2015/ProgrammingLanguagesAndSystems/hw9/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"542686281","text":"import os\n\n# map is a list of lists [[],[],[],[]], where each another list is next row in print\n# position on map is accesed by map[y][x]\n\ndef print_bcg(bcg):\n for each in bcg:\n print(\"\".join(each))\n\ndef controls(y, x, control, bcg):\n if control == \"w\":\n (y, x) = move_up(y, x, bcg)\n elif control == \"s\":\n (y, x) = move_down(y, x, bcg)\n elif control == \"a\":\n (y, x) = move_left(y, x, bcg)\n elif control == \"d\":\n (y, x) = move_right(y, x, bcg)\n return (y, x)\n\n\ndef move_up(y, x, bcg):\n if bcg[y-1][x] != \"X\":\n bcg[y][x] = ' '\n bcg[y-1][x] = '@'\n return (y-1, x)\n else:\n return (y, x)\n\ndef move_down(y, x, bcg):\n if bcg[y+1][x] != \"X\":\n bcg[y][x] = ' '\n bcg[y+1][x] = '@'\n return (y+1, x)\n else:\n return (y, x)\n\ndef move_left(y, x, bcg):\n if bcg[y][x-1] != \"X\":\n bcg[y][x] = ' '\n bcg[y][x-1] = '@'\n return (y, x-1)\n else:\n return (y, x)\n\ndef move_right(y, x, bcg):\n if bcg[y][x+1] != \"X\":\n bcg[y][x] = ' '\n bcg[y][x+1] = '@'\n return (y, x+1)\n else:\n return (y, x)\n\n\nbcg = []\ntemp_list = []\nfor i in range(0,50):\n temp_list.append('X')\nbcg.append(temp_list)\nfor i in range(0, 48):\n temp_list = ['X']\n for i in range(1,49):\n temp_list.append(' ')\n temp_list.append('X')\n bcg.append(temp_list)\n temp_list = []\nfor i in range(0,50):\n temp_list.append('X')\nbcg.append(temp_list)\n\nprint_bcg(bcg)\ny = 5\nx = 5\nbcg[5][5] = '@'\nprint_bcg(bcg)\n\ncontrol = None\nwhile control != \"exit\":\n control = input()\n (y, x) = controls(y, x, control, bcg)\n os.system(\"clear\")\n print_bcg(bcg)\n","sub_path":"try.py","file_name":"try.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"155158050","text":"import math\nfrom collections import OrderedDict\nfrom rest_framework.pagination import LimitOffsetPagination\nfrom rest_framework.response import Response\n\n#Provide a maximum limit for http GET \":8000/drones/limit=8&offset=0\"\nclass LimitOffsetPaginationWithUpperBound(LimitOffsetPagination):\n #Set the maximum limit value to 20 for ?limit=100 we still return max of 20 instances\n max_limit = 20\n #default_limit is how many instances you want to return if the user does not\n #use a query param ?limit=N to indicate\n default_limit=10\n def get_paginated_response(self, data):\n return Response(OrderedDict([\n ('count', self.count),\n ('next', self.get_next_link()),\n ('previous', self.get_previous_link()),\n ('total_page_count',\n math.ceil(\n self.count / self.limit\n )\n ),\n ('limit', self.limit),\n ('offset', self.offset),\n ('results', data),\n ]))\n","sub_path":"backend/drones/custompagination.py","file_name":"custompagination.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"634128337","text":"def setup():\n size(600, 600)\n \ndef draw():\n background(255)\n translate(50, 450)\n sierprinski(400, 8)\n \ndef sierprinski(sz, level):\n if level == 0:\n fill(0)\n triangle(0, 0, sz, 0, sz / 2.0, -sz*sqrt(3)/2.0)\n else:\n for i in range(3):\n sierprinski(sz / 2.0, level-1)\n translate(sz/2.0, -sz*sqrt(3)/2.0)\n rotate(radians(120))\n","sub_path":"sierpinski/sierpinski.pyde","file_name":"sierpinski.pyde","file_ext":"pyde","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"21389725","text":"from chair.models import Order, Customer\nimport datetime\n\ndef custom_validate(order, customer):\n try:\n custom_error_list = []\n\n if customer.firstname and customer.lastname and len(customer.firstname + customer.lastname) > 30:\n custom_error_list.append(f'Name Error - customer name has > 30 characters')\n\n if customer.phone and (customer.phone.replace(\"+\", \"\").lstrip().startswith(\"0\") or customer.phone.replace(\"+\", \"\").lstrip().startswith(\"1\")):\n # Remove +'s strip the string after then check the leading digit\n # custom_error_list.append(f'Telephone Error - starts with \"{customer.phone[0]}\"')\n # Remove all +'s, -'s and white spaces then take everything but the first \n pn = customer.phone.replace(\"+\", \"\").lstrip()[1:].replace(\" \", \"\").replace(\"-\", \"\") + \"1\"\n # Just remove the digit and add \"1\" to the back of the customer's phone number to let it pass Newegg validation\n #'123-456-7890'\n #'234-567-8901'\n customer.phone = \"-\".join([pn[:3], pn[3:6], pn[6:]])\n\n if customer.street and (\"po box\" in customer.street.lower() or \"p.o. box\" in customer.street.lower()):\n custom_error_list.append(\"Address error - contains P.O. Box\")\n\n if customer.street and not any(char.isdigit() for char in customer.street):\n # Address string has no digits\n custom_error_list.append(\"Address error - has no numeric component\")\n\n if customer.street and len(customer.street) > 40:\n custom_error_list.append(\"Address error - has more than 40 characters\")\n\n other_occurances_this_customer = Customer.objects.filter(firstname__iexact=customer.firstname, lastname__iexact=customer.lastname).exclude(id=customer.id).values_list('id', flat=True)\n # No repeat customer handling - each customer has a different id - exclude the one of the current order to find his other orders\n if other_occurances_this_customer: \n # A customer with this firstname + lastname exists\n five_days_ago = datetime.datetime.utcnow() - datetime.timedelta(days=5)\n orders = Order.objects.filter(customer_id_id__in=other_occurances_this_customer, part_number=order.part_number).exclude(received__gt=five_days_ago).values_list('order_id', flat=True)\n # Find this customers other orders using the list of ids filter for this part only and remove orders older than 5 days ago\n if orders:\n # Repeated order\n custom_error_list.append(f'Order error - this customer has ordered this SKU in {\", \".join(orders)} within range of 5 days')\n\n if custom_error_list: \n s = \" \\n \"\n order.custom_error = s.join(custom_error_list)\n order.save()\n except AttributeError:\n print(f'Could not validate order {order.order_id} from customer {customer.id}, missing parameters')","sub_path":"chair/order_processing/validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":2946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"330962633","text":"\"\"\"List of config validators.\"\"\"\n\nimport warnings\nfrom collections.abc import Iterable\nfrom functools import lru_cache\nfrom pathlib import Path\n\n\nclass ValidationError(ValueError):\n \"\"\"Custom validation error.\"\"\"\n\n\n# The code for this function was taken from matplotlib (v3.3) and modified\n# to fit the needs of eWaterCycle. Matplotlib is licenced under the terms of\n# the the 'Python Software Foundation License'\n# (https://www.python.org/psf/license)\ndef _make_type_validator(cls, *, allow_none=False):\n \"\"\"Construct a type validator for `cls`.\n\n Return a validator that converts inputs to *cls* or raises (and\n possibly allows ``None`` as well).\n \"\"\"\n def validator(inp):\n looks_like_none = isinstance(inp, str) and (inp.lower() == \"none\")\n if (allow_none and (inp is None or looks_like_none)):\n return None\n try:\n return cls(inp)\n except ValueError as err:\n if isinstance(cls, type):\n raise ValidationError(\n f'Could not convert {repr(inp)} to {cls.__name__}'\n ) from err\n raise\n\n validator.__name__ = f\"validate_{cls.__name__}\"\n if allow_none:\n validator.__name__ += \"_or_None\"\n validator.__qualname__ = (validator.__qualname__.rsplit(\".\", 1)[0] + \".\" +\n validator.__name__)\n return validator\n\n\n# The code for this function was taken from matplotlib (v3.3) and modified\n# to fit the needs of eWaterCycle. Matplotlib is licenced under the terms of\n# the the 'Python Software Foundation License'\n# (https://www.python.org/psf/license)\n@lru_cache()\ndef _listify_validator(scalar_validator,\n allow_stringlist=False,\n *,\n n_items=None,\n docstring=None):\n \"\"\"Apply the validator to a list.\"\"\"\n def func(inp):\n if isinstance(inp, str):\n try:\n inp = [\n scalar_validator(val.strip()) for val in inp.split(',')\n if val.strip()\n ]\n except Exception:\n if allow_stringlist:\n # Sometimes, a list of colors might be a single string\n # of single-letter colornames. So give that a shot.\n inp = [\n scalar_validator(val.strip()) for val in inp\n if val.strip()\n ]\n else:\n raise\n # Allow any ordered sequence type -- generators, np.ndarray, pd.Series\n # -- but not sets, whose iteration order is non-deterministic.\n elif isinstance(inp,\n Iterable) and not isinstance(inp, (set, frozenset)):\n # The condition on this list comprehension will preserve the\n # behavior of filtering out any empty strings (behavior was\n # from the original validate_stringlist()), while allowing\n # any non-string/text scalar values such as numbers and arrays.\n inp = [\n scalar_validator(val) for val in inp\n if not isinstance(val, str) or val\n ]\n else:\n raise ValidationError(\n f\"Expected str or other non-set iterable, but got {inp}\")\n if n_items is not None and len(inp) != n_items:\n raise ValidationError(f\"Expected {n_items} values, \"\n f\"but there are {len(inp)} values in {inp}\")\n return inp\n\n try:\n func.__name__ = \"{}list\".format(scalar_validator.__name__)\n except AttributeError: # class instance.\n func.__name__ = \"{}List\".format(type(scalar_validator).__name__)\n func.__qualname__ = func.__qualname__.rsplit(\".\",\n 1)[0] + \".\" + func.__name__\n if docstring is not None:\n docstring = scalar_validator.__doc__\n func.__doc__ = docstring\n return func\n\n\ndef validate_path(value, allow_none=False):\n \"\"\"Return a `Path` object.\"\"\"\n if (value is None) and allow_none:\n return value\n try:\n path = Path(value).expanduser().absolute()\n except TypeError as err:\n raise ValidationError(f\"Expected a path, but got {value}\") from err\n else:\n return path\n\n\nvalidate_string = _make_type_validator(str)\nvalidate_string_or_none = _make_type_validator(str, allow_none=True)\nvalidate_stringlist = _listify_validator(validate_string,\n docstring='Return a list of strings.')\nvalidate_int = _make_type_validator(int)\nvalidate_int_or_none = _make_type_validator(int, allow_none=True)\nvalidate_float = _make_type_validator(float)\nvalidate_floatlist = _listify_validator(validate_float,\n docstring='Return a list of floats.')\n\nvalidate_path_or_none = _make_type_validator(validate_path, allow_none=True)\n\nvalidate_pathlist = _listify_validator(validate_path,\n docstring='Return a list of paths.')\n\n_validators = {\n 'esmvaltool_config': validate_path_or_none,\n 'grdc_location': validate_path_or_none,\n 'container_engine': validate_string_or_none,\n 'singularity_dir': validate_path_or_none,\n 'output_dir': validate_path_or_none,\n 'ewatercycle_config': validate_path_or_none,\n # wflow specific\n 'wflow.singularity_image': validate_string_or_none,\n 'wflow.docker_image': validate_string_or_none,\n # marrmot specific\n 'marrmot.singularity_image': validate_string_or_none,\n 'marrmot.docker_image': validate_string_or_none,\n # lisflood specific\n 'lisflood.singularity_image': validate_string_or_none,\n 'lisflood.docker_image': validate_string_or_none,\n # pcrglobwb specific\n 'pcrglobwb.singularity_image': validate_string_or_none,\n 'pcrglobwb.docker_image': validate_string_or_none,\n}\n","sub_path":"ewatercycle/config/_validators.py","file_name":"_validators.py","file_ext":"py","file_size_in_byte":5905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"456200364","text":"import uuid\n\nimport pytest\nimport time\n\nfrom labelbox.schema.labeling_frontend import LabelingFrontend\nfrom labelbox.schema.annotation_import import MALPredictionImport\n\n\n@pytest.fixture\ndef ontology():\n bbox_tool = {\n 'required':\n False,\n 'name':\n 'bbox',\n 'tool':\n 'rectangle',\n 'color':\n '#a23030',\n 'classifications': [{\n 'required': False,\n 'instructions': 'nested',\n 'name': 'nested',\n 'type': 'radio',\n 'options': [{\n 'label': 'radio_option_1',\n 'value': 'radio_value_1'\n }]\n }]\n }\n polygon_tool = {\n 'required': False,\n 'name': 'polygon',\n 'tool': 'polygon',\n 'color': '#FF34FF',\n 'classifications': []\n }\n polyline_tool = {\n 'required': False,\n 'name': 'polyline',\n 'tool': 'line',\n 'color': '#FF4A46',\n 'classifications': []\n }\n point_tool = {\n 'required': False,\n 'name': 'point--',\n 'tool': 'point',\n 'color': '#008941',\n 'classifications': []\n }\n entity_tool = {\n 'required': False,\n 'name': 'entity--',\n 'tool': 'named-entity',\n 'color': '#006FA6',\n 'classifications': []\n }\n segmentation_tool = {\n 'required': False,\n 'name': 'segmentation--',\n 'tool': 'superpixel',\n 'color': '#A30059',\n 'classifications': []\n }\n checklist = {\n 'required':\n False,\n 'instructions':\n 'checklist',\n 'name':\n 'checklist',\n 'type':\n 'checklist',\n 'options': [{\n 'label': 'option1',\n 'value': 'option1'\n }, {\n 'label': 'option2',\n 'value': 'option2'\n }, {\n 'label': 'optionN',\n 'value': 'optionn'\n }]\n }\n free_form_text = {\n 'required': False,\n 'instructions': 'text',\n 'name': 'text',\n 'type': 'text',\n 'options': []\n }\n\n tools = [\n bbox_tool, polygon_tool, polyline_tool, point_tool, entity_tool,\n segmentation_tool\n ]\n classifications = [checklist, free_form_text]\n return {\"tools\": tools, \"classifications\": classifications}\n\n\n@pytest.fixture\ndef configured_project(client, ontology, rand_gen, image_url):\n project = client.create_project(name=rand_gen(str))\n dataset = client.create_dataset(name=rand_gen(str))\n editor = list(\n client.get_labeling_frontends(\n where=LabelingFrontend.name == \"editor\"))[0]\n project.setup(editor, ontology)\n data_row_ids = []\n for _ in range(len(ontology['tools']) + len(ontology['classifications'])):\n data_row_ids.append(dataset.create_data_row(row_data=image_url).uid)\n project.datasets.connect(dataset)\n project.data_row_ids = data_row_ids\n yield project\n project.delete()\n dataset.delete()\n\n\n@pytest.fixture\ndef prediction_id_mapping(configured_project):\n #Maps tool types to feature schema ids\n ontology = configured_project.ontology().normalized\n result = {}\n\n for idx, tool in enumerate(ontology['tools'] + ontology['classifications']):\n if 'tool' in tool:\n tool_type = tool['tool']\n else:\n tool_type = tool['type']\n result[tool_type] = {\n \"uuid\": str(uuid.uuid4()),\n \"schemaId\": tool['featureSchemaId'],\n \"dataRow\": {\n \"id\": configured_project.data_row_ids[idx],\n },\n 'tool': tool\n }\n return result\n\n\n@pytest.fixture\ndef polygon_inference(prediction_id_mapping):\n polygon = prediction_id_mapping['polygon'].copy()\n polygon.update({\n \"polygon\": [{\n \"x\": 147.692,\n \"y\": 118.154\n }, {\n \"x\": 142.769,\n \"y\": 404.923\n }, {\n \"x\": 57.846,\n \"y\": 318.769\n }, {\n \"x\": 28.308,\n \"y\": 169.846\n }]\n })\n del polygon['tool']\n return polygon\n\n\n@pytest.fixture\ndef rectangle_inference(prediction_id_mapping):\n rectangle = prediction_id_mapping['rectangle'].copy()\n rectangle.update({\n \"bbox\": {\n \"top\": 48,\n \"left\": 58,\n \"height\": 865,\n \"width\": 1512\n },\n 'classifications': [{\n \"schemaId\":\n rectangle['tool']['classifications'][0]['featureSchemaId'],\n \"answer\": {\n \"schemaId\":\n rectangle['tool']['classifications'][0]['options'][0]\n ['featureSchemaId']\n }\n }]\n })\n del rectangle['tool']\n return rectangle\n\n\n@pytest.fixture\ndef line_inference(prediction_id_mapping):\n line = prediction_id_mapping['line'].copy()\n line.update(\n {\"line\": [{\n \"x\": 147.692,\n \"y\": 118.154\n }, {\n \"x\": 150.692,\n \"y\": 160.154\n }]})\n del line['tool']\n return line\n\n\n@pytest.fixture\ndef point_inference(prediction_id_mapping):\n point = prediction_id_mapping['point'].copy()\n point.update({\"point\": {\"x\": 147.692, \"y\": 118.154}})\n del point['tool']\n return point\n\n\n@pytest.fixture\ndef entity_inference(prediction_id_mapping):\n entity = prediction_id_mapping['named-entity'].copy()\n entity.update({\"location\": {\"start\": 67, \"end\": 128}})\n del entity['tool']\n return entity\n\n\n@pytest.fixture\ndef segmentation_inference(prediction_id_mapping):\n segmentation = prediction_id_mapping['superpixel'].copy()\n segmentation.update(\n {'mask': {\n 'instanceURI': \"sampleuri\",\n 'colorRGB': [0, 0, 0]\n }})\n del segmentation['tool']\n return segmentation\n\n\n@pytest.fixture\ndef checklist_inference(prediction_id_mapping):\n checklist = prediction_id_mapping['checklist'].copy()\n checklist.update({\n 'answers': [{\n 'schemaId': checklist['tool']['options'][0]['featureSchemaId']\n }]\n })\n del checklist['tool']\n return checklist\n\n\n@pytest.fixture\ndef text_inference(prediction_id_mapping):\n text = prediction_id_mapping['text'].copy()\n text.update({'answer': \"free form text...\"})\n del text['tool']\n return text\n\n\n@pytest.fixture\ndef video_checklist_inference(prediction_id_mapping):\n checklist = prediction_id_mapping['checklist'].copy()\n checklist.update({\n 'answers': [{\n 'schemaId': checklist['tool']['options'][0]['featureSchemaId']\n }]\n })\n\n checklist.update(\n {\"frames\": [{\n \"start\": 7,\n \"end\": 13,\n }, {\n \"start\": 18,\n \"end\": 19,\n }]})\n del checklist['tool']\n return checklist\n\n\n@pytest.fixture\ndef model_run_predictions(polygon_inference, rectangle_inference,\n line_inference):\n # Not supporting mask since there isn't a signed url representing a seg mask to upload\n return [polygon_inference, rectangle_inference, line_inference]\n\n\n@pytest.fixture\ndef object_predictions(polygon_inference, rectangle_inference, line_inference,\n entity_inference, segmentation_inference):\n return [\n polygon_inference, rectangle_inference, line_inference,\n entity_inference, segmentation_inference\n ]\n\n\n@pytest.fixture\ndef classification_predictions(checklist_inference, text_inference):\n return [checklist_inference, text_inference]\n\n\n@pytest.fixture\ndef predictions(object_predictions, classification_predictions):\n return object_predictions + classification_predictions\n\n\n@pytest.fixture\ndef model(client, rand_gen, configured_project):\n ontology = configured_project.ontology()\n data = {\"name\": rand_gen(str), \"ontology_id\": ontology.uid}\n model = client.create_model(data[\"name\"], data[\"ontology_id\"])\n yield model\n try:\n model.delete()\n except:\n # Already was deleted by the test\n pass\n\n\n@pytest.fixture\ndef model_run(rand_gen, model):\n name = rand_gen(str)\n model_run = model.create_model_run(name)\n yield model_run\n try:\n model_run.delete()\n except:\n # Already was deleted by the test\n pass\n\n\n@pytest.fixture\ndef model_run_annotation_groups(client, configured_project,\n annotation_submit_fn, model_run_predictions,\n model_run):\n configured_project.enable_model_assisted_labeling()\n\n upload_task = MALPredictionImport.create_from_objects(\n client, configured_project.uid, f'mal-import-{uuid.uuid4()}',\n model_run_predictions)\n upload_task.wait_until_done()\n label_ids = []\n for data_row_id in {x['dataRow']['id'] for x in model_run_predictions}:\n label_ids.append(\n annotation_submit_fn(configured_project.uid, data_row_id))\n model_run.upsert_labels(label_ids)\n time.sleep(3)\n yield model_run\n # TODO: Delete resources when that is possible ..\n","sub_path":"tests/integration/mal_and_mea/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":9051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"436142314","text":"import asyncio\nimport aiohttp\nimport http.cookiejar\nfrom lxml import etree, html\nimport re\nfrom DataPersistor import persist\nfrom bs4 import BeautifulSoup\nimport json\n\n\nclass scraper:\n def __init__(self):\n self.jar = http.cookiejar.CookieJar()\n self.headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36'}\n self.baseURL = \"http://www.quamnet.com/\"\n self.news_list_basesURL = self.baseURL + \"newslist.action?listSectionCode=NEW_HOT&p=\"\n self.news_article_baseURL = self.baseURL + \"newscontent.action?articleId=\"\n self.public_news_title_list = []\n self.url_not_parsed = []\n self.loop = asyncio.get_event_loop()\n self.success_count = 0\n self.parse_title_count = 0\n self.page_fetched = []\n self.end_id = 0\n self.start_id = 0\n self.total_url_num = 0\n\n async def fetch_page(self, session, url):\n async with session.get(url, timeout=120) as response:\n # if the html sources is successfully load\n assert response.status == 200\n # return await response.read()\n return await response.text()\n\n # added the try catch mechanism back since the article crawling part is a little bit unstable\n async def issue_call(self, loop, session, sem, parser, url):\n async with sem:\n try:\n html = await self.fetch_page(session, url)\n self.page_fetched.append(url)\n print(\"\\npage %s download is done\\n\" % (url))\n collection = await parser(html, url)\n print(\"\\nParsing task %s is done\\n\" % (url))\n self.public_news_title_list.extend(collection) if type(\n collection) == list else self.public_news_title_list.append(collection)\n # self.public_news_title_list.extend(l)\n return collection\n except Exception as e:\n print(\"\\ncaught exception: [%s] in downloading page: [%s]\\n\" % (e, url))\n self.url_not_parsed.append(url)\n\n async def getNewsList(self, min, max):\n print(\"getNewsList\")\n\n current_page = max\n # each page currently display 30 news\n tasks = []\n # filling all the url that need to download to the tasks list\n # 300 concurrent request at a time; introdcuing the Semaphore mechanism\n sem = asyncio.Semaphore(300)\n async with aiohttp.ClientSession() as session:\n while current_page >= min:\n fullURL = self.news_list_basesURL + str(current_page)\n task = asyncio.ensure_future(self.issue_call(self.loop, session, sem, self.parse_title, fullURL))\n tasks.append(task)\n current_page -= 1\n responses = await asyncio.gather(*tasks)\n return responses\n\n async def parse_title(self, html_string, url):\n l = []\n tree = html.fromstring(str(html_string))\n title = tree.xpath('//td[1]/table[4]/tr/td[@valign=\"top\"]/a[@class=\"content_lt_blue_link\"]')\n url = tree.xpath('//td[1]/table[4]/tr/td[@valign=\"top\"]/a/@href')\n time = tree.xpath('//td[1]/table[4]/tr/td[@valign=\"top\"]/font[@class=\"q_datetime_grey\"]')\n\n for x in range(0, len(title)):\n news_dict = {\"article_id\": re.search(\"(?<==)(\\d+)\", str(url[x])).group(1), 'category': \"滾動新聞\",\n 'title': title[x].text, 'url': self.baseURL + url[x], 'time': time[x].text}\n l.append(news_dict)\n print(news_dict)\n self.parse_title_count += 1\n return l\n\n async def getNewsArticle(self, start_id, end_id):\n tasks = []\n sem = asyncio.Semaphore(300)\n async with aiohttp.ClientSession() as session:\n for id in range(start_id, end_id):\n fullURL = self.news_article_baseURL + str(id)\n task = asyncio.ensure_future(self.issue_call(self.loop, session, sem, self.parse_news_article, fullURL))\n tasks.append(task)\n responses = await asyncio.gather(*tasks)\n return responses\n\n async def getNewsArticle(self, l):\n tasks = []\n sem = asyncio.Semaphore(300)\n async with aiohttp.ClientSession() as session:\n for id in l:\n fullURL = self.news_article_baseURL + str(id)\n task = asyncio.ensure_future(self.issue_call(self.loop, session, sem, self.parse_news_article, fullURL))\n tasks.append(task)\n responses = await asyncio.gather(*tasks)\n return responses\n\n async def parse_news_article(self, html_string, url):\n l = []\n # create xpath object\n tree = html.fromstring(html_string)\n\n title = tree.xpath('//table/tr/td/font[@class=\"headline\"]/text()')\n source = tree.xpath('//table[3]/tr/td/font[3]/text()')\n date = tree.xpath('//table[3]/tr/td/font[2]/text()')\n\n soup = BeautifulSoup(html_string, 'html.parser')\n # removed the undesired tag from the soup first\n unwanted = [x.extract() for x in soup.findAll(\"span\", attrs={\"class\": \"content\"})]\n # print(unwanted)\n content = soup.find(\"font\", attrs={\"id\": \"article_content\"}).findAll(text=True)\n news_article_dict = {\"title\": title, \"date\": date, \"url\": url, \"source\": source, \"content\": content}\n\n for key, value in news_article_dict.items():\n # do something with value\n newvalue = \"\".join(map(str, value)).strip().replace(\"\\n\", \"\").replace(\"\\xa0\", \"\")\n news_article_dict[key] = newvalue\n\n l.append(news_article_dict)\n return l\n\n # The main loop -> run method\n def news_list_run(self, min, max):\n self.start_id = min\n self.end_id = max\n self.total_url_num = max - min\n future = asyncio.ensure_future(self.getNewsList(min, max))\n self.loop.run_until_complete(future)\n self.loop.close()\n # Last block of the logic, serialize the output with text file\n persist().save_to_json(self.public_news_title_list, \"document/\", \"news_title\")\n persist().save_to_json(self.create_report, \"log/\", \"report\")\n return future\n\n # The main loop -> run method\n def news_article_run(self, min, max):\n self.start_id = min\n self.end_id = max\n self.total_url_num = max - min\n\n future = asyncio.ensure_future(self.getNewsArticle(min, max))\n self.loop.run_until_complete(future)\n self.loop.close()\n # Last block of the logic, serialize the output with text file\n persist().save_to_json(self.public_news_title_list, \"document/\", \"news_articles\")\n persist().save_to_json(self.create_report, \"log/\", \"report\")\n return future\n\n # The main loop -> run method\n def news_article_run(self, l):\n self.start_id = l[0]\n self.end_id = l[-1]\n self.total_url_num = len(l) + 1\n\n future = asyncio.ensure_future(self.getNewsArticle(l))\n self.loop.run_until_complete(future)\n self.loop.close()\n # Last block of the logic, serialize the output with text file\n persist().save_to_json(self.public_news_title_list, \"document/\", \"news_articles\")\n persist().save_to_json(self.create_report(), \"log/\", \"report\")\n return future\n\n def create_report(self):\n report_dict = {\n \"start_id\": self.start_id,\n \"end_id\": self.end_id,\n \"total_url_to_parse\": self.total_url_num,\n \"url_failed\": self.url_not_parsed,\n \"page_failed\": len(self.url_not_parsed),\n \"success_rate\": (self.total_url_num - len(self.url_not_parsed)) / self.total_url_num,\n }\n\n return dict(report_dict)\n","sub_path":"QuamnetNewsScrapper.py","file_name":"QuamnetNewsScrapper.py","file_ext":"py","file_size_in_byte":7847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"81738837","text":"from django.db import models\n\nfrom stream_field import blocks\nfrom stream_field.blocks import admin_block\nfrom stream_field.fields import StreamField\n\n\nclass ChooseableModel(models.Model):\n text = models.TextField()\n\n\nclass StreamFieldModel(models.Model):\n\n body = StreamField([\n ('chooser', admin_block.ForeignKeyChooserBlock(ChooseableModel)),\n ('text', blocks.CharBlock()),\n ('List', blocks.ListBlock(blocks.URLBlock())),\n ('DateTime', blocks.DateTimeBlock()),\n ('Person', blocks.StructBlock([\n ('first_name', blocks.CharBlock()),\n ('last_name', blocks.CharBlock()),\n ('date_of_birth', blocks.DateBlock()),\n ('bio', blocks.TextBlock()),\n ])),\n ])\n","sub_path":"example/exampleapp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"183918464","text":"\"Implements various metrics to measure training accuracy\"\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom sklearn.isotonic import IsotonicRegression\n\n\ndef isotonic(input_data, quantile_list):\n quantile_list = np.array(quantile_list).reshape(-1)\n batch_size = input_data.shape[0]\n new_output_data = []\n for i in range(batch_size):\n new_output_data.append(IsotonicRegression().fit_transform(quantile_list, input_data[i]))\n return np.stack(new_output_data, 0)\n\n\nclass HuberPinballLoss(nn.Module):\n __name__ = 'huber_pinball_loss'\n\n def __init__(self, quantile_levels, alpha=0.01):\n super(HuberPinballLoss, self).__init__()\n self.quantile_levels = torch.Tensor(quantile_levels).contiguous().reshape(1, -1)\n self.alpha = alpha\n\n def forward(self, predict_data, target_data):\n target_data = target_data.contiguous().reshape(-1, 1)\n batch_size = target_data.size()[0]\n predict_data = predict_data.contiguous().reshape(batch_size, -1)\n\n error_data = target_data - predict_data\n loss_data = torch.where(torch.abs(error_data) < self.alpha,\n 0.5 * error_data * error_data,\n self.alpha * (torch.abs(error_data) - 0.5 * self.alpha))\n loss_data = loss_data / self.alpha\n\n scale = torch.where(error_data >= 0,\n torch.ones_like(error_data) * self.quantile_levels,\n torch.ones_like(error_data) * (1 - self.quantile_levels))\n loss_data *= scale\n return loss_data.mean()\n\n\nclass PinballLoss(nn.Module):\n __name__ = 'pinball_loss'\n\n def __init__(self, quantile_levels):\n super(PinballLoss, self).__init__()\n if quantile_levels is None:\n self.quantile_levels = None\n else:\n self.quantile_levels = torch.Tensor(quantile_levels).contiguous().reshape(1, -1)\n\n def forward(self, predict_data, target_data):\n # compute error (batch_size x num_quantiles)\n target_data = target_data.contiguous().reshape(-1, 1)\n error_data = target_data - predict_data\n\n # compute pinball loss\n loss_data = torch.max(self.quantile_levels * error_data, (self.quantile_levels - 1) * error_data)\n\n # mean over samples (num_quantiles)\n return loss_data.mean()\n","sub_path":"tabular/src/autogluon/tabular/models/fastainn/quantile_helpers.py","file_name":"quantile_helpers.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"87088707","text":"from django.contrib import admin\nfrom django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('/', views.detail, name = \"detail\"),\n path('create', views.create, name = \"create\"),\n path('new/', views.new, name = \"new\"),\n path('newblog/', views.blogpost, name = \"newblog\"),\n path('blog/', views.blog, name = \"blog\"),\n path('plus/', views.plus, name = \"plus\"),\n path('search/', views.search, name = \"search\"),\n]","sub_path":"firstblog/blog1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"574776427","text":"from t2v_common import *\nimport requests,random\nfrom bs4 import BeautifulSoup\n\nDATE_RANGE_STR = '20180101_31' #'20171219_31' #'20180401_17' #'20180301_31' #'20180201_28' #\n\nDATA_DIR = '../twtrstyle' #'/Volumes/JYPENG-HD3/trendmicro/twtrstyle' #\nTWEETS_FILENAME = \"%s/tweets/tweets_%%s.gz\" % DATA_DIR\nUSERMAP_FILENAME = \"%s/usermap/usermap_%%s.gz\" % DATA_DIR\nUSERFILT_FILENAME = \"%s/userfilt/userfilt_%%s.gz\" % DATA_DIR\n\ndt_range = date_range_from_str(DATE_RANGE_STR,'d')\n\n#-----------------------------#\n#-- Collect Experiment Data --#\n#-----------------------------#\nstats = pd.DataFrame(columns=('orig_tweets','orig_users','filt_tweets','filt_users'))\ncounts = None\nfor dt in dt_range.strftime('%Y%m%d'):\n print(dt)\n #\n counts_dt = None\n for datehour in date_range_from_str(dt,'H').strftime('%Y%m%d%H'):\n t = read_prep(TWEETS_FILENAME % datehour,usecols=['id','created_at','text','truncated','has_media','user_id','interaction_24hr'])\n # u = read_prep(USERMAP_FILENAME % datehour)\n #\n # t['screen_name'] = u.loc[t.user_id,'screen_name'].values\n #\n c = t.groupby('user_id').interaction_24hr.agg(['count','sum']).rename(columns={'count':'N','sum':'c'})\n counts_dt = c if counts_dt is None else counts_dt.add(c,fill_value=0)\n #\n counts_dt['nc'] = counts_dt.c/counts_dt.N\n #\n mask = (counts_dt.N<=10) & (counts_dt.nc>=30)\n stats.loc[dt,'orig_tweets'] = counts_dt.N.sum()\n stats.loc[dt,'orig_users'] = len(counts_dt)\n stats.loc[dt,'filt_tweets'] = counts_dt[mask].N.sum()\n stats.loc[dt,'filt_users'] = len(counts_dt[mask])\n print(\" Original:\\n\\t%(orig_tweets)d Tweets\\n\\t%(orig_users)d Users\\n Filtered:\\n\\t%(filt_tweets)d Tweets\\n\\t%(filt_users)d Users\" % \n stats.loc[dt])\n #\n counts = counts_dt[['N','c']] if counts is None else counts.add(counts_dt[['N','c']],fill_value=0)\n\ncounts['nc'] = counts.c/counts.N\nmask = (counts.N<=10*len(dt_range)) & (counts.nc>100)\nstats.loc[DATE_RANGE_STR,'orig_tweets'] = counts.N.sum()\nstats.loc[DATE_RANGE_STR,'orig_users'] = len(counts)\nstats.loc[DATE_RANGE_STR,'filt_tweets'] = counts[mask].N.sum()\nstats.loc[DATE_RANGE_STR,'filt_users'] = len(counts[mask])\ncounts[['N','c']].astype(int).to_csv(USERFILT_FILENAME % DATE_RANGE_STR,compression='gzip')\n","sub_path":"t2v_expt_user.py","file_name":"t2v_expt_user.py","file_ext":"py","file_size_in_byte":2330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"494125593","text":"# Libraries Import\nimport os\nimport pickle\nfrom datetime import datetime\nimport argparse\nimport matplotlib.pyplot as plt\nimport autograd.numpy as np\nimport sys\nimport shutil\nimport math\nimport random\nimport pickle\n\nimport data\nimport model\nfrom scipy.linalg import subspace_angles\nimport math\n\nfrom tqdm import tqdm\n\nimport torch\nfrom pyfiglet import Figlet\n\n\nos.system('clear')\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=FutureWarning)\n\nprint(\"===============================================================================================\")\nf = Figlet(font='thin')\nprint(f.renderText('Invariance Baseline'))\nprint(\":::: Code by Adepu Ravi Shankar & Rahul-Vigneswaran K 2019 ::::\")\nprint(\"===============================================================================================\\n\")\n\n\n# Initialize Variables\n\nprev_hess = 0\nprev_eigval = 0\nprev_eigvec = 0\ninitial_model = []\n\nparser = argparse.ArgumentParser()\n # Hessian\nparser.add_argument('--top', type=int, default= 100,\n help='Dimension of the top eigenspace')\nparser.add_argument('--suffix', type=str, default='new',\n help='suffix to save npy array')\nparser.add_argument('--freq', type=int, default='1',\n help='freq of Hess calculation')\n\n\n# Data Generation\nparser.add_argument('--data-type', type=str, choices=['blob', 'circle', 'moon'], default='blob',\n help='Type of random data generation pattern.')\nparser.add_argument('--num-samples', type=int, default=1000,\n help='Number of training samples')\nparser.add_argument('--input-dim', type=int, default=5,\n help='Dimension of the input space')\nparser.add_argument('--num-classes', type=int, default=2,\n help='Number of classes in generated data. '\n 'Taken into account only by classifiers and data generators that support multi-class')\nparser.add_argument('--cov-factor', type=float, default=1.,\n help='Multiplier for the covariance of the data')\nparser.add_argument('--data-seed', type=int, default=None,\n help='Seed for random number generation of data generators')\n\n# Model\nparser.add_argument('--classifier', type=str, choices=['logreg', 'fullconn'], default='fullconn',\n help='Type of classifier. Logistic Regression, Fully-Connected NN.')\nparser.add_argument('--layer-sizes', nargs='*', type=int, default=[10, 5],\n help='Number of units in hidden layers. '\n 'First layer will have --input-dim units. Last layer will have --num-classes units.')\n\n# Training\nparser.add_argument('--batch-size', type=int, default=0,\n help='Number of samples in a training batch. '\n '0 means whole dataset')\nparser.add_argument('--learning-rate', type=float, default=0.01,\n help='Learning rate')\nparser.add_argument('--stopping-grad-norm', type=float, default=1e-4,\n help='Stop training if grad_norm becomes smaller than this threshold')\nparser.add_argument('--max-iterations', type=int, default=100,\n help='Cancel training after maximum number of iteration steps')\n\n# Results\nparser.add_argument('--hessian-calc-period', type=int, default=1,\n help='Calculate hessian at every N iteration. '\n '0 means do not calculate at intermediate iterations.')\nparser.add_argument('--results-folder', type=str, default='/home/ravi/eclipse-workspace/saguant/hessian-for-basicDL/hessianexps/results',\n help='Folder in which to put all results folders')\nparser.add_argument('--experiment-folder', type=str, default='defaults',\n help='Folder in which to write results files')\n\n# Hessian analysis\nparser.add_argument('--top-evals', type=int, default=100,\n help='Find top k evals')\nparser.add_argument('--bottom-evals', type=int, default=0,\n help='Find bottom k evals')\n\nargs = parser.parse_args()\n#args.layer_sizes = np.array(args.layer_sizes)\n\ndef yes_or_no() :\n while True:\n yes = {'yes','y', 'ye', ''}\n no = {'no','n'}\n\n choice = raw_input(\"Do you want me to delete the directory? (y/n) \\n\\n\").lower()\n if choice in yes:\n return True\n elif choice in no:\n return False\n else:\n sys.stdout.write(\"\\nPlease respond with 'yes' or 'no' \\n\\n\")\n\ndef yes_or_no_image():\n while True:\n yes = {'yes', 'y', 'ye', ''}\n no = {'no', 'n'}\n\n choice = raw_input(\n \"Do you want to see the plot? (y/n) \\n\\n\").lower()\n if choice in yes:\n return True\n elif choice in no:\n return False\n else:\n sys.stdout.write(\"\\nPlease respond with 'yes' or 'no' \\n\\n\")\n\n\nargs.results_folder = os.getcwd() + '/' +'results/' + 'baseline/' +'B_size-'+str(args.batch_size)+'-Arch-'+str(args.input_dim)+str(args.layer_sizes)+'-iters-'+str(args.max_iterations)+'-data-'+str(args.data_type)+'-hess_freq-'+str(args.hessian_calc_period)+'-top-'+str(args.top)+'--freq-'+str(args.freq)+'--iter-'+str(args.max_iterations)\nif not os.path.exists(args.results_folder):\n os.mkdir(args.results_folder)\nelse: \n print(\"\\nDirectory already exists !!\\n\")\n a1 = yes_or_no()\n if a1 == True :\n shutil.rmtree(args.results_folder, ignore_errors=True) # Prompt to delete directory if it already exists\n print(\"====> Directory Deleted\")\n os.mkdir(args.results_folder)\n print(\"====> Directory recreated\\n\")\n print(\"===============================================================================================\\n\")\n\n\n else:\n print (\"Directory Already exists and was not opted for deletion.\\n\\n\")\n sys.exit()\n \nif args.classifier == 'logreg' and args.data_type == 'blob' and args.num_classes != 2:\n raise Exception('LogReg for more than 2 classes is not implemented yet.')\n\n\ndef main():\n inputs_train, targets_train, inputs_test, targets_test = data.generate_data(args)\n results = {\n 'inputs_train': inputs_train,\n 'targets_train': targets_train,\n 'inputs_test': inputs_test,\n 'targets_test': targets_test\n }\n \n mdl = model.create_model(args, inputs_train, targets_train) # Actual Model that is being observed\n mdl_test = model.create_model(args, inputs_train, targets_train) # Dummy Model for calculating gradient\n train_model(args, mdl, mdl_test, results)\n\n\ndef train_model(args, mdl, mdl_test, results):\n coeff = []\n ang_sb=[]\n ang_np=[]\n p_angles = []\n all_w=[]\n results['args'] = args\n loss=[]\n\n init_loss = mdl.loss(mdl.params_flat)\n init_grad_norm = np.linalg.norm(mdl.gradient(mdl.params_flat))\n print(\"\\n===============================================================================================\\n\")\n\n print('Initial loss: {}, norm grad: {}\\n'.format(init_loss, init_grad_norm))\n results['init_full_loss'] = init_loss\n results['init_full_grad_norm'] = init_grad_norm\n\n results['history1'] = []\n results['history1_columns'] = ['iter_no', 'batch_loss', 'batch_grad_norm', 'batch_param_norm']\n results['history2'] = []\n results['history2_columns'] = ['full_hessian', 'full_hessian_evals']\n\n for iter_no in tqdm(range(args.max_iterations), desc=\"Training Progress\", dynamic_ncols=True):\n inputs, targets = get_batch_samples(iter_no, args, mdl)\n batch_loss = mdl.loss(mdl.params_flat, inputs, targets)\n batch_grad = mdl.gradient(mdl.params_flat, inputs, targets)\n batch_grad_norm = np.linalg.norm(batch_grad)\n batch_param_norm = np.linalg.norm(mdl.params_flat)\n\n if iter_no % args.freq == 0:\n\n # calculating hessian\n hess = mdl.hessian(mdl.params_flat) # Calculating Hessian\n hess = torch.tensor(hess).float() # Converting the Hessian to Tensor\n eigenvalues, eigenvec = torch.symeig(hess,eigenvectors=True) # Extracting the eigenvalues and Eigen Vectors from the Calculated Hessian\n \n if iter_no == 0:\n prev_hess = hess\n prev_eigval = eigenvalues\n prev_eigvec = eigenvec\n \n top = args.top # This decides how many top eigenvectors are considered\n dom = eigenvec[:,-top:] # |The reason for negative top :: torch.symeig outputs eigen vectors in the increasing order and as a result |\n # | the top (maximum) eigenvectors will be atlast. |\n dom = dom.float()\n alpha=torch.rand(top) # A random vector which is of the dim of variable \"top\" is being initialized\n\n # Finding the top vector\n vec=(alpha*dom.float()).sum(1) # Representing alpha onto dominant eigen vector\n vec=vec/torch.sqrt((vec*vec).sum()) # Normalization of top vector\n# vec = vec*5\n\n # Finding gradient at top vec using Dummy network.\n mdl_test.params_flat = np.array(vec)\n \n \n batch_grad_mdl_test = mdl_test.gradient(mdl_test.params_flat, inputs, targets)\n mdl_test.params_flat -= batch_grad_mdl_test * args.learning_rate\n\n # Find coeff and append. But why do we need to find the coeffs ? \n c = torch.mv(hess.transpose(0,1), torch.tensor(mdl_test.params_flat).float())\n if np.size(coeff) == 0:\n coeff = c.detach().cpu().numpy()\n coeff = np.expand_dims(coeff, axis=0)\n else:\n coeff = np.concatenate((coeff,np.expand_dims(c.detach().cpu().numpy(),axis=0)),0) \n\n#\tStatistics of subspaces, (1) Angle between top subpaces\n eigenvalues_prev, eigenvec_prev = torch.symeig(prev_hess, eigenvectors = True)\n dom_prev = eigenvec_prev[:,-top:] # Is it not the same as the variable \"dom\" that was calculated earlier ?\n # calculation 1 norm, which is nothing but angle between subspaces\n ang=np.linalg.norm(torch.mm(dom_prev, dom.transpose(0,1)).numpy(),1)\n ang_sb.append(ang)\n ang = np.rad2deg(subspace_angles(dom_prev, dom))\n ang_np.append(ang)\n# Calculating principal angles\n u,s,v =torch.svd(torch.mm(dom.transpose(0, 1), dom_prev))\n # Output in radians\n s = torch.acos(torch.clamp(s,min=-1,max=1))\n s = s*180/math.pi\n# Attach 's' to p_angles\n if np.size(p_angles) == 0:\n p_angles = s.detach().cpu().numpy()\n p_angles = np.expand_dims(p_angles, axis=0)\n else:\n p_angles = np.concatenate((p_angles,np.expand_dims(s.detach().cpu().numpy(),axis=0)),0) \n prev_hess = hess\n prev_eigval = eigenvalues\n prev_eigvec = eigenvec\n\n# saving weights in all iterations\n if batch_grad_norm <= args.stopping_grad_norm:\n break\n mdl.params_flat -= batch_grad * args.learning_rate\n #print(mdl.params_flat)\n all_w.append(np.power(math.e,mdl.params_flat))\n # print('{:06d} {} loss: {:.8f}, norm grad: {:.8f}'.format(iter_no, datetime.now(), batch_loss, batch_grad_norm))\n loss.append(batch_loss)\n final_loss = mdl.loss(mdl.params_flat)\n final_grad_norm = np.linalg.norm(mdl.gradient(mdl.params_flat))\n print('\\nFinal loss: {}, norm grad: {}'.format(final_loss, final_grad_norm))\n args.suffix=args.results_folder+'/coeff.npy'\n np.save(args.suffix,coeff)\n args.suffix=args.results_folder+'/ang_sb.npy'\n np.save(args.suffix,ang_sb)\n args.suffix=args.results_folder+'/ang_np.npy'\n np.save(args.suffix,ang_np) \n args.suffix=args.results_folder+'/p_angles.npy'\n np.save(args.suffix,p_angles) \n args.suffix=args.results_folder+'/all_weights.npy'\n np.save(args.suffix,np.array(all_w))\n \n \n\n# Saving png plots\n coeff = torch.tensor(coeff)\n for i in range(coeff.shape[0]):\n a=torch.zeros(coeff[i].shape[0]).long()\n b=torch.arange(0, coeff[i].shape[0])\n c=torch.where(((coeff[i] > -0.1) & (coeff[i] < 0.1)),b,a)\n z = torch.zeros(coeff[i].shape[0]).fill_(0)\n z[torch.nonzero(c)] = coeff[i][torch.nonzero(c)]\n z = np.array(z)\n plt.plot(z)\n plt.xlabel('Dimension', fontsize=14)\n plt.ylabel('Coefficient', fontsize=14)\n pnpy = args.results_folder+'/plot1'\n plt.savefig(pnpy, format='png', pad_inches=5)\n\n\n return args.results_folder\n\n\ndef get_batch_samples(iter_no, args, mdl):\n \"\"\"Return inputs and outputs belonging to batch given iteration number.\"\"\"\n if args.batch_size == 0:\n return None, None\n\n num_batches = int(np.ceil(len(mdl.inputs) / args.batch_size))\n mod_iter_no = iter_no % num_batches\n start = mod_iter_no * args.batch_size\n end = (mod_iter_no + 1) * args.batch_size\n inputs = mdl.inputs[start:end]\n targets = mdl.targets[start:end]\n return inputs, targets\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n args.results_folder = main()\n print(\"\\n\\n The code has been successfully executed!!\\n\\n\")\n #a11 = yes_or_no_image()\n #if a11 == True :\n # pnpy = str(args.results_folder) + '/plot1' + '.png'\n # import cv2 \n # img = cv2.imread(pnpy) \n # cv2.imshow('Plot', img) \n # cv2.waitKey(0) \n # cv2.destroyAllWindows() \n # print(\"\\n\\n Tata!!\\n\\n\")\n #else:\n # print(\"\\n\\n Tata!!\\n\\n\")\n # \n print(\"\\n===============================================================================================\\n\")\n","sub_path":"baseline.py","file_name":"baseline.py","file_ext":"py","file_size_in_byte":13835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"250612570","text":"\"\"\"\nLandon Buell\nNeural-Network-Projects-with-Python\nChapter 01 - Creating Neural Networks with Keras\n6 June 2021\n\"\"\"\n\n #### IMPORTS ####\n\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import SGD\n\n #### MAIN EXECUTABLE ####\n\nif __name__ == \"__main__\":\n\n # Create and model, and add a few layers\n model = Sequential(name=\"my_model\")\n model.add(Dense(units=4,activation='sigmoid',input_dim=3)) # layer 1\n model.add(Dense(units=1,activation='sigmoid')) # output layer\n\n # Get a summary of the model\n print(model.summary())\n print(\"\")\n \n # Compile w/ Optimizer & \n sgd = SGD(learning_rate=1)\n model.compile(optimizer=sgd,loss='mean_squared_error')\n\n # Genrate a Data Set\n np.random.seed(9)\n X = np.array([[0,0,1],\n [0,1,1],\n [1,0,1],\n [1,1,1]])\n Y = np.array([[0],[1],[1],[0]])\n\n # Train for 1500 iterations\n model.fit(X,Y,epochs=1500,verbose=1)\n\n # Get predictions\n print(model.predict(X))\n print(\"\")\n\n","sub_path":"Chapter01/KerasIntro.py","file_name":"KerasIntro.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"180463813","text":"\"\"\"\ncreated by nzh\nDate: 2018/9/21 上午11:00\n\"\"\"\n\n# 创建数组\n# 1. []\nlist1 = []\n\n# 2. list(iteralbe)\n# 给list函数传入一个可迭代变量,iterable可以是str,list,dict,set, tuple\n# 如果传入dict,那么dict的所有key会被提取到数组中\nlist2 = list(set((1, 2, 3)))\nlist2 = list({'a': 1, 'b': 2}) # output: ['a', 'b']\nlist2 = list('abc')\nlist2 = list((1,2,3))\n\n# 3. 列表生成式\nlist3 = [i for i in 'abc']\n# 列表生成式还可以加入筛选条件,比如过滤掉了'a'和'c'\nlist3 = [i for i in 'abc' if i not in ['a', 'c']]\n\n\n# 创建二维数组\nlist4 = ['a'] * 3 # output: ['a', 'a', 'a']\nlist4 = [{'a': 1, 'b': 2}] * 3 # output: [{'a': 1, 'b': 2}, {'a': 1, 'b': 2}, {'a': 1, 'b': 2}]\nlist4 = [[]] * 3 # output: [[], [], []]\n# 由于内部的[]会被浅赋值,所以当修改其中一个元素时,其他[]也会被修改。\nlist4[0].append(3) # output: [[3], [3], [3]]\n# 可以使用列表生成式\n# for循环表示迭代的次数,[]表示生成的结果\nlist4 = [[] for i in range(3)]\nlist4[0].append(1)\nlist4[1].append([1,3])\n\nlist4 = [[0] * 3 for i in range(4)] #output: [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]\nlist4[1].remove(0)\n\n\n###################################################\n# 查看python列表的内置函数\nbuilt_in_function_list = dir(list)\nprint(built_in_function_list)\n\n\n# 1. append,在list的末尾添加一个元素\n# append函数的返回值是None,函数会直接改变list的值\nlist5 = [1, 2, 3]\nappended_list = list5.append(4)\n# print(list5) # output: [1, 2, 3, 4]\n# print(appended_list) # output: None\n\n\n# 2. clear,清空list\n# clear函数的返回值���None\nclear_list = list5.clear()\n# print(list5) # output: []\n# print(clear_list) # output: None\n\n\n# 3. copy,对list进行浅复制\nlist6 = [{'a': 2}, 3, '4', 5.1234, [7, 7, 8]]\nshadow_copy = list6.copy()\n# print(list6) # output: [{'a': 2}, 3, '4', 5.1234, [7, 7, 8]]\nshadow_copy.append(9)\nshadow_copy[0] = 1\n# print(shadow_copy) # output: [1, 3, '4', 5.1234, [7, 7, 8], 9]\nshadow_copy[4].append(10)\n# print(shadow_copy) # output: [1, 3, '4', 5.1234, [7, 7, 8, 10], 9]\n\n\n# count,计算list中某个元素出现的次数\n# 传入一个值,返回list中这个值的个数\nlist7 = [[1] * 3, [2] * 2, [1], [1], [1] * 3]\n# print(list7) # output: [[1, 1, 1], [2, 2], [1], [1], [1, 1, 1]]\n# print(list7[0].count(1)) # output: 3\n\n\n# extend(iterable),扩展列表\n# extend接受一个可迭代对象,并将可迭代对象的每一个元素依次添加到list中\n# 如果iterable是dict,那么会依次添加dict的key到list中\nlist8 = [1, 2, 3, 4]\nlist8.append('abc')\n# print(list8) # output: [1, 2, 3, 4, 'abc']\nlist8.extend(['def'])\n# print(list8) # output: [1, 2, 3, 4, 'abc', 'def']\nlist8.extend('ipo')\n# print(list8) # output: [1, 2, 3, 4, 'abc', 'def', 'i', 'p', 'o']\nlist8.extend({'name': 'nzh', 'age': 18})\n# print(list8) # output: [1, 2, 3, 4, 'abc', 'def', 'i', 'p', 'o', 'name', 'age']\n\n\n# index(element, start, stop),返回element在list中的索引\nlist9 = [1, 2, 3, 4]\nindex = list9.index(4)\n# index函数还有其他参数start和end,用来指定索引的搜索范围\n# 包括start索引,但是不包括end索引,区间是左闭右开\n# 如果没有找到element,就会引发ValueError异常,提示:element is not in list\nlist10 = [1, 2, 3, 5, 4, 3, 2, 4, 1]\nindex = list10.index(1, 7, len(list10))\n# print(len(list10))\n# print(index) # output: 8\n\n\n# insert,在指定索引的地方添加元素,返回插入element之后的list\nlist11 = [1, 2, 3, 4, 5, 6, 7]\nlist11.insert(3, 100)\n# print(list11) # output: [1, 2, 3, 100, 4, 5, 6, 7]\n\n\n# pop(index),弹出指定索引处的元素\n# 从list11中弹出最后一个元素\nlist11.pop(-1)\n# print(list11) # output: [1, 2, 3, 100, 4, 5, 6]\n\n\n# remove(value), 删除指定的元素\n# 函数返回None\nlist11.remove(1)\n# print(list11) # output: [2, 3, 100, 4, 5, 6]\n# 当列表中有多个重复元素value时,删除第一个value\nlist12 = [1, 2, 1, 1]\nlist12.remove(1)\n# print(list12) # output: [2, 1, 1]\n# 当删除一个不存在的value时,抛出ValueError异常,提示x not in list\n# list12.remove(4) # raise Exception: ValueError\n\n\n# reverse(),颠倒list中的元素\n# 改变原始list,返回None\nlist13 = [1, 2, 3, 4]\nlist13.reverse()\n\n# 其他逆转list的方法\n# 比如内置的reversed(list)函数,会return一个list_reverseiterator类型的对象\n# 可以使用for或者列表生成式,再或者list()来生成一个新的list\n# print([i for i in reversed(list13)]) # output: [1, 2, 3, 4]\n# print(reversed(list13)) # output: \n# print(list(reversed(list13))) # output: [1, 2, 3, 4]\n\n# 除了上述操作,使用list的切片属性也能完成list反转\n# print(list13[::-1]) # output: [1, 2, 3, 4]\n\n\n# sort(),对list按照升序排序\nlist14 = [1, 3, 2, 1, 5, 4]\nlist14.sort()\n# print(list14) # output: [1, 1, 2, 3, 4, 5]\n# 降序排序\nlist14.sort(reverse=True)\n# print(list14) # output: [5, 4, 3, 2, 1, 1]","sub_path":"list_prictise/basic_use.py","file_name":"basic_use.py","file_ext":"py","file_size_in_byte":5124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"255033218","text":"# Write a function that accepts two positive integers as parameters. The first integer is the number of heads and the\n# second integer is the number of legs of all the creatures in a farm which consists of chickens and dogs.\n# Your function should calculate and return the number of chickens and number of dogs in the farm in a list as specified\n# below. If it is impossible to determine the correct number of chickens and dogs with the given information\n# then your function should return None.\n# your function should return a list that contains two numbers in this order [number_of_chickens, number_of_dogs]\ndef farm (heads, legs):\n #Check if it is at least 2 legs per heads\n if heads >= legs/ 2:\n return None\n elif legs % 2 != 0:\n return None\n\n chicken = 0\n dog = 0\n dogDiff = 0\n\n twoLegs = legs / 2\n if twoLegs > heads:\n dogDiff = twoLegs - heads\n dog = dogDiff\n chicken = (legs - (dogDiff * 4))/2\n\n return [dog, chicken]\n\nprint(farm(5, 12))","sub_path":"CSE1309x/chickenDogs.py","file_name":"chickenDogs.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"211466123","text":"# DFS\n# 20200811\n\ndef dfs(v): # v : 각 노��\n global curr_time\n mark[v] = 'visited'\n print(v, end=' ')\n\n pre[v] = curr_time\n curr_time += 1\n\n for i in edge:\n if v in i:\n if i[0] == v:\n if mark[i[1]]=='unvisited':\n parent[i[1]] = v\n #print(i[1])\n dfs(i[1])\n else:\n if mark[i[0]]=='unvisited':\n parent[i[0]] = v\n #print(i[0])\n dfs(i[0])\n post[v] = curr_time\n curr_time += 1\n\n \n\ndef dfsAll(G): # G = [1,2,3,4]\n for node in G:\n if mark[node] == 'unvisited':\n dfs(node)\n\n print()\n print(pre)\n print(post)\n\n \n\n\n\nN,M,V = input().split()\nN,M,V = int(N),int(M),int(V)\nedge = []\nnode = [i for i in range(1,N+1)] # node = [1,2,3,4]\nparent = [0]*(N+1) # parend = [0,0,0,0,0] \nmark = ['unvisited']*(N+1) # mark = ['unvisited','unvisited','unvisited'...]\nfor _ in range(M):\n edge.append(tuple(map(int,input().split())))\n\nedge.sort()\n\npre = [0]*(N+1)\npost = [0]*(N+1)\nglobal curr_time\ncurr_time = 1\n\ndfsAll(node)\n","sub_path":"DFS_goorm.py","file_name":"DFS_goorm.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"131466898","text":"import os\n\nif __name__ == \"__main__\":\n path_to_settings = os.path.join(os.path.expanduser(\"~\"), \"Documents\\Paradox Interactive\\Stellaris\\settings.txt\")\n while not os.path.exists(path_to_settings):\n print(\"Please print path to the Documents folder: \", end='')\n path_to_settings = os.path.join(input(), \"Paradox Interactive\\Stellaris\\settings.txt\")\n\n mod_list = []\n with open(path_to_settings, 'r') as file:\n mod_lines = False\n for line in file:\n if line == \"last_mods={\\n\":\n mod_lines = True\n continue\n if line == \"}\\n\" and mod_lines: # the closing bracket\n break\n if mod_lines:\n mod_list.append(line.split('_')[-1].split('.')[0])\n file.close()\n\n with open(\"master_mod_list.txt\", 'w') as file:\n for mod in mod_list:\n file.write(\"{}\\n\".format(mod))\n file.close()","sub_path":"PycharmProjects/Stellaris/StellarisModSynchronaizerMaster.py","file_name":"StellarisModSynchronaizerMaster.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"123669356","text":"import requests\nfrom flask import render_template, Blueprint, current_app, request\n\nfrom sqlalchemy import func\n\nfrom labmanager.db import db\nfrom labmanager.models import UseLog\n\nstats_blueprint = Blueprint('stats', __name__)\n\n@stats_blueprint.before_request\ndef check_auth():\n key = request.args.get(\"key\")\n if not key:\n return \"key missing\"\n\n if key != current_app.config.get(\"EASYADMIN_KEY\"):\n return \"Invalid key\"\n return\n\n@stats_blueprint.route(\"/\")\ndef simple():\n by_day = sorted(db.session.query(func.count(\"*\"), UseLog.date).group_by(UseLog.date).all(), lambda x, y: cmp(x[1], y[1]))\n return render_template(\"stats/index.html\", by_day = by_day)\n\n@stats_blueprint.route(\"/monthly\")\ndef monthly():\n try:\n failure_data = requests.get(\"http://composer.golabz.eu/translator/stats/status.json\").json()\n except:\n failure_data = {\n 'failing': [],\n 'flash': [],\n 'ssl': [],\n }\n\n lab_contents = requests.get('http://www.golabz.eu/rest/labs/retrieve.json').json()\n lab_per_url = {\n # url: lab_data\n }\n for lab in lab_contents:\n for lab_app in lab['lab_apps']:\n lab_per_url[lab_app['app_url']] = lab\n\n month_results = [\n # {\n # 'year': year,\n # 'month': month,\n # 'count': count,\n # }\n ]\n monthly_summary = {\n # (year, month): count\n }\n for count, year, month in db.session.query(func.count(\"id\"), UseLog.year, UseLog.month).group_by(UseLog.year, UseLog.month).all():\n month_results.append({\n 'year': year,\n 'month': month,\n 'count': count\n })\n monthly_summary[year, month] = count\n month_results.sort(lambda x, y: cmp(x['year'], y['year']) or cmp(x['month'], y['month']), reverse=True)\n\n temporal_month_url = {\n # (year, month): [ { 'count': count, 'url': url ]\n }\n for count, year, month, url in db.session.query(func.count(\"id\"), UseLog.year, UseLog.month, UseLog.url).group_by(UseLog.year, UseLog.month, UseLog.url).all():\n if (year, month) not in temporal_month_url:\n temporal_month_url[year, month] = []\n\n temporal_month_url[year, month].append({\n 'count': count,\n 'url': url,\n 'data': lab_per_url.get(url, {})\n })\n temporal_month_url[year, month].sort(lambda x, y: cmp(x['count'], y['count']), reverse=True)\n\n month_url_results = [\n # {\n # 'year': year,\n # 'month': month,\n # 'urls': [\n # { # sorted > to min\n # 'count': count,\n # 'url': url\n # }\n # ]\n # }\n ]\n for (year, month), results in temporal_month_url.items():\n month_url_results.append({\n 'year': year,\n 'month': month,\n 'count': monthly_summary[year, month],\n 'urls': results,\n })\n\n month_url_results.sort(lambda x, y: cmp(x['year'], y['year']) or cmp(x['month'], y['month']), reverse=True)\n return render_template(\"stats/monthly.html\", month_results=month_results, month_url_results=month_url_results, failure_data=failure_data)\n\n\n","sub_path":"labmanager/views/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"377867446","text":"import streamlit as st\nimport numpy as np\nimport pandas as pd\npd.set_option('display.max_rows', None)\nimport pandas_datareader as dr\nfrom datetime import datetime\nfrom datetime import timedelta\nimport math\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import mean_squared_error\nfrom keras.models import Sequential\nfrom keras.layers import Dense, LSTM, GRU\nfrom keras.preprocessing.sequence import TimeseriesGenerator\nfrom keras import callbacks\n\n\ndef app():\n\n st.write(\"\"\"\n # Prediction\n Enter a stock, date range, and training parameters to train a prediction model to generate prediction curves on that stock.\n \"\"\")\n\n #Create a sidebar header\n st.sidebar.header('Training Parameters:')\n\n def get_input():\n with open('./stock symbols.csv', 'r', encoding='utf-8-sig') as stock_file:\n stock_list = pd.read_csv(stock_file)\n symbols = stock_list.iloc[:, 0]\n selected = st.selectbox(label=\"\", options=symbols)\n index = stock_list[stock_list['Symbol'] == selected].index.values\n stock_symbol = stock_list['Symbol'][index].to_string(index=False)\n company_name = stock_list['Name'][index].to_string(index=False)\n start_date = st.sidebar.date_input(\"Starting Date:\", value=(datetime.today() - timedelta(days=365*3)), min_value=datetime(1817, 3, 8), max_value=datetime.today())\n end_date = st.sidebar.date_input(\"Ending Date:\", min_value=datetime(1817, 3, 8), max_value=datetime.today())\n epochs = st.sidebar.text_input(\"Enter Number of Epochs:\", 100)\n lag = st.sidebar.text_input(\"Enter Time Series Lag:\", 30)\n steps = st.sidebar.text_input(\"Enter Training Steps:\", 100)\n days = st.sidebar.text_input(\"Enter Prediction Length in Days:\", 30)\n pullback = st.sidebar.text_input(\"Pullback (Used for experiments):\", 0)\n return start_date, end_date, stock_symbol.strip(), company_name, int(epochs), int(lag), int(steps), int(days), int(pullback)\n\n global RMSE\n start_date, end_date, stock_symbol, company_name, epochs, lag, steps, days, pullback = get_input()\n\n ###Load and shape data\n df = dr.DataReader(stock_symbol, data_source='yahoo', start=start_date, end=end_date)\n prices = df.reset_index()['Adj Close']\n scaler = MinMaxScaler(feature_range=(0,1))\n prices = scaler.fit_transform(np.array(prices).reshape(-1,1))\n\n ###Split data into training and testing sets\n training_size = int(len(prices)*.65)\n training_data = prices[0:training_size, :]\n test_data = prices[training_size:len(prices), :]\n\n\n ###function to create time series datasets\n def create_timeseries(data, lag):\n t_series = TimeseriesGenerator(data, data, length=lag, batch_size=len(data))\n for i in range(len(t_series)):\n x, y = t_series[i]\n return np.array(x), np.array(y)\n\n ###generate time series for training and test sets\n x_train, y_train = create_timeseries(training_data, lag)\n x_test, y_test = create_timeseries(test_data, lag)\n\n ###reshape data for LSTM which requires 3D data\n x_train = x_train.reshape(x_train.shape[0], x_train.shape[1], 1)\n x_test = x_test.reshape(x_test.shape[0], x_test.shape[1], 1)\n\n ###create stacked LSTM model\n model = Sequential()\n model.add(LSTM(50, return_sequences=True, input_shape=(100,1)))\n model.add(LSTM(50, return_sequences=True))\n model.add(LSTM(50))\n model.add(Dense(1))\n model.compile(loss='mean_squared_error', optimizer='adam')\n\n if st.button(\"Train Model\"):\n bar = st.progress(0)\n class Callback(callbacks.Callback):\n def on_epoch_end(self, epoch, logs=None):\n bar.progress(((epoch+1)/epochs))\n\n model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=epochs, batch_size=64, verbose=1, callbacks=[Callback()])\n\n ###run trained model on train and test data, get RMSE, undo scaling\n train_predict = model.predict(x_train)\n test_predict = model.predict(x_test)\n math.sqrt(mean_squared_error(y_train, train_predict))\n RMSE = math.sqrt(mean_squared_error(y_test, test_predict))\n train_predict = scaler.inverse_transform((train_predict))\n test_predict = scaler.inverse_transform((test_predict))\n\n\n ###Reformat data to be plotted\n prices = scaler.inverse_transform(prices)\n prices = np.array(prices).reshape(len(prices))\n train_predict = np.array(train_predict).reshape(len(train_predict))\n test_predict = np.array(test_predict).reshape(len(test_predict))\n\n\n ###Load data into single dataframe and plot\n global data_df\n data_df = pd.DataFrame(columns=['Prices', 'Training Predictions', 'Testing Predictions'])\n data_df['Prices'] = prices\n data_df['Training Predictions'][(lag - 5):len(train_predict) + (lag - 5)] = train_predict\n data_df['Testing Predictions'][len(train_predict) + ((lag*2)-5):len(test_predict) + len(train_predict) + ((lag*2)-5)] = test_predict\n\n st.header(company_name + \" Training Results from \" + str(start_date) + \" to \" + str(end_date) + \"\\n\")\n st.line_chart(data_df)\n st.text(\"Epochs used: \" + str(epochs))\n st.text(\"Steps: \" + str(steps))\n st.text(\"Training RMSE: \" + str(RMSE))\n\n if st.button(\"Run Predictions\"):\n ###Use all data to train for predictions\n data = prices[:]\n\n\n ###function to create time series datasets\n def create_timeseries(data, lag):\n t_series = TimeseriesGenerator(data, data, length=lag, batch_size=len(data))\n for i in range(len(t_series)):\n x, y = t_series[i]\n return np.array(x), np.array(y)\n\n ###generate time series for training and test sets\n x_train, y_train = create_timeseries(data, lag)\n\n ###reshape data for LSTM which requires 3D data\n x_train = x_train.reshape(x_train.shape[0], x_train.shape[1], 1)\n\n ###create stacked LSTM model\n model = Sequential()\n model.add(LSTM(50, return_sequences=True, input_shape=(100, 1)))\n model.add(LSTM(50, return_sequences=True))\n model.add(LSTM(50))\n model.add(Dense(1))\n model.compile(loss='mean_squared_error', optimizer='adam')\n\n bar = st.progress(0)\n\n class Callback(callbacks.Callback):\n def on_epoch_end(self, epoch, logs=None):\n bar.progress(((epoch + 1) / epochs))\n\n model.fit(x_train, y_train, epochs=epochs, batch_size=64, verbose=1,\n callbacks=[Callback()])\n\n\n ###Forecasting function takes number of steps (or lag days) to use to make prediction, and number of days to forecast out.\n def forecast(data, steps, days):\n n_steps = steps\n x_input = data[-steps:].reshape(1,-1)\n temp_input = list(x_input)\n temp_input=temp_input[0].tolist()\n lst_output = []\n i = 0\n while (i < days):\n\n if (len(temp_input) > n_steps):\n x_input = np.array(temp_input[1:])\n x_input = x_input.reshape(1, -1)\n x_input = x_input.reshape((1, n_steps, 1))\n yhat = model.predict(x_input, verbose=0)\n temp_input.extend(yhat[0].tolist())\n temp_input = temp_input[1:]\n lst_output.extend(yhat.tolist())\n i = i + 1\n else:\n x_input = x_input.reshape((1, n_steps, 1))\n yhat = model.predict(x_input, verbose=0)\n temp_input.extend(yhat[0].tolist())\n lst_output.extend(yhat.tolist())\n i = i + 1\n\n return lst_output\n lst_output = forecast(data[0:len(data)-pullback], steps, days)\n if(pullback != 0):\n prediction_RMSE = math.sqrt(mean_squared_error(data[len(data)-pullback:], lst_output))\n\n ###Convert data to dataframes and chart zoomed in view\n prices_df = pd.DataFrame(columns= ['Actual', 'Predictions'])\n prices_df['Actual'] = data_df['Prices']\n lst_output = scaler.inverse_transform(lst_output)\n lst_output = np.array(lst_output).reshape(len(lst_output))\n lst_output_df = pd.DataFrame(columns=['Actual','Predictions'])\n lst_output_df['Predictions'] = lst_output\n chart_df = pd.DataFrame(columns=['Actual', 'Predictions'])\n if(pullback == 0):\n chart_df = pd.concat([prices_df[['Actual', 'Predictions']], lst_output_df[['Actual', 'Predictions']]], ignore_index=True)\n else:\n chart_df['Actual'] = prices_df['Actual']\n chart_df['Predictions'] = np.nan\n chart_df['Predictions'][-pullback:] = lst_output_df['Predictions']\n\n st.header(company_name + \" Prediction (Zoomed In)\" + \" from \" + str(start_date) + \" to \" + str(end_date) + \" for \" + str(days) + \" days\\n\")\n st.line_chart(chart_df[-(steps+days):])\n\n ###Chart zoomed out view\n st.header(company_name + \" Prediction (Zoomed Out)\" + \" from \" + str(start_date) + \" to \" + str(end_date) + \" for \" + str(days) + \" days\\n\")\n st.line_chart(chart_df)\n st.text(\"Epochs: \" + str(epochs))\n st.text(\"Steps: \" + str(steps))\n if(pullback != 0):\n st.text(\"Prediction RMSE: \" + str(prediction_RMSE))\n\n\n\n\n\n\n\n\n\n","sub_path":"Prediction.py","file_name":"Prediction.py","file_ext":"py","file_size_in_byte":9428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"557684390","text":"# archives GIS job data into a .csv\n\nimport csv\nfrom time import strftime\nimport os\n\n\ndef jobs(c):\n try:\n c.execute('SELECT jobkey, jobtitle, lat, lng, city, state, formattedLocation, country from jobs_tbl;')\n\n locations = c.fetchall()\n\n locations_outfile = os.path.join('archived_data', 'jobs', strftime('%y%m%d_%H%M') + '.tsv')\n\n with open(locations_outfile, 'w') as csvfile:\n fieldnames = ['jobkey','jobtitle','lat', 'lng', 'city', 'state', 'location', 'country']\n writer = csv.DictWriter(csvfile, delimiter='\\t', fieldnames=fieldnames)\n writer.writeheader()\n for l in locations:\n writer.writerow({'jobkey': l[0], 'jobtitle': l[1], 'lat': l[2], 'lng': l[3], 'city': l[4], 'state':l[5], 'location': l[6], 'country':l[7]})\n\n except Exception as e:\n print('Archiving Job Locations Error', e)\n\n\ndef employers(c):\n try:\n c.execute('SELECT employer, sum_current, sum_avg from employers_tbl;')\n\n locations = c.fetchall()\n\n locations_outfile = os.path.join('archived_data', 'employers', 'locations_' + strftime('%y%m%d') + '.csv')\n\n print(locations_outfile)\n\n with open(locations_outfile, 'w') as csvfile:\n fieldnames = ['employer', 'sum_current', 'sum_avg']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n for l in locations:\n writer.writerow({'lat': round(l[0],5), 'lng': round(l[1],5), 'location': l[2]})\n\n except Exception as e:\n print('Archiving Job Locations Error', e)\n","sub_path":"src/archive_data.py","file_name":"archive_data.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"546202990","text":"import scrapy\nfrom mpicture.items import MpictureItem\nimport requests\nclass SexypicSpider(scrapy.Spider):\n name = 'sexypic'\n # allowed_domains = ['b9102.com']\n start_urls = ['https://www.b9102.com/photo/photo_list.html?photo_type=23&page_index=1']\n\n\n\n def parse(self, response):\n\n # headers={\n # \":authority\": \"imagetupian.nypd520.com\",\n # \":method\": \"GET\",\n # # \":path\": /uploads/laoying/2020/2/2020226/80.jpg?max-age=3600\n # \":scheme\": \"https\",\n # \"accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\",\n # \"accept-encoding\": \"gzip, deflate, br\",\n # \"accept-language\": \"zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6\",\n # \"cache-control\": \"max-age=0\",\n # \"if-modified-since\": \"Wed, 26 Feb 2020 00:47:31 GMT\",\n # \"if-none-match\": 'W/\"5e55c023-48422\"',\n # \"sec-fetch-dest\": \"document\",\n # \"sec-fetch-mode\": \"navigate\",\n # \"sec-fetch-site\": \"none\",\n # \"sec-fetch-user\": \"?1\",\n # \"upgrade-insecure-requests\": \"1\",\n # \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36 Edg/83.0.478.61\",\n # }\n\n current_item_list=response.xpath('//div[@class=\"box movie_list\"]/ul/li/a/@href').getall()\n for url in current_item_list:\n # headers[':path']=url+'?max-age=3600'\n yield scrapy.Request(url=response.urljoin(url),callback=self.dealwith_item)\n \n \n next_page_tmp=response.xpath('//div[@class=\"pagination\"]/a/@href').getall()\n next_page_url=next_page_tmp[-2]\n yield scrapy.Request(url=response.urljoin(next_page_url),callback=self.parse)\n\n def dealwith_item(self,response):\n catgery=response.xpath('//div[@class=\"post_title\"]/h1/text()').get()\n image_urls=response.xpath('//div[@class=\"post_content\"]/a/img/@src').getall()\n # for i in image_urls:\n # resp=requests.get(i)\n # if resp.status_code==200:\n # with open(image_urls.split('/')[-1],\"wb+\") as f:\n # f.write(resp.text)\n item=MpictureItem(catgery=catgery,image_urls=image_urls)\n # item=MpictureItem()\n # item['image_urls']=image_urls\n # item['catgery']=catgery\n print(\"_\"*50)\n print(item)\n yield item \n\n\n","sub_path":"mpicture/mpicture/spiders/sexypic.py","file_name":"sexypic.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"269548388","text":"from douglas.tests import PluginTest\nfrom douglas.plugins import yeararchives\n\n\nclass Test_yeararchives(PluginTest):\n def setUp(self):\n PluginTest.setUp(self, yeararchives)\n\n def tearDown(self):\n PluginTest.tearDown(self)\n\n def test_parse_path_info(self):\n for testin, testout in [\n (\"\", None),\n (\"/\", None),\n (\"/2003\", (\"2003\", None)),\n (\"/2003/\", (\"2003\", None)),\n (\"/2003/index\", (\"2003\", None)),\n (\"/2003/index.theme\", (\"2003\", \"theme\")),\n ]:\n \n self.assertEquals(yeararchives.parse_path_info(testin),\n testout)\n","sub_path":"douglas/tests/test_yeararchives.py","file_name":"test_yeararchives.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"196266420","text":"import numpy as np\n\n\nclass MatrixFactorizationModel:\n \"\"\"\n Basic Matrix Factorization Model\n \"\"\"\n\n def __init__(self, x_train, y_train, x_test, y_test, num_users, num_movies, k, alpha, beta, epochs, shuffle=False, verbose=False):\n \"\"\"\n\n :param x_train (ndarray) : 훈련 데이터 (userId, movieId)\n :param y_train (ndarray) : 훈련 데이터 라벨 (rating)\n :param x_test (ndarray) : 테스트 데이터 (userId, movieId)\n :param y_test (ndarray) : 테스트 데이터 라벨 (rating)\n :param num_users (int) : 전체 user 수\n :param num_movies (int) : 전체 movie 수\n :param k (int) : latent feature 크기\n :param alpha (float) : learning rate\n :param beta (float) : lambda, regularization parameter\n :param epochs (int) : training epochs\n :param shuffle (bool) : 훈련 데이터 shuffle\n :param verbose (bool) : print status\n \"\"\"\n\n self.train_size = x_train.shape[0]\n self.x_train = x_train\n self.y_train = y_train\n self.test_size = x_test.shape[0]\n self.x_test = x_test\n self.y_test = y_test\n self.num_users = num_users\n self.num_movies = num_movies\n self.k = k\n self.alpha = alpha\n self.beta = beta\n self.epochs = epochs\n self.shuffle = shuffle\n self.verbose = verbose\n\n # latent feature 초기화\n self.P = np.random.normal(size=(self.num_users+1, self.k)) # user latent feature\n self.Q = np.random.normal(size=(self.num_movies+1, self.k)) # movie latent feature\n\n # bias 초기화\n self.b_u = np.zeros(self.num_users) # user bias\n self.b_i = np.zeros(self.num_movies) # movie bias\n self.b = np.mean(self.y_train) # global bias, Mu, overall average rating\n\n def train(self):\n \"\"\"\n Matrix Factorization Model 학습, optimizer로 SGD를 이용하여 가중치 갱신\n :return: training_process (학습 진행 상황, epoch 별 rmse 값)\n \"\"\"\n training_process = []\n for epoch in range(self.epochs):\n cnt = 0\n if self.shuffle is True:\n idx = np.arange(self.x_train.shape[0])\n np.random.shuffle(idx)\n for (i, j), r in zip(self.x_train[idx], self.y_train[idx]):\n self.sgd(i, j, r)\n cnt += 1\n if self.verbose is True and cnt % 500000 == 0:\n s = \".\" * (cnt // 500000)\n print(\"\\rtraining\", s, end='')\n else:\n for (i, j), r in zip(self.x_train, self.y_train):\n self.sgd(i, j, r)\n cnt += 1\n if self.verbose is True and cnt % 500000 == 0:\n s = \".\" * (cnt // 500000)\n print(\"\\rtraining\", s, end='')\n\n rmse = self.rmse()\n _, test_error = self.test()\n training_process.append([epoch+1, rmse, test_error])\n\n if self.verbose is True:\n print(\" Epoch: %d, rmse = %.4f, test_error(rmse) = %.4f\" % (epoch + 1, rmse, test_error))\n\n return training_process\n\n def test(self):\n \"\"\"\n\n :param x_test (ndarray) : test data (userId, movieId)\n :param y_test (ndarray) : test data label(ratings)\n :return: preds, rmse (테스트 데이터에 대한 에측 값, rmse 값)\n \"\"\"\n preds = [] # test data에 대한 예측 값 리스트\n error = 0\n for (i, j), r in zip(self.x_test, self.y_test): # i: userId, j: movieId, r: 실제 rating 값\n pred = self.get_pred(i, j)\n preds.append(str(round(pred, 4)))\n error += pow(r - pred, 2)\n\n return preds, np.sqrt(error / self.test_size)\n\n def rmse(self):\n \"\"\"\n train data에 대한 rmse 값 계산\n :return: rooted mean square error 값\n \"\"\"\n error = 0\n for (i, j), r in zip(self.x_train, self.y_train): # i: userId, j: movieId, r: 실제 rating 값\n pred = self.get_pred(i, j)\n error += pow(r - pred, 2)\n return np.sqrt(error / self.train_size)\n\n def sgd(self, i, j, r):\n \"\"\"\n Stochastic Gradient Descent 수행\n\n :param i (int) : userId\n :param j (int) : movieId\n :param r (float) : 실제 rating 값\n \"\"\"\n pred = self.get_pred(i, j)\n error = r - pred\n\n # latent feature 갱신\n self.P[i, :] += self.alpha * (error * self.Q[j, :] - self.beta * self.P[i, :])\n self.Q[j, :] += self.alpha * (error * self.P[i, :] - self.beta * self.Q[j, :])\n\n # bias 갱신\n self.b_u[i] += self.alpha * (error - self.beta * self.b_u[i])\n self.b_i[j] += self.alpha * (error - self.beta * self.b_i[j])\n\n def get_pred(self, i, j):\n \"\"\"\n\n :param i (int) : userId\n :param j (int) : movieId\n :return: user i, movie j에 대해 모델이 예측한 rating 값\n \"\"\"\n pred = self.b + self.b_u[i] + self.b_i[j] + self.P[i, :].dot(self.Q[j, :].T)\n return pred\n\n def get_pred_matrix(self):\n \"\"\"\n\n :return: 모든 user x movie 조합에 대하여 예측한 matrix\n \"\"\"\n return self.b + self.b_u[:, np.newaxis] + self.b_i[np.newaxis:, ] + self.P.dot(self.Q.T)\n","sub_path":"Dataset2/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"193694780","text":"import os\nimport sys\nimport uuid\n\nfrom ._uwsgi import uwsgi\n\n\nclass WebSocketClient(object):\n '''\n Default WebSocket client has a blocking recieve method, but still exports\n rest of uWSGI API.\n '''\n def __init__(self, environ, fd, timeout=5):\n self.environ = environ\n self.fd = fd\n self.timeout = timeout\n self.id = str(uuid.uuid1())\n self.connected = True\n self.ctx = uwsgi.request_context()\n\n def receive(self):\n return self.recv()\n\n def recv(self):\n try:\n return uwsgi.websocket_recv(request_context=self.ctx)\n except IOError:\n return None\n\n def recv_nb(self):\n return uwsgi.websocket_recv_nb(request_context=self.ctx)\n\n def send(self, msg, binary=False):\n if binary:\n return self.send_binary(msg)\n return uwsgi.websocket_send(msg, request_context=self.ctx)\n\n def send_binary(self, msg):\n return uwsgi.websocket_send_binary(msg, request_context=self.ctx)\n\n def send_from_sharedarea(self, id, pos):\n return uwsgi.websocket_send_from_sharedarea(id, pos)\n\n def send_binary_from_sharedarea(self, id, pos):\n return uwsgi.websocket_send_binary_from_sharedarea(id, pos)\n\n def close(self):\n self.connected = False\n\n\nclass WebSocketMiddleware(object):\n '''\n WebSocket Middleware that handles handshake and passes route a WebSocketClient.\n '''\n client = WebSocketClient\n\n def __init__(self, wsgi_app, websocket):\n self.wsgi_app = wsgi_app\n self.websocket = websocket\n\n def __call__(self, environ, start_response):\n handler = self.websocket.routes.get(environ['PATH_INFO'])\n\n if not handler or 'HTTP_SEC_WEBSOCKET_KEY' not in environ:\n return self.wsgi_app(environ, start_response)\n\n uwsgi.websocket_handshake(environ['HTTP_SEC_WEBSOCKET_KEY'], environ.get('HTTP_ORIGIN', ''))\n handler(self.client(environ, uwsgi.connection_fd(), self.websocket.timeout))\n return ''\n\n\nclass WebSocket(object):\n '''\n Flask extension which makes it easy to integrate uWSGI-powered WebSockets\n into your applications.\n '''\n middleware = WebSocketMiddleware\n\n def __init__(self, app=None, timeout=5):\n if app:\n self.init_app(app)\n self.timeout = timeout\n self.routes = {}\n\n def run(self, app=None, debug=False, host='localhost', port=5000, **kwargs):\n if not app:\n app = self.app.name + ':app'\n\n # kwargs are treated as uwsgi arguments\n if kwargs.get('master') is None:\n kwargs['master'] = True\n\n # boolean should be treated as empty value\n for k,v in kwargs.items():\n if v is True:\n kwargs[k] = ''\n\n # constructing uwsgi arguments\n uwsgi_args = ' '.join(['--{0} {1}'.format(k,v) for k,v in kwargs.items()])\n\n uwsgi_executable = \"{0}/uwsgi\".format(os.path.dirname(sys.executable))\n args = '{0} --http {1}:{2} --http-websockets {3} --wsgi {4}'.format(uwsgi_executable, host, port, uwsgi_args, app)\n\n # set enviromental variable to trigger adding debug middleware\n if self.app.debug or debug:\n args = 'FLASK_UWSGI_DEBUG=true {0} --python-autoreload 1'.format(args)\n\n # run uwsgi with our args\n print('Running: {0}'.format(args))\n sys.exit(os.system(args))\n\n def init_app(self, app):\n self.app = app\n\n if os.environ.get('FLASK_UWSGI_DEBUG'):\n from werkzeug.debug import DebuggedApplication\n app.wsgi_app = DebuggedApplication(app.wsgi_app, True)\n app.debug = True\n\n app.wsgi_app = self.middleware(app.wsgi_app, self)\n app.run = lambda **kwargs: self.run(**kwargs)\n\n def route(self, rule):\n def decorator(f):\n self.routes[rule] = f\n return f\n return decorator\n","sub_path":"flask_uwsgi_websocket/websocket.py","file_name":"websocket.py","file_ext":"py","file_size_in_byte":3921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"498382136","text":"import sys\n# 创建字符串、列表或元组对象\nlist = ['苹果','香蕉','橘子','桃子']\n# 创建迭代对象\niter_list = iter(list)\n# 迭代一次\n# print(next(iter_list))\n\n# 遍历\nflag = True\nwhile flag:\n try:\n print(next(iter_list))\n except StopIteration:\n print('end...')\n flag = False\n\n# 迭代器对象可以使用for 语句进行遍历\nstr = 'string'\niter_str = iter(str)\nfor s in iter_str:\n print(s, end=\" \")\n","sub_path":"迭代器和操作文件/Iterator.py","file_name":"Iterator.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"217736211","text":"coin1 = float(input(\"Coin 1: \"))\ncoin2 = float(input(\"Coin 2: \"))\ncoin3 = float(input(\"Coin 3: \"))\ncoin4 = float(input(\"Coin 4: \"))\ncost = float(input(\"Cost: \"))\npaid = float(input(\"Paid: \"))\nsort = []\nsort.append(coin1)\nsort.append(coin2)\nsort.append(coin3)\nsort.append(coin4)\nlist.sort(sort)\ntruepaid = paid\ntruecost = cost - truepaid\n\nwhile truepaid > truecost:\n if sort[0] <= truecost:\n while sort[0] <= truecost:\n truepaid += sort[0]\n if sort[1] <= truecost:\n while sort[1] <= truecost:\n truepaid += sort[1]\n if sort[2] <= truecost:\n while sort[2] <= truecost:\n truepaid += sort[2]\n if sort[3] <= truecost:\n while sort[3] <= truecost:\n truepaid += sort[3]\nprint (truepaid)\n","sub_path":"2011/6A.py","file_name":"6A.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"11399066","text":"# Project Euler Problem 039\n\n\n#-------------------------------------------------------------------------------------#\n# If p is the perimeter of a right angle triangle with integral length sides, \n# {a,b,c}, there are exactly three solutions for p = 120.\n#\n# {20,48,52}, {24,45,51}, {30,40,50}\n#\n# For which value of p ≤ 1000, is the number of solutions maximised?\n#-------------------------------------------------------------------------------------#\n\n\nPERIMETER = 1000\nMIN_PERIM = 12\n\n\ndef main():\n max_sols = 0\n p = PERIMETER\n max_count = 0\n\n # Honestly just brute force it, it's quick enough to not be too much of a burden\n while p >= MIN_PERIM:\n count = 0\n for a in range(1, p - 1):\n if p % a == 0:\n b = 1\n while (a + b) <= p:\n if (a ** 2 + b ** 2) == (p - (a + b)) ** 2:\n count += 1\n b += 1\n\n if count > max_count:\n max_count = count \n max_sols = p\n\n p -= 1\n\n print(max_sols)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Python/Problem039.py","file_name":"Problem039.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"443975322","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 13 12:05:38 2015\n\n@author: jlade\n\"\"\"\nnode_list = []\n\nclass Node():\n def __init__(self):\n self.connected_to = []\n global node_list\n node_list.append(self)\n\n def connect_to(self,node):\n if node == self:\n return 0\n elif node in self.connected_to:\n return 1\n else:\n self.connected_to.append(node)\n node.connect_to(self)\n \n def connect_to_multiple(self, nodes):\n for node in nodes:\n self.connect_to(node)\n\n\n","sub_path":"Objects_Vortrag/Listings/my_class2.py","file_name":"my_class2.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"44007262","text":"def ozgunliste(a):\r\n\r\n liste = []\r\n for i in a:\r\n if i not in liste:\r\n liste.append(i)\r\n\r\n return liste\r\n\r\nonerilen_liste = [1,2,5,7,6,6,9,45,54,25,12,35,1,7,25,'a','a','b',[3,4],[4,3]]\r\n\r\nprint(ozgunliste(onerilen_liste)) \r\n","sub_path":"11.ödev-özgün liste.py","file_name":"11.ödev-özgün liste.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"43451817","text":"\"\"\"Demonstrate the creation of a simple wxPython application.\"\"\"\n\nimport wx\n\n\nclass MainFrame(wx.Frame):\n \"\"\"Create and show the frame for the application.\"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"Initialise the MainFrame class.\"\"\"\n super(MainFrame, self).__init__(*args, **kwargs)\n panel = MainPanel(self)\n sizer = wx.BoxSizer(orient=wx.VERTICAL)\n sizer.Add(panel)\n self.SetSizerAndFit(sizer)\n self.Show()\n\n\nclass MainPanel(wx.Panel):\n \"\"\"Create a panel to hold application widgets.\"\"\"\n def __init__(self, parent, *args, **kwargs):\n \"\"\"Initialise the MainPanel class.\"\"\"\n super(MainPanel, self).__init__(parent, *args, **kwargs)\n lbl_name = wx.StaticText(parent=self, label=\"Name:\")\n txt_name = wx.TextCtrl(parent=self, size=(150, -1))\n cmd_quit = wx.Button(parent=self, id=wx.ID_CANCEL)\n cmd_quit.Bind(wx.EVT_BUTTON, self.on_cmd_quit_click)\n sizer = wx.BoxSizer(orient=wx.VERTICAL)\n sizer.Add(lbl_name, flag=wx.ALL, border=10)\n sizer.Add(txt_name, flag=wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10)\n sizer.Add(cmd_quit, flag=wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10)\n self.SetSizer(sizer)\n\n def on_cmd_quit_click(self, event):\n \"\"\"Tear down processes and quit the application.\"\"\"\n del event\n quit()\n\nif __name__ == \"__main__\":\n \"\"\"Implement the wxPython loop.\"\"\"\n SCREEN_APP = wx.App()\n MAIN_FRAME = MainFrame(parent=None, title=\"Frame with widgets\")\n SCREEN_APP.MainLoop()\n","sub_path":"wx_python/snippets/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"485099929","text":"# -*- coding: utf-8 -*-\n\nfrom django.conf import settings\nfrom django.core.mail import send_mail\nfrom django.template.loader import render_to_string\nfrom django.utils.translation import ugettext\nfrom pinax.notifications.backends.base import BaseBackend\n\nfrom tools.iam_client import get_profile\n\n\nclass EmailBackend(BaseBackend):\n spam_sensitivity = 2\n\n def can_send(self, user, notice_type, scoping):\n can_send = super(EmailBackend, self).can_send(user, notice_type, scoping)\n if can_send and user.email:\n return True\n return False\n\n def deliver(self, recipient, sender, notice_type, extra_context):\n context = self.default_context()\n context.update({\n \"recipient\": recipient,\n \"sender\": sender,\n \"notice\": ugettext(notice_type.display),\n \"cloudEyeUrl\": settings.CLOUD_EYE_URL,\n })\n context.update(extra_context)\n\n # 将消息体中的回车换行符替换为html格式\n extra_context['pm_message'].body = str(extra_context['pm_message'].body.encode(\"utf-8\")).replace('\\r\\n', '
') \\\n .replace('\\n', '
').replace('\\\\r\\\\n', '
').replace('\\\\n', '
')\n\n subject = \"\".join(render_to_string(\"email/email_subject.txt\", {\n \"subject\": extra_context[\"pm_message\"].subject\n }).splitlines())\n body = render_to_string(\"email/email_body.html\", {\n \"extra_content\": extra_context,\n \"recipient\": recipient,\n })\n\n mail_sender_name = extra_context['pm_message'].sender.username\n mail_sender_profile = get_profile(mail_sender_name)\n if mail_sender_profile and mail_sender_profile[0].get(\"name\"):\n mail_from = mail_sender_profile[0].get(\"name\") + '<' + settings.DEFAULT_FROM_EMAIL + '>'\n else:\n mail_from = mail_sender_name + '<' + settings.DEFAULT_FROM_EMAIL + '>'\n # 屏蔽邮件发送功能\n send_mail(subject, body, mail_from, [recipient.email], html_message=body)\n","sub_path":"WiseEye/cmdb_back/frame/backends/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"648216406","text":"import h5py\nimport numpy as np\nfrom pathlib import Path\nimport torch\nfrom torch.utils import data\nfrom torch.utils.data.dataloader import default_collate\n\n\nclass HDF5Dataset(data.Dataset):\n \"\"\"Represents an abstract HDF5 dataset.\n \n Parameters:\n file_path: Path to the HDF5 file.\n dataset_names: List of dataset names to gather. \n Objects will be returned in this order.\n \"\"\"\n def __init__(self, file_path, partition):\n super().__init__()\n self.file_path = file_path\n self.partition = partition\n self.meta_dset = partition + '_metadata'\n # s3 is too risky and slow here\n self.h5f = h5py.File(file_path, 'r')\n\n def __len__(self):\n return self.h5f[self.partition].shape[0]\n \n def __getitem__(self, index):\n data = self.h5f[self.partition][index]\n #if self.meta_dset in self.h5f.keys():\n # metadata = self.h5f[self.meta_dset][index]\n #else:\n metadata = None\n return data, metadata\n \n\ndef id_collate(batch):\n new_batch = []\n ids = []\n for _batch in batch:\n new_batch.append(_batch[0])\n ids.append(_batch[1])\n return default_collate(new_batch), np.array(ids)\n \n\ndef get_n_params(model):\n trainable = filter(lambda x: x.requires_grad, model.parameters())\n n_params = sum([np.prod(p.size()) for p in trainable])\n return n_params\n\n\ndef get_gradient_norm(model):\n total_norm = 0\n for p in model.parameters():\n param_norm = p.grad.data.norm(2)\n total_norm += param_norm.item() ** 2\n return total_norm ** (0.5)\n\n\ndef get_quantiles(x):\n rank = np.searchsorted(sorted(x), x)\n quantile = rank / len(rank)\n return quantile\n\ndef match_ids(IDs, match_IDs, require_in_match=True):\n \"\"\" Match input IDs to another array of IDs (usually in a table)\n Return the rows aligned with input IDs\n Parameters\n ----------\n IDs : ndarray\n match_IDs : ndarray\n require_in_match : bool, optional\n Require that each of the input IDs occurs within the match_IDs\n Returns\n -------\n rows : ndarray\n Rows in match_IDs that match to IDs, aligned\n -1 if there is no match\n \"\"\"\n rows = -1 * np.ones_like(IDs).astype(int)\n # Find which IDs are in match_IDs\n in_match = np.in1d(IDs, match_IDs)\n if require_in_match:\n if np.sum(~in_match) > 0:\n raise IOError(\"qcat.match_ids: One or more input IDs not in match_IDs\")\n rows[~in_match] = -1\n #\n IDs_inmatch = IDs[in_match]\n # Find indices of input IDs in meta table -- first instance in meta only!\n xsorted = np.argsort(match_IDs)\n ypos = np.searchsorted(match_IDs, IDs_inmatch, sorter=xsorted)\n indices = xsorted[ypos]\n rows[in_match] = indices\n return rows","sub_path":"ulmo/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"216205380","text":"from tkinter import *\nimport tkinter.font\n\nimport sys\nimport os\n\nfrom rosie import RosieGUI\nfrom rosie.testing import TestAgent\nfrom mobilesim.rosie import MobileSimAgent\n\ndef launch_gui(rosie_config):\n root = Tk()\n eval_agent = MobileSimAgent(rosie_config)\n eval_agent.messages.append(\"!CMD cli pc -f\")\n eval_gui = RosieGUI(eval_agent, master=root)\n eval_gui.run()\n\ndef run_test(rosie_config):\n eval_agent = TestAgent(config_filename=rosie_config, write_to_stdout=True, source_output=\"summary\",\n task_test_output_filename='output/test-output.txt', watch_level=0)\n eval_agent.run_test('correct-output.txt')\n\n# Lookup $ROSIE_HOME\nrosie_home = \"\"\nif \"ROSIE_HOME\" in os.environ:\n rosie_home = os.environ[\"ROSIE_HOME\"]\nelse:\n print(\"ERROR: Requires ROSIE_HOME environment variable set\")\n sys.exit(0)\n\nrosie_config = \"agent/rosie.fill.config\"\n\nif \"--test\" in sys.argv:\n run_test(rosie_config)\nelse:\n launch_gui(rosie_config)\n\n","sub_path":"python/rosie/evaluation/modifiers/fill/run_rosie.py","file_name":"run_rosie.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"255085094","text":"import os\nimport sys\n\ntry:\n\tBOOL = os.path.exists(\"/home/test/flag.txt\")\n\tif BOOL == True:\n\t\tprint(\"What rights do you have with document 'flag.txt'?\")\n\telse:\n\t\tf = open(\"/root/flag.txt\",'r')\n\t\ta = f.read()\n\t\tprint(a)\n\t\tprint('you are brave')\nexcept:\n\tprint(\"you have make some mistake\")\n","sub_path":"Docker190924/ee.py","file_name":"ee.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"363669634","text":"#! /usr/bin/python\n\nfrom stick_figure import *\n\ndef collision_detect(x1,y1,w1,h1,x2,y2,w2,h2,debug,screen):\n\t\n\tif x2+w2>=x1>=x2 and y2+h2>=y1>=y2:\n\t\treturn True\n\telif x2+w2>=x1+w1>=x2 and y2+h2>=y1>=y2:\n\t\treturn True\n\telif x2+w2>=x1>=x2 and y2+h2>=y1+h1>=y2:\n\t\treturn True\n\telif x2+w2>=x1+w1>=x2 and y2+h2>=y1+h1>=y2:\n\t\treturn True\n\telse:\n\t\treturn False\n\n\n\tif debug == 0:\n\t\tpass\n\telif debug == 1:\n\t\tdraw_blocker(screen,red,[x1,y1,h1,w1])\n\t\tdraw_blocker(screen,red,[x2,y2,h2,w2])\n\n\n\n\n\nclass Player(object):\n\tdef __init__(self, screen, pos, size):\n\t\t# Instantiate with the position of player object\n\t\tself.x = pos[0]\n\t\tself.y = pos[1]\n\t\tself.screen = screen\n\t\tself.size = size\n\t\t\n\n\tdef move(self, x_move, y_move):\n\t\t# Move the player object\n\t\tself.x = self.x + x_move\n\t\tself.y = self.y + y_move\n\t\treturn (self.x, self.y)\n\n\tdef render(self):\n\t\tdraw_ball(self.screen, self.x, self.y)\n\n\nclass Projectile(object):\n\tdef __init__(self, screen, pos):\n\t\tself.x = pos[0]\n\t\tself.y = pos[1]\n\t\tself.screen = screen\n\n\tdef move(self, speed):\n\t\tself.x = self.x - speed\n\n\n\tdef render(self):\n\t\tdraw_bullet(self.screen, self.x, self.y)\n\n\n\n\n\n","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"138388976","text":"import os\nfrom setuptools import setup\n \nREADME = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()\n \n# Allow setup.py to be run from any path\nos.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))\n \nsetup(\n name = 'django-rest-framework-proxy-gateway',\n version = '1.0.0',\n packages = ['rest_framework_proxy_gateway', 'tests'],\n include_package_data = True,\n license = 'BSD License',\n description = 'Extends django-rest-framework-proxy to limit the http verbs.',\n long_description = README,\n install_requires=[\n 'django-rest-framework-proxy>=1.6.0,<1.7.0',\n ],\n test_suite='tests',\n url = 'http://www.example.com/',\n author = 'Gordon Collins',\n author_email = 'gordon.collins@excella.com',\n classifiers =[\n 'Environment :: Web Environment',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3.7',\n 'Topic :: Internet :: WWW/HTTP',\n 'Topic :: Internet :: WWW/HTTP :: Dynamic Content'\n ]\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"171135533","text":"import os\nimport numpy as np\nimport pandas as pd\nimport sys\nimport pdb\nimport glob\nfrom collections import defaultdict\nfrom tensorboard.backend.event_processing.event_accumulator import EventAccumulator\nimport matplotlib\n#matplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MultipleLocator\n\ntestcases = {\n'loss curve of vgg16 on K80': 'K80_vgg16_64', \n'loss curve of vgg16 on P100': 'P100_vgg16_64',\n'loss curve of vgg16 on V100': 'V100_vgg16_64'\n}\n\nbase_dir = '/scratch/li.baol/tsrbrd_log/pwr_meas/round1/'\n\nfig, axs = plt.subplots(1, 1, gridspec_kw={'hspace': 0, 'wspace': 0}, figsize=(5,5))\nfig.suptitle(\"loss curve during training\")\n\nfor key, value in testcases.items():\n log_dir = base_dir + value + '_*/'\n \n dirs = glob.glob(log_dir)\n dirs.sort()\n time_all = [] # time for all 10 reps\n loss_all = []\n \n for tc in dirs:\n model = tc.split('/')[5+1]\n iterator = EventAccumulator(tc).Reload()\n tag = 'loss'#iterator.Tags()['scalars'][3] # this is tag for loss\n \n loss = [item.value for item in iterator.Scalars(tag)]\n pdb.set_trace()\n wall_time = [t.wall_time for t in iterator.Scalars(tag)]\n relative_time = [(time - wall_time[0])/3600 for time in wall_time]\n \n time_all.append(relative_time)\n loss_all.append(loss)\n \n time_avg = [0] * len(time_all[0])\n loss_avg = [0] * len(time_all[0])\n \n for j in range(len(time_all)): # 10\n time_avg = np.add(time_all[j], time_avg)\n loss_avg = np.add(loss_all[j], loss_avg) \n \n time_avg = time_avg / len(time_all)\n loss_avg = loss_avg / len(time_all) * 100\n \n# clr = 'tab:orange' if 'vgg16' in value else 'tab:blue'\n# mkr = 'o' if 'K80' in value else '^'\n axs.plot(#time_avg, \n loss_avg, label = key)#, color = clr, marker = mkr)\n\naxs.set_xlabel('epoch') #'training time (h)')\naxs.set_ylabel('model loss')\n\naxs.legend(loc='center right')#, bbox_to_anchor=(1, 0.5))\n#axs.get_xaxis().set_minor_locator(MultipleLocator(0.5))\n#axs.get_yaxis().set_minor_locator(MultipleLocator(5))\naxs.grid(which='both', axis='both', linestyle=':', color='black')\n\n#plt.show()\nplt.savefig('vgg16.png')\n\n#pdb.set_trace()\n#df = pd.DataFrame(time_all, columns=[\"time(h)\"])\n#df.to_csv(result_base_dir + 'csv/' + testcase + '.csv', index=False)\n#\n#fig, axs = plt.subplots(1, 1, gridspec_kw={'hspace': 0, 'wspace': 0}, figsize=(12,5))\n#fig.suptitle(testcase + \" GPU time (h) to train 50 epochs\")\n# \n#x = np.arange(len(time_all))\n#axs.bar(x, time_all)\n#axs.set_xlabel('test rep (10 reps in total)')\n#axs.set_ylabel('time (h)')\n##axs.set_yticks(minor=True)\n#axs.get_yaxis().set_minor_locator(MultipleLocator(5))\n#\n#axs.grid(which='both', axis='y', linestyle=':', color='black')\n#time = int(sum(time_all) / len(time_all))\n#plt.savefig(result_base_dir + \"png/\" + testcase + '_time' + str(time) + \".png\")\n","sub_path":"examples/pwr_run/motivation/motivation2/motivation2.py","file_name":"motivation2.py","file_ext":"py","file_size_in_byte":2895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"147453198","text":"import boto3\nfrom botocore.client import Config\n\ns3 = boto3.resource('s3',config=Config(signature_version='s3v4'))\nbucket_name = 'sc-clipboard'\nkey_name = '08may2017_sc_mds_saral_exambasesumm_v3_1494318395.csv'\n\ndef file_stream():\n data_to_prepend = ''\n fileobj = s3.Object(bucket_name, key).get()['Body']\n for idx in range(5):\n chunk = fileobj.read(1)\n if idx == 1:\n yield headers + chunk\n else:\n yield chunk # Store the new object with .temp appended to the name\n \n \ntemp_key = key_name + \".temp\"\n# we have to keep track of all of our parts\npart_info_dict = {'Parts': []}\n# start the multipart_upload process\nmulti_part_upload = s3.create_multipart_upload(Bucket=bucket_name, Key=temp_key)\ncounter = 0\n# Part Indexes are required to start at 1\nfor part_index, line in enumerate(file_stream(), start=1):\n if counter == 5:\n break\n counter += 1\n # store the return value from s3.upload_part for later\n part = s3.upload_part(\n Bucket=bucket_name,\n Key=temp_key,\n # PartNumber's need to be in order and unique\n PartNumber=part_index,\n # This 'UploadId' is part of the dict returned in multi_part_upload\n UploadId=multi_part_upload['UploadId'],\n # The chunk of the file we're streaming.\n Body=line,\n )\n\n # PartNumber and ETag are needed\n part_info_dict['Parts'].append({\n 'PartNumber': part_index,\n # You can get this from the return of the uploaded part that we stored earlier\n 'ETag': part['ETag']\n })\n\n # This what AWS needs to finish the multipart upload process\n completed_ctx = {\n 'Bucket': bucket_name,\n 'Key': temp_key,\n 'UploadId': multi_part_upload['UploadId'],\n 'MultipartUpload': part_info_dict\n }\n\n# Complete the upload. This triggers Amazon S3 to rebuild the file for you.\n# No need to manually unzip all of the parts ourselves!\ns3.complete_multipart_upload(**completed_ctx)\n","sub_path":"s3_read.py","file_name":"s3_read.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"174234530","text":"import datetime\nimport unittest\n\nfrom baseplate.message_queue import MessageQueue, TimedOutError\nimport webtest\n\nfrom events import collector\n\n\nclass CollectorFunctionalTests(unittest.TestCase):\n def setUp(self):\n # we create the queues before the actual code can so that we can\n # override the max sizes to use these numbers which are safe to use\n # without extra privileges on linux\n self.events_queue = MessageQueue(name=\"/events\",\n max_messages=10, max_message_size=8192)\n self.errors_queue = MessageQueue(name=\"/errors\",\n max_messages=10, max_message_size=8192)\n\n class MockDatetime(datetime.datetime):\n @classmethod\n def utcnow(cls):\n return datetime.datetime(2015, 11, 17, 12, 34, 56)\n datetime.datetime = MockDatetime\n\n app = collector.make_app(global_config={}, **{\n \"key.TestKey1\": \"dGVzdA==\",\n \"msgq.events\": \"0xcafe\",\n \"msgq.errors\": \"0xdecaf\",\n \"allowed_origins\": \"example.com\",\n \"metrics.namespace\": \"eventcollector\",\n \"metrics.endpoint\": \"\",\n })\n self.test_app = webtest.TestApp(app)\n\n def tearDown(self):\n self.events_queue.queue.unlink()\n self.events_queue.queue.close()\n self.errors_queue.queue.unlink()\n self.errors_queue.queue.close()\n\n def test_batch(self):\n self.test_app.post(\"/v1\",\n '[{\"event1\": \"value\"}, {\"event2\": \"value\"}]',\n headers={\n \"Content-Type\": \"application/json\",\n \"User-Agent\": \"TestApp/1.0\",\n \"Date\": \"Wed, 25 Nov 2015 06:25:24 GMT\",\n \"X-Signature\": \"key=TestKey1, mac=d7aab40b9db8ae0e0b40d98e9c50b2cfc80ca06127b42fbbbdf146752b47a5ed\",\n },\n extra_environ={\n \"REMOTE_ADDR\": \"1.2.3.4\",\n },\n )\n\n event1 = self.events_queue.get(timeout=0)\n self.assertEqual(event1, '{\"ip\": \"1.2.3.4\", \"event\": {\"event1\": \"value\"}, \"time\": \"2015-11-17T12:34:56\"}')\n event2 = self.events_queue.get(timeout=0)\n self.assertEqual(event2, '{\"ip\": \"1.2.3.4\", \"event\": {\"event2\": \"value\"}, \"time\": \"2015-11-17T12:34:56\"}')\n\n with self.assertRaises(TimedOutError):\n self.errors_queue.get(timeout=0)\n\n def test_cors(self):\n response = self.test_app.options(\"/v1\", headers={\n \"Origin\": \"http://example.com\",\n \"Access-Control-Request-Method\": \"POST\",\n \"Access-Control-Request-Headers\": \"X-Signature\",\n })\n\n self.assertEqual(response.status_code, 204)\n","sub_path":"tests/functional_tests.py","file_name":"functional_tests.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"617102653","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\nimport commands\nimport os\nimport threading\nimport time\nimport uuid\nimport json\nfrom Queue import Queue\nfrom bondVideo import utils\nfrom bondVideo import course_info\nimport logging.config\nfrom bondVideo.model import CourseVideo, camera_param\nfrom bondVideo.utils import t2s, getPath, getNow\nimport sys\nimport thread\nimport globalValues\nreload(sys)\nsys.setdefaultencoding( \"utf-8\" )\nlogging.config.fileConfig(getPath(\"logger.conf\"))\nlogger = logging.getLogger(\"bondVideo\")\ncameraQueue = Queue()\nclass Consumer_even(threading.Thread):\n\n def __init__(self, t_name, queue):\n threading.Thread.__init__(self, name=t_name)\n self.data = queue\n\n def run(self):\n logger.info('job {0} start'.format('Consumer'))\n logger.info('开始处理等待开课的队列,大小:{0}'.format(self.data.qsize()))\n while True:\n if self.data.qsize() > 0:\n cameraQueue.put(self.data.get())\n else:break\n processJob(self,cameraQueue)\n\n '''\n 调用摄像头\n '''\ndef processJob(self,dataQueue):\n nowTime =time.strftime(\"%H:%M\")\n while True:\n if dataQueue.qsize() > 0:\n data = dataQueue.get()\n if data.startTime <= nowTime:\n logger.info(\"{0}-{1} 开始启动摄像头\".format(data.courseNo,data.classIdx))\n thread.start_new_thread(callCamera,(data,))\n else:\n logger.info(\"{0}-{1}-时间未到重新插入等待队列,开课时间 {2} 当前时间 {3} \"\n .format(data.courseNo,data.classIdx,\n data.startTime,nowTime))\n self.data.put(data)\n else:break\n logger.info(\"处理等待开课的队列任务结束\")\n\n\n\ndef callCamera(data):\n try:\n dicKey = data.courseNo+\"_\"+str(data.classIdx)\n if globalValues.GLOBAL_DIC_CAPTURE.has_key(dicKey):\n logger.info(\"{0}已经在 {1} 开始抓取,返回退出\".format(dicKey,\n globalValues.GLOBAL_DIC_CAPTURE[dicKey]))\n return\n globalValues.GLOBAL_DIC_CAPTURE[dicKey]= time.strftime(\"%Y-%m-%d %X\", time.localtime( time.time() ) )\n logger.info(\"{0}插入到已经开始抓取视屏的列表.当前已经执行抓取任务{1}条\"\n .format(dicKey ,len(globalValues.GLOBAL_DIC_CAPTURE)))\n duration = t2s(str(data.endTime)) - \\\n t2s(str(data.startTime))\n fileName = data.courseNo + \"_\" + \\\n str(data.classIdx) + \".data\"\n captureDir = utils.getConfig(\"sys\", \"captureDir\")\n downloadDir = utils.getConfig(\"sys\", \"downloadDir\")\n school_id = int(utils.getConfig(\"sys\", \"school_id\")),\n course_video = CourseVideo(\n id=str(uuid.uuid1()),\n cno=data.courseNo,\n class_time=data.classIdx,\n file_path=downloadDir + os.sep + fileName,\n school_id=school_id,\n video_unique='',\n video_status=0,\n video_id=0,\n video_file_size=0,\n video_add_time='1970-01-01 00:00:00',\n video_complete_time='1970-01-01 00:00:00',\n video_duration=duration,\n video_img='',\n upload_times=0,\n create_time=getNow(),\n update_time=getNow(),\n capture_status=1,\n post_status=0)\n\n #读取摄像头配置信息\n videoCamera = course_info.getCameraConf(school_id ,data.classRoom);\n\n if videoCamera==None:\n errmsg=\"{0}-{1}@[{2}]不存在对应关系\".format(school_id, dicKey, data.classRoom)\n logger.error(errmsg);\n #utils.sendMailNotifier(\"edu_room\", \"edu_room\", errmsg)\n #utils.sendSMSNotifier(\"edu_room\", \"[vod]\"+errmsg)\n return\n # 组织抓取参数\n jsonData = camera_param(\n fileName,\n downloadDir,\n captureDir,\n videoCamera.user,\n videoCamera.pwd,\n \"rapidjson\",\n duration,\n videoCamera.ip,\n videoCamera.port,\n videoCamera.channel\n )\n param = json.dumps(jsonData,separators=( ',',':'),default=lambda o: o.__dict__,sort_keys=False)\n param = param.replace('\"', '\\\\\"').replace(',', '\\\\,') # 抓视屏的脚本需要对JSON格式中的冒号 双引号 : \" 转义 不能有空格\n param = param+ \" \" + dicKey +\" > camera.log 2>&1 &\";\n cmd = utils.getConfig(\"sys\", \"capture_command\") + \" \" + param\n logger.info(cmd)\n course_info.addCourseVideo(course_video)\n os.system(cmd)\n logger.info(\"{0}调用抓取视屏完成\".format(dicKey))\n except Exception as e:\n logger.exception(\"{0}调用摄像头异常 :{1}\".format(dicKey,e))\n finally:\n logger.info(\"{0}调用摄像头程序完成!\".format(dicKey))\n\n\n\n","sub_path":"bondVideo/consumer_camera.py","file_name":"consumer_camera.py","file_ext":"py","file_size_in_byte":4922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"344764601","text":"from numpy import *\nimport random as rd\nimport time\n\nuse_vision_walls = True\nuse_odorat_candies = True\nuse_odorat_snakes = True\n\nvision_walls_max = 2\nodorat_candies_max = 8\nodorat_snakes_max = 4\n\nepsilon = 0.01\ntau = 0.1\nalpha = 0.2\ngamma = 0.9\nreward_dead = -10\nreward_candy = 1\n\nuse_epsilon_greedy = True # Softmax otherwise\nuse_sarsa = True # Q-Learning otherwise\n\nMOVES = [\n (1, 0),\n (0, -1),\n (-1, 0),\n (0, 1)\n]\n\nsensors = [vision_walls_max for _ in range(4)] * use_vision_walls + [odorat_candies_max for _ in range(4)] * use_odorat_candies + [odorat_snakes_max for _ in range(4)] * use_odorat_snakes\nn_sensors = len(sensors)\nn_actions = 4\nactions = range(n_actions)\nn_states = (vision_walls_max ** (4 * use_vision_walls)) * (odorat_candies_max ** (4 * use_odorat_candies)) * (odorat_snakes_max ** (4 * use_odorat_snakes))\ndelimiter = \",\"\n\nclass IA():\n\n def __init__(self, agent_id, save = None):\n\n self.id = agent_id\n\n self.prev_s = None\n self.prev_a = None\n\n if save is None:\n self.q = zeros((n_states, n_actions))\n else:\n self.q = save\n\n def load(self, fichier):\n self.q = loadtxt(fichier, delimiter = delimiter)\n self.prev_s = None\n self.prev_a = None\n\n def save(self, fichier):\n savetxt(fichier, self.q, delimiter = delimiter)\n\n def numberize_state(self, s):\n r = 0\n m = 1\n for i in range(n_sensors):\n x = s[i]\n r += (x - 1) * m\n m *= sensors[i]\n if (x <= 0 or x > sensors[i]):\n print(i, x)\n time.sleep(100)\n raise Exception(\"Error: Bad sensor value\")\n return r\n\n def distance_to_candy(self, x, y, M):\n d = odorat_candies_max - 1\n for (a, b) in M.candies:\n d = min(d, abs(x - a) + abs(y - b))\n return d + 1\n\n def distance_to_snake(self, x, y, M):\n d = odorat_snakes_max - 1\n for agent in M.agents:\n if agent.id != self.id:\n for (a, b) in agent.pos:\n d = min(d, abs(x - a) + abs(y - b))\n return d + 1\n\n def convert_input(self, M):\n\n head = M.agents[self.id].getHead()\n x = head[0]\n y = head[1]\n values = []\n\n if use_vision_walls:\n vision_walls = []\n # Walls\n for i in range(len(MOVES)):\n (xx, yy) = MOVES[i]\n dist_wall = vision_walls_max\n if xx == 1:\n dist_wall = M.gridsize - x\n elif xx == -1:\n dist_wall = x + 1\n elif yy == 1:\n dist_wall = M.gridsize - y\n elif yy == -1:\n dist_wall = y + 1\n else:\n print(\"ERROR: shouldn't happen\")\n vision_walls.append(min(dist_wall, vision_walls_max))\n values += vision_walls\n\n if use_odorat_candies:\n odorat_candies = []\n odorat_candies.append(self.distance_to_candy(x + 1, y, M))\n odorat_candies.append(self.distance_to_candy(x, y - 1, M))\n odorat_candies.append(self.distance_to_candy(x - 1, y, M))\n odorat_candies.append(self.distance_to_candy(x, y + 1, M))\n values += odorat_candies\n\n if use_odorat_snakes:\n odorat_snakes = []\n odorat_snakes.append(self.distance_to_snake(x + 1, y, M))\n odorat_snakes.append(self.distance_to_snake(x, y - 1, M))\n odorat_snakes.append(self.distance_to_snake(x - 1, y, M))\n odorat_snakes.append(self.distance_to_snake(x, y + 1, M))\n values += odorat_snakes\n\n return values\n\n def proba_softmax(self, l):\n p = [exp(q_value / tau) for q_value in l]\n s = sum(p)\n return [x/s for x in p]\n\n def choose_action(self, s):\n l = self.q[s]\n if use_epsilon_greedy:\n if rd.random() < epsilon:\n return rd.choice(actions)\n return argmax(l)\n else:\n p = self.proba_softmax(l)\n somme = p[0]\n r = rd.random()\n i = 0\n while r > somme:\n i +=1\n somme += p[i]\n return i\n\n def print_choix(self, s):\n spaces = \" \" * 4\n l = [\"%.2f\" % x for x in self.q[s]]\n print(\"\")\n print(\"Espace de choix\")\n print(spaces + l[1])\n print(l[2] + spaces + l[0])\n print(spaces + l[3])\n print(\"\")\n\n def candy_found(self, M):\n return M.agents[self.id].has_eaten\n\n def act(self, M):\n reward = reward_candy * self.candy_found(M)\n s = self.numberize_state(self.convert_input(M))\n a = self.choose_action(s)\n if not (self.prev_s is None):\n if use_sarsa:\n self.q[self.prev_s][self.prev_a] = (1 - alpha) * self.q[self.prev_s][self.prev_a] + alpha * (reward + gamma * self.q[s][a])\n else:\n self.q[self.prev_s][self.prev_a] = (1 - alpha) * self.q[self.prev_s][self.prev_a] + alpha * (reward + gamma * max(self.q[s]))\n self.prev_a = a\n self.prev_s = s\n return a\n\n def dead(self):\n self.q[self.prev_s][self.prev_a] = (1 - alpha) * self.q[self.prev_s][self.prev_a] + alpha * reward_dead\n","sub_path":"IA/IA_rl.py","file_name":"IA_rl.py","file_ext":"py","file_size_in_byte":5352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"415402548","text":"from mcpi.minecraft import Minecraft\r\nmc = Minecraft.create()\r\n\r\nimport random,time\r\n\r\n\r\nwhile True:\r\n x,y,z = mc.player.getTilePos()\r\n x = x+1\r\n for j in range(10):\r\n color = random.randrange(0,16)\r\n z = z+1\r\n mc.setBlock(x,y-1,z,35,color)\r\n time.sleep(20)\r\n ","sub_path":"untitled11.py","file_name":"untitled11.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"352852326","text":"# ======================================================================================================================\n# 将fasta文件进行分词,修改fastafilepath(源文件)和wordfilepath(目标文件存储路径)的路径即可\n# ======================================================================================================================\n# kmer切分\n# b = [document[i:i + 3] for i in range(len(document)) if i < len(document) - 2]\n# b = re.findall(r'.{3}', string)\n\nimport re\nimport time\n\nstart_time=time.time()\nfastafilepath = \"..\\\\data\\\\4mc\\\\4mc.txt\"\nwordfilepath = \"..\\\\data\\\\4mc\\\\4mcword.txt\"\n\nf = open(fastafilepath)\nf1 = open(wordfilepath, \"w\")\n\ndocuments = f.readlines()\nstring=\"\"\nflag=0\nfor document in documents:\n if document.startswith(\">\") and flag == 0:\n flag = 1\n continue\n elif document.startswith(\">\") and flag == 1:\n b = [string[i:i + 3] for i in range(len(string)) if i < len(string) - 2]\n word = \" \".join(b)\n f1.write(word)\n f1.write(\"\\n\")\n string = \"\"\n else:\n string += document\n string = string.strip()\nb = [string[i:i + 3] for i in range(len(string)) if i < len(string) - 2]\nword = \" \".join(b)\nf1.write(word)\nf1.write(\"\\n\")\n\nprint(\"训练结果已保存到{}该目录下!\\n\".format(wordfilepath))\n\nend_time = time.time()\nprint(\"耗时:{}s\\n\".format(end_time - start_time))\nf1.close()\nf.close()\n\n","sub_path":"LSTM/word2vec/Fasta2Segment.py","file_name":"Fasta2Segment.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"469228449","text":"import pygame,sys, random, time\r\nfrom pygame.locals import *\r\n#Set up pygame\r\npygame.init()\r\n\r\nBLACK=(0,0,0)\r\nWHITE=(255,255,255)\r\n\r\nMovespeed = 5\r\ndirection= 'right'\r\n#Set up the window\r\nwindowSurface=pygame.display.set_mode((400,400))\r\npygame.display.set_caption(\"Animation xD\")\r\nwindowSurface.fill(WHITE)\r\n#Set up and display the rectangular(Square) block\r\nblock=pygame.Rect(0,0,20,20)\r\npygame.draw.rect(windowSurface,BLACK,block)\r\npygame.display.update()\r\n#Run the game Loop\r\nwhile True:\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n\r\n #Draw the black background onto the surface\r\n windowSurface.fill(WHITE)\r\n\r\n\r\n if direction == 'right':\r\n block.right=block.right + Movespeed\r\n\r\n\r\n #Draw the player onto the surface\r\n pygame.draw.rect(windowSurface,BLACK,block)\r\n\r\n #Render the windowSurface object\r\n pygame.display.update()\r\n time.sleep(0.02)\r\n\r\n\r\n","sub_path":"2016/Animation.py","file_name":"Animation.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"329369496","text":"import pandas as pd\nimport numpy as np\nimport pickle\nfrom keras.models import load_model\nfrom collections import deque\nimport time\nimport shap\n\n\nclass Model_module:\n def __init__(self):\n self.shap_result_postive = {'Normal':deque(maxlen=1), 'Ab21_01':deque(maxlen=1), 'Ab21_02':deque(maxlen=1), 'Ab20_04':deque(maxlen=1), 'Ab15_07':deque(maxlen=1), 'Ab15_08':deque(maxlen=1), 'Ab63_04':deque(maxlen=1), 'Ab63_02':deque(maxlen=1), 'Ab21_12':deque(maxlen=1), 'Ab19_02':deque(maxlen=1), 'Ab21_11':deque(maxlen=1), 'Ab23_03':deque(maxlen=1), 'Ab60_02':deque(maxlen=1), 'Ab59_02':deque(maxlen=1), 'Ab23_01':deque(maxlen=1), 'Ab23_06':deque(maxlen=1)}\n self.shap_result_negative = {'Normal':deque(maxlen=1), 'Ab21_01':deque(maxlen=1), 'Ab21_02':deque(maxlen=1), 'Ab20_04':deque(maxlen=1), 'Ab15_07':deque(maxlen=1), 'Ab15_08':deque(maxlen=1), 'Ab63_04':deque(maxlen=1), 'Ab63_02':deque(maxlen=1), 'Ab21_12':deque(maxlen=1), 'Ab19_02':deque(maxlen=1), 'Ab21_11':deque(maxlen=1), 'Ab23_03':deque(maxlen=1), 'Ab60_02':deque(maxlen=1), 'Ab59_02':deque(maxlen=1), 'Ab23_01':deque(maxlen=1), 'Ab23_06':deque(maxlen=1)}\n self.selected_para = pd.read_csv('./DataBase/Final_parameter_200825.csv')\n\n\n def flatten(self, X):\n '''\n Flatten a 3D array.\n\n Input\n X A 3D array for lstm, where the array is sample x timesteps x features.\n\n Output\n flattened_X A 2D array, sample x features.\n '''\n flattened_X = np.empty((X.shape[0], X.shape[2])) # sample x features array.\n for i in range(X.shape[0]):\n flattened_X[i] = X[i, (X.shape[1] - 1), :]\n return (flattened_X)\n\n\n def load_model(self):\n # Model Code + Weight (나중에..)\n # Compile False Option -> Very fast model load\n self.train_untrain_lstm_autoencoder = load_model('model/Train_Untrain_epoch27_[0.00225299]_acc_[0.9724685967462512].h5', compile=False)\n self.multiple_xgbclassification = pickle.load(open('model/Lightgbm_max_depth_feature_137_200825.h5', 'rb')) # multiclassova\n self.explainer = pickle.load(open('model/explainer.pkl', 'rb')) # pickle로 저장하여 로드하면 더 빠름.\n self.normal_abnormal_lstm_autoencoder = load_model('model/node32_Nor_Ab_epoch157_[0.00022733]_acc_[0.9758567350470185].h5', compile=False)\n self.ab_21_01_lstmautoencoder = load_model('model/ab21-01_epoch74_[0.00712891]_acc_[0.9653829136428816].h5', compile=False)\n self.ab_21_02_lstmautoencoder = load_model('model/ab21-02_epoch200_[0.01140293]_acc_[0.8144184191122964]_rev1.h5', compile=False)\n self.ab_20_04_lstmautoencoder = load_model('model/ab20-04_epoch62_[0.00121183]_acc_[0.9278062539244847].h5', compile=False)\n self.ab_15_07_lstmautoencoder = load_model('model/ab15-07_epoch100_[0.00048918]_acc_[0.9711231231353337].h5', compile=False)\n self.ab_15_08_lstmautoencoder = load_model('model/ab15-08_epoch97_[0.00454363]_acc_[0.9602876916386659].h5', compile=False)\n self.ab_63_04_lstmautoencoder = load_model('model/ab63-04_epoch92_[0.00015933]_acc_[0.9953701129330438].h5', compile=False)\n self.ab_63_02_lstmautoencoder = load_model('model/ab63-02_epoch100_[0.00376744]_acc_[0.8948400650463064].h5', compile=False)\n self.ab_21_12_lstmautoencoder = load_model('model/ab21-12_epoch40_[0.00236955]_acc_[0.9473147939642043].h5', compile=False)\n self.ab_19_02_lstmautoencoder = load_model('model/ab19-02_epoch200_[0.00610265]_acc_[0.8852787664918006]_rev1.h5', compile=False)\n self.ab_21_11_lstmautoencoder = load_model('model/ab21-11_epoch98_[0.00265125]_acc_[0.9907740136695732].h5', compile=False)\n self.ab_60_02_lstmautoencoder = load_model('model/ab60-02_epoch100_[0.00370811]_acc_[0.989989808320697].h5', compile=False)\n self.ab_23_03_lstmautoencoder = load_model('model/ab23-03_epoch91_[0.00017211]_acc_[0.9931771647209489].h5', compile=False)\n self.ab_59_02_lstmautoencoder = load_model('model/ab59-02_epoch98_[0.00424398]_acc_[0.9923899523150299].h5', compile=False)\n self.ab_23_01_lstmautoencoder = load_model('model/ab23-01_epoch93_[0.00314694]_acc_[0.9407692298522362].h5', compile=False)\n self.ab_23_06_lstmautoencoder = load_model('model/ab23-06_epoch96_[0.00584512]_acc_[0.8694280893287306].h5', compile=False)\n return\n\n\n def train_untrain_classifier(self, data):\n # LSTM_AutoEncoder를 활용한 Train / Untrain 분류\n train_untrain_prediction = self.train_untrain_lstm_autoencoder.predict(data) # 예측\n train_untrain_error = np.mean(np.power(self.flatten(data) - self.flatten(train_untrain_prediction), 2), axis=1)\n if train_untrain_error[0] <= 0.00225299:\n train_untrain_result = 0 # trained condition\n else:\n train_untrain_result = 1 # untrained condition\n return train_untrain_result\n\n def abnormal_procedure_classifier_0(self, data):\n self.abnormal_procedure_prediction = self.multiple_xgbclassification.predict(data) # Softmax 예측 값 출력\n self.diagnosed_scenario = np.argmax(self.abnormal_procedure_prediction, axis=1)[0]\n self.shap_value = self.explainer.shap_values(data) # Shap_value 출력\n return self.abnormal_procedure_prediction, self.diagnosed_scenario\n\n def abnormal_procedure_classifier_1(self):\n diagnosis_convert_text = {0: 'Normal', 1: 'Ab21_01', 2: 'Ab21_02', 3: 'Ab20_04', 4: 'Ab15_07', 5: 'Ab15_08',\n 6: 'Ab63_04', 7: 'Ab63_02', 8: 'Ab21_12',9: 'Ab19_02', 10: 'Ab21_11', 11: 'Ab23_03',\n 12: 'Ab60_02', 13: 'Ab59_02', 14: 'Ab23_01', 15: 'Ab23_06'}\n sort_shap_values_positive = pd.DataFrame(self.shap_value[np.argmax(self.abnormal_procedure_prediction, axis=1)[0]], columns=self.selected_para['0'].tolist()).sort_values(by=0, ascending=False, axis=1)\n drop_shap_values_positive = sort_shap_values_positive[sort_shap_values_positive.iloc[:]>0].dropna(axis=1).T\n reset_shap_values_positive = drop_shap_values_positive.reset_index()\n column_positive = reset_shap_values_positive['index']\n var_positive = [self.selected_para['0'][self.selected_para['0'] == col_].index for col_ in column_positive]\n val_col_positive = [self.selected_para['1'][var_].iloc[0] for var_ in var_positive]\n proba_positive = [(reset_shap_values_positive[0][val_num]/sum(reset_shap_values_positive[0]))*100 for val_num in range(len(reset_shap_values_positive))]\n val_system_positive = [self.selected_para['2'][var_].iloc[0] for var_ in var_positive]\n reset_shap_values_positive['describe'] = val_col_positive\n reset_shap_values_positive['probability'] = proba_positive\n reset_shap_values_positive['system'] = val_system_positive\n self.shap_result_postive[diagnosis_convert_text[np.argmax(self.abnormal_procedure_prediction, axis=1)[0]]].append(reset_shap_values_positive)\n return self.shap_result_postive\n\n def abnormal_procedure_classifier_2(self, scenario):\n int_convert_text = {0:'Normal', 1:'Ab21_01', 2:'Ab21_02', 3:'Ab20_04', 4:'Ab15_07', 5:'Ab15_08',\n 6:'Ab63_04', 7:'Ab63_02', 8:'Ab21_12', 9:'Ab19_02', 10:'Ab21_11', 11:'Ab23_03',\n 12:'Ab60_02', 13:'Ab59_02', 14:'Ab23_01', 15:'Ab23_06'}\n\n sort_shap_values_negative = pd.DataFrame(self.shap_value[scenario], columns=self.selected_para['0'].tolist()).sort_values(by=0, ascending=True, axis=1)\n drop_shap_values_negative = sort_shap_values_negative[sort_shap_values_negative.iloc[:]<0].dropna(axis=1).T\n reset_shap_values_negative = drop_shap_values_negative.reset_index()\n column_negative = reset_shap_values_negative['index']\n val_negative = [self.selected_para['0'][self.selected_para['0'] == col_].index for col_ in column_negative]\n val_col_negative = [self.selected_para['1'][var_].iloc[0] for var_ in val_negative]\n proba_negative = [(reset_shap_values_negative[0][val_num]/sum(reset_shap_values_negative[0]))*100 for val_num in range(len(reset_shap_values_negative))]\n val_system_negative = [self.selected_para['2'][var_].iloc[0] for var_ in val_negative]\n reset_shap_values_negative['describe'] = val_col_negative\n reset_shap_values_negative['probability'] = proba_negative\n reset_shap_values_negative['system'] = val_system_negative\n self.shap_result_negative[int_convert_text[scenario]].append(reset_shap_values_negative)\n return self.shap_result_negative\n\n def abnormal_procedure_verification(self, data): # 만약 abnormal 예측이 실패한다면??\n global verif_prediction, verif_threshold\n if self.diagnosed_scenario == 0:\n verif_prediction = self.normal_abnormal_lstm_autoencoder.predict(data)\n verif_threshold = 0.00022733\n elif self.diagnosed_scenario == 1:\n verif_prediction = self.ab_21_01_lstmautoencoder.predict(data)\n verif_threshold = 0.00712891\n elif self.diagnosed_scenario == 2:\n verif_prediction = self.ab_21_02_lstmautoencoder.predict(data)\n verif_threshold = 0.01140293\n elif self.diagnosed_scenario == 3:\n verif_prediction = self.ab_20_04_lstmautoencoder.predict(data)\n verif_threshold = 0.00121183\n elif self.diagnosed_scenario == 4:\n verif_prediction = self.ab_15_07_lstmautoencoder.predict(data)\n verif_threshold = 0.00048918\n elif self.diagnosed_scenario == 5:\n verif_prediction = self.ab_15_08_lstmautoencoder.predict(data)\n verif_threshold = 0.00454363\n elif self.diagnosed_scenario == 6:\n verif_prediction = self.ab_63_04_lstmautoencoder.predict(data)\n verif_threshold = 0.00015933\n elif self.diagnosed_scenario == 7:\n verif_prediction = self.ab_63_02_lstmautoencoder.predict(data)\n verif_threshold =0.00376744\n elif self.diagnosed_scenario == 8:\n verif_prediction = self.ab_21_12_lstmautoencoder.predict(data)\n verif_threshold = 0.00236955\n elif self.diagnosed_scenario == 9:\n verif_prediction = self.ab_19_02_lstmautoencoder.predict(data)\n verif_threshold = 0.00610265\n elif self.diagnosed_scenario == 10:\n verif_prediction = self.ab_21_11_lstmautoencoder.predict(data)\n verif_threshold = 0.00265125\n elif self.diagnosed_scenario == 11:\n verif_prediction = self.ab_23_03_lstmautoencoder.predict(data)\n verif_threshold = 0.00017211\n elif self.diagnosed_scenario == 12:\n verif_prediction = self.ab_60_02_lstmautoencoder.predict(data)\n verif_threshold = 0.00370811\n elif self.diagnosed_scenario == 13:\n verif_prediction = self.ab_59_02_lstmautoencoder.predict(data)\n verif_threshold = 0.00424398\n elif self.diagnosed_scenario == 14:\n verif_prediction = self.ab_23_01_lstmautoencoder.predict(data)\n verif_threshold = 0.00314694\n elif self.diagnosed_scenario == 15:\n verif_prediction = self.ab_23_06_lstmautoencoder.predict(data)\n verif_threshold = 0.00584512\n abnormal_verif_error = np.mean(np.power(self.flatten(data) - self.flatten(verif_prediction), 2), axis=1)\n if abnormal_verif_error <= verif_threshold: # diagnosis success\n verif_result = 0\n else: # diagnosis failure\n verif_result = 1\n return verif_result\n\n\n\n","sub_path":"version 6/model_module_thread_210210.py","file_name":"model_module_thread_210210.py","file_ext":"py","file_size_in_byte":11581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"560019833","text":"if __name__ == '__main__':\n\n students = []\n\n for _ in range(int(input())):\n name = input()\n score = float(input())\n\n # create the list\n students.append([name, score])\n\n # sort list by grade first (highest first) and name second\n students = sorted(students, key=lambda x: (x[1], x[0]))\n\n # edge case where only one student or all students got the same grade\n if len(students) == 1 or students[0][1] == students[-1][1]:\n print(\"Error: Only one grade\")\n\n # find second highest grade\n for i in range(1, len(students)):\n if students[i][1] > students[0][1]:\n # print all students with this grade\n j = i\n while students[i][1] == students[j][1]:\n print(students[j][0])\n j += 1\n break\n","sub_path":"Python/BasicDataTypes/NestedList.py","file_name":"NestedList.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"404727873","text":"import os\nimport threading\nfrom multiprocessing.pool import Pool\nfrom time import sleep, time\n\nimport sys\n\nimport logging\n\nimport fcntl\n\nfrom confmom.ConfMom import ConfMom, SelectEnv, MODE_ZK, MODE_FILE\n\nstdout_handler = logging.StreamHandler(sys.stdout)\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S', # filename='/var/log/sea_spider/logging.log',\n # filemode='a',\n handlers=[stdout_handler])\n\ndef get_config():\n conf = ConfMom(\"127.0.0.1:2181\",\"beehive_web\",\"master\")\n c = conf.get_config()\n print(c)\n\ndef test_client_get_config():\n \"\"\"\n 测试客户端拉取数据的例子\n :return:\n \"\"\"\n def get_change(data):\n print(\"变化了{}\".format(data))\n conf = ConfMom(\"127.0.0.1:2181\", \"beehive_web\", SelectEnv.Env(\"master\"),(\"conf_server\",\"123456\"), callbackOnChange=get_change)\n c = conf.get_config()\n print(c)\n\n\n conf.push_config({\"push_data\":\"123456\"})\n print(\"推送配置\")\n\n t = threading.Thread(target=lambda: sleep(100))\n t.start()\n t.join()\ndef test_client_select_env():\n print(SelectEnv.FileEnv(\"./env\"))\n print(SelectEnv.GitEnv(\"./\"))\n\ndef test_conf_mom_in_muti_process():\n def get_change(data):\n pass\n # print(\"变化了{}\".format(data))\n conf = ConfMom( \"beehive_web\", SelectEnv.Env(\"dev\"),\n mode=MODE_ZK ,\n zk_host=\"192.168.81.60:2181\",\n acl=(\"read\", \"123\"),\n callbackOnChange=get_change, use_file_on_fork=\"./ignore.config.json\"\n )\n\n d = conf.get_config()\n print(\"1--\"+str(d))\n sleep(1)\n if 0 == os.fork():\n d = conf.get_config()\n print(\"2--\"+str(d))\n sleep(1)\n if 0== os.fork():\n d = conf.get_config()\n print(\"3--\"+str(d))\n sleep(1)\n if 0 == os.fork():\n d = conf.get_config()\n print(\"4--\" + str(d))\n sleep(100000)\n else:\n sleep(100000)\n else:\n sleep(100000)\n else:\n sleep(100000)\n\n\ndef test_conf_mom_more_p():\n def get_change(data):\n pass\n\n conf = ConfMom(\"beehive_web\", SelectEnv.Env(\"dev\"), mode=MODE_ZK, zk_host=\"192.168.81.60:2181\", acl=(\"read\", \"123\"),\n callbackOnChange=get_change, use_file_on_fork=\"./ignore.config.json\")\n d = conf.get_config()\n print(\"master {}\".format(d))\n # def par(x):\n # d = conf.get_config()\n # print(\"{}.{} = {}\".format(x, os.getpid(),d))\n # sleep(100)\n # return os.getpid()\n # worker = Pool(processes=100)\n # result = worker.map(par,range(100))\n # print(result)\n\n a = 200\n while a:\n if os.fork() == 0:\n d = conf.get_config()\n print(\"{} = {}\".format(a,d))\n sleep(100)\n break\n a-=1\n sleep(1000)\n\ndef test_conf_file_multi_process():\n def get_change(data):\n pass\n\n def config():\n if 0 == os.fork():\n print(\"儿子备锁住文件\")\n\n file = open(\"./ignore.config.json\", \"w\")\n print(file)\n fcntl.lockf(file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)\n print(\"儿子锁住文件\")\n sleep(100)\n else:\n print(\"爸爸准备锁住文件\")\n file = open(\"./ignore.config.json\",\"w\")\n fcntl.lockf(file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)\n print(\"爸爸锁住文件\")\n sleep(100)\n threading.Thread(target=config).start()\n sleep(1000)\n\ntest_conf_mom_more_p()","sub_path":"confmom/Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":3705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"167808437","text":"import socket,ssl,select\nclass RequestMethod:\n UNSET=0\n GET=1\n POST=2\n PUT=3\n OPTIONS=4\n HEAD=5\n DELETE=6\n TRACE=7\n CONNECT=8\n def toString(reqMeth):\n if reqMeth==0:return \"UNSET\";\n elif reqMeth==1:return \"GET\";\n elif reqMeth==2:return \"POST\";\n elif reqMeth==3:return \"PUT\";\n elif reqMeth==4:return \"OPTIONS\";\n elif reqMeth==5:return \"HEAD\";\n elif reqMeth==6:return \"DELETE\";\n elif reqMeth==7:return \"TRACE\";\n elif reqMeth==8:return \"CONNECT\";\n def parseMethod(s):\n if s==\"GET\":return RequestMethod.GET;\n elif s==\"POST\":return RequestMethod.POST;\n elif s==\"PUT\":return RequestMethod.PUT;\n elif s==\"OPTIONS\":return RequestMethod.OPTIONS;\n elif s==\"HEAD\":return RequestMethod.HEAD;\n elif s==\"DELETE\":return RequestMethod.DELETE;\n elif s==\"TRACE\":return RequestMethod.TRACE;\n elif s==\"CONNECT\":return RequestMethod.CONNECT;\n else:return RequestMethod.UNSET\ndef StripLeadingChar(s,c):\n while True:\n if(len(s)>0):\n if(s[0]==c):s=s[1:len(s)]\n else:break\n else:break\n return s\nclass RequestHeader:\n def __init__(self):\n self.requestMethod=RequestMethod.GET;self.requestData=\"/\";self.headers={};self.httpVersion=\"1.1\"\n def LoadString(self,headerData):\n self.requestMethod=RequestMethod.UNSET\n headerSplit=headerData.split(\"\\r\\n\")\n if(len(headerSplit)>0):\n firstSplit=headerSplit[0].split(\" \")\n self.requestMethod=RequestMethod.parseMethod(firstSplit[0])\n if(len(firstSplit)>2):\n self.requestData=firstSplit[1]\n for s in firstSplit:\n if \"HTTP\" in s:httpSplit=s.split(\"/\");self.httpVersion=httpSplit[1];break\n for i in range(1,headerLength):\n dataSplit=headerSplit[i].split(\":\");self.headers[dataSplit[0]]=StripLeadingChar(dataSplit[1],' ')\n return self\n def setRequestMethod(self,requestMethod):self.requestMethod=requestMethod;return self;\n def getRequestMethod(self):return self.requestMethod\n def setHTTPVersion(self,httpVersion):self.httpVersion=httpVersion;return self;\n def getHTTPVersion(self):return self.httpVersion;\n def setRequestData(self,requestData):self.requestData=requestData;return self;\n def getRequestData(self):return self.requestData;\n def putHeader(self,key,value):self.headers[key]=value;return self;\n def removeHeader(self,key):del self.headers[key];return self;\n def hasHeader(self,key):return key in self.headers\n def toString(self):\n reqData=\"/\"\n if(len(self.requestData)>0):reqData=self.requestData\n s=RequestMethod.toString(self.requestMethod)+\" \"+reqData+\" HTTP/\"+self.httpVersion\n for k,v in self.headers.items():\n s+=\"\\r\\n\"+str(k)+\": \"+str(v)\n return s\ndef IsInteger(s):\n try:int(s);return True;\n except ValueError as ve:return False;\nclass ResponseHeader:\n def __init__(self):self.responseCode=200;self.httpVersion=\"1.1\";self.headers={}\n def LoadString(self,s):\n headerSplit=s.split(\"\\r\\n\")\n if len(headerSplit)>0:\n firstSplit = headerSplit[0].split(\" \")\n for st in firstSplit:\n if \"HTTP\" in st:self.httpVersion=st.split(\"/\")[1]\n elif IsInteger(st):self.responseCode=int(st)\n for i in range(1,len(headerSplit)):\n dataSplit=headerSplit[i].split(\":\")\n self.headers[dataSplit[0]]=StripLeadingChar(dataSplit[1],' ')\n return self\n def setResponseCode(self,code):self.responseCode=code;return self;\n def getResponseCode(self):return self.responseCode;\n def setHTTPVersion(self,httpVersion):self.httpVersion=httpVersion;return self;\n def getHTTPVersion(self):return self.httpVersion;\n def putHeader(self,key,value):self.headers[key]=value;return self;\n def removeHeader(self,key):del self.headers[key];return self;\n def hasHeader(self,key):return key in self.headers;\n def toString(self):\n s=\"HTTP/\"+self.httpVersion+\" \"+str(self.responseCode)\n for k,v in self.headers.items():\n s+=\"\\r\\n\"+str(k)+\": \"+str(v)\n return s\ndef Dechunkify(body):\n actualBody=\"\"\n hexAmount=\"\"\n hexTime=0\n bodyLength=len(body)\n for i in range(len(body)):\n if(i==hexTime):\n hexAmount=\"\"\n if(i>=hexTime):\n if(body[i]=='\\r' and body[i+1]=='\\n'):\n hexTime=i+3+int(hexAmount,16)\n else:\n hexAmount+=body[i]\n else:\n actualBody+=body[i]\n return actualBody\n#Appears to be some crappy bot\nsock=socket.socket()\ncfduid=\"\"\nscraptf_session=\"\"\nscr_session=\"\"\nuser_agent=\"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36\"\nlanguage_settings=\"en-GB,en;q=0.8,en-US;q=0.6,ru;q=0.4\"\ndef GetRaffleInfo(raffleID):\n sock=socket.socket()\n sock.connect((\"scrap.tf\",443))\n sslsock=ssl.wrap_socket(sock)\n req=RequestHeader().setRequestMethod(RequestMethod.GET).setRequestData(\"/raffles/\"+raffleID).putHeader(\"Host\",\"scrap.tf\").putHeader(\"dnt\",1).putHeader(\"upgrade-insecure-requests\",1)\n req.putHeader(\"accept\",\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\").putHeader(\"accept-language\",language_settings).putHeader(\"user-agent\",user_agent)\n req.putHeader(\"cache-control\",\"max-age=0\").putHeader(\"cookie\",\"__cfduid=\"+cfduid+\"; scraptf_session=\"+scraptf_session+\"; scr_session=\"+scr_session)\n sslsock.write((req.toString()+\"\\r\\n\\r\\n\").encode())\n sslsock.settimeout(1)\n entireResponse=\"\"\n while True:\n try:entireResponse+=sslsock.read().decode()\n except Exception as e:break\n splet=entireResponse.split(\"\\r\\n\\r\\n\")\n respHed=ResponseHeader().LoadString(splet[0])\n dataTime=None\n specialThing=None\n if(respHed.hasHeader(\"Transfer-Encoding\")):\n body=Dechunkify(splet[1])\n if(\"onclick=\\\"ScrapTF.Raffles.EnterRaffle(\" in body):\n ind=body.index(\"onclick=\\\"ScrapTF.Raffles.EnterRaffle(\")\n i=ind+37\n length=len(body)\n raffleData=\"\"\n while i 1:\n loss = loss / grad_accum_steps\n\n if config.fp16:\n optimizer.backward(loss)\n else:\n loss.backward()\n\n # step the optimizer every grad_accum_steps\n if (step + 1) % grad_accum_steps == 0:\n update_learning_rate(optimizer, global_step, lr_schedule, config)\n optimizer.step()\n optimizer.zero_grad()\n global_step += 1\n\n losses.append(loss.item() * grad_accum_steps)\n batch_iter.set_postfix(loss=np.mean(losses))\n\n if val_dl is not None:\n res = eval_model(model, val_dl, config)\n test_loss, test_accy = res['loss'], res['accy']\n msg = \"Epoch %d, Train loss: %0.04f, Val loss: %0.04f, Val accy: %0.02f%%\"\n msg = msg%(epoch+1, np.mean(losses), test_loss, test_accy)\n if 'f1' in res:\n msg += \", f1: %0.02f\"%(100 * res['f1'])\n log(msg)\n else:\n msg = \"Epoch %d, Train loss : %0.04f\"%(epoch+1, np.mean(losses))\n log(msg, console=False)\n\n return model\n\n\ndef eval_model(model, dataloader, config, desc=\"Validating\"):\n \"\"\"\n Evaluate model on validation data.\n\n Parameters\n ----------\n model : BertPlusMLP\n Bert model plus mlp head\n dataloader : Dataloader\n validation dataloader\n config : FinetuneConfig\n Parameters for finetuning BERT\n desc : string\n text label for progress bar\n \n Returns\n -------\n loss : float\n Loss calculated on eval data\n accy : float\n Classification accuracy for classifiers.\n Pearson coorelation for regressors.\n \"\"\"\n device = config.device\n model_type = config.model_type\n ignore_label = config.ignore_label_id\n\n regression_stats = OnlinePearson()\n stats = OnlineF1(ignore_label=ignore_label)\n\n model.to(device)\n model.eval()\n loss = accy = 0.\n total_evals = 0\n res = {}\n\n sys.stdout.flush()\n batch_iter = pbar(dataloader, desc=desc, leave=True)\n\n for eval_steps, batch in enumerate(batch_iter):\n batch = tuple(t.to(device) for t in batch)\n _, _, _, y = batch\n with torch.no_grad():\n tmp_eval_loss, output = model(*batch)\n loss += tmp_eval_loss.mean().item()\n\n if model_type == \"text_classifier\":\n _, y_pred = torch.max(output, 1)\n accy += torch.sum(y_pred == y)\n\n elif model_type == \"text_regressor\":\n y_pred = output\n\n # add to online stats calculator\n for xi, yi in zip(y.detach().cpu().numpy(),\n y_pred.detach().cpu().numpy()):\n regression_stats.add(xi, yi)\n\n elif model_type == \"token_classifier\":\n\n output = output.view(-1, output.shape[-1])\n y_true = y.view(-1)\n valid_tokens = y_true != -1\n\n _, y_pred = torch.max(output, 1)\n\n accy += torch.sum(y_pred[valid_tokens] == y_true[valid_tokens])\n total_evals += torch.sum(valid_tokens).item()\n\n y_true = y_true[valid_tokens].detach().cpu().numpy()\n y_pred = y_pred[valid_tokens].detach().cpu().numpy()\n\n # add to online stats calculator\n stats.add(y_true=y_true, y_pred=y_pred)\n\n loss = loss/(eval_steps+1)\n\n if model_type == \"text_classifier\":\n accy = 100 * (accy.item() / len(dataloader.dataset))\n elif model_type == \"text_regressor\":\n accy = 100 * regression_stats.pearson\n elif model_type == \"token_classifier\":\n accy = 100 * (accy.item() / total_evals)\n res['f1'] = stats.f1\n res['precision'] = stats.precision\n res['recall'] = stats.recall\n\n res['loss'] = loss\n res['accy'] = accy\n return res\n","sub_path":"bert-sklearn/bert_sklearn/finetune.py","file_name":"finetune.py","file_ext":"py","file_size_in_byte":7327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"143068815","text":"import os\nimport copy\nimport time\nimport random\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom message_utils import parse_message\nimport datetime\n\n# util and commands \n\ndef calc_paramater(act_min, act_max, max_val):\n if act_max == 0.0 and act_min == 0.0:\n return 0, (0.5,0.5)\n reward_sum = act_max + act_min\n reward_rate = (act_min / reward_sum, act_max / reward_sum)\n value = max_val * reward_rate[1]\n return value, reward_rate\n\ndef command_turn(inference_result):\n direction, reward_rate = calc_paramater(inference_result[0], inference_result[1],180)\n command = '(turn {})'.format(direction - 90)\n # print(inference_result, reward_rate)\n return command, reward_rate\n\ndef command_dash(inference_result):\n power, reward_rate_a = calc_paramater(inference_result[0], inference_result[1], 100)\n direction, reward_rate_b = calc_paramater(inference_result[2], inference_result[3], 180)\n command = '(dash {} {})'.format(power, direction - 90)\n return command, (reward_rate_a[0] / 2.0, reward_rate_a[1] / 2.0, reward_rate_b[0] / 2.0, reward_rate_b[1] / 2.0)\n\ndef command_kick(inference_result):\n power, reward_rate_a = calc_paramater(inference_result[0], inference_result[1], 100)\n direction, reward_rate_b = calc_paramater(inference_result[2], inference_result[3], 180)\n command = '(kick {} {})'.format(power, direction - 90)\n return command, (reward_rate_a[0] / 2.0, reward_rate_a[1] / 2.0, reward_rate_b[0] / 2.0, reward_rate_b[1] / 2.0)\n\ndef command_change_view_wide(inference_result):\n return '(change_view wide)', (1,)\n\ndef command_change_view_normal(inference_result):\n return '(change_view normal)', (1,)\n\ndef command_change_view_narrow(inference_result):\n return '(change_view narrow)', (1,)\n\ndef random_commands():\n vals = [\n (0, [0.2, 0.8]),\n (0, [0.3, 0.7]),\n (0, [0.4, 0.6]),\n (1, [0.2, 0.8, 0.8, 0.2]),\n ]\n return vals[random.randrange(len(vals))]\n\ndef find_command_and_rate(command:str) -> int:\n print(command)\n parsed_command = parse_message(command)[0]\n command_index = ['turn', 'dash', 'kick', 'change_view'].index(parsed_command[0])\n if parsed_command[0] == 'turn':\n command_index = 0\n dir_a = float(parsed_command[1]) + 180.0\n dir_b = 360.0 - dir_a\n return command_index, [dir_b, dir_a]\n elif parsed_command[0] == 'dash' or parsed_command[0] == 'kick':\n command_index = 1 if parsed_command[0] == 'dash' else 2\n power_a = float(parsed_command[1])\n power_b = 100.0 - power_a\n dir_a = float(parsed_command[2]) + 180.0\n dir_b = 360.0 - dir_a\n return command_index, [power_b, power_a, dir_b, dir_a]\n elif parsed_command[0] == 'change_view':\n return 2 + ['wide', 'normal', 'narrow'].index(parsed_command[1])\n\n\n\ncommand_arg_counts = np.array([2,4,4,1,1,1])\ncommands = [\n command_turn,\n command_dash,\n command_kick,\n command_change_view_wide,\n command_change_view_normal,\n command_change_view_narrow\n]\n\n# turn(dir) dash(power, direction), kick(power, direction) change_view_wide() change_view_normal() change_view_narrow()\n# 入力値がある場合、入力値*2のActが存在していることになる\n\n# 環境\nMONITOR = False\nHIDDEN_SIZE = 300\nMEMORY_SIZE = 3000\nBATCH_SIZE = 20\nTRAIN_INTERVAL = 10\nGAMMA = 0.97\nacts_num = 13\nobs_num = 294 * 2 + acts_num * 3\n\nclass NN(nn.Module):\n def __init__(self):\n super(NN, self).__init__()\n self.fc1 = nn.Linear(obs_num, HIDDEN_SIZE)\n self.fc2 = nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE)\n self.fc3 = nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE)\n self.fc4 = nn.Linear(HIDDEN_SIZE+obs_num, acts_num)\n self.dropout1 = nn.Dropout(0.3)\n self.dropout2 = nn.Dropout(0.5)\n \n def __call__(self, x):\n h = F.relu(self.fc1(x))\n h = F.relu(self.fc2(h))\n h = self.dropout1(h)\n h = F.relu(self.fc3(h))\n h = self.dropout2(h)\n y = F.relu(self.fc4(torch.cat([h, x], -1)))\n return y\n\nclass Estimater():\n def __init__(self, player_number, player_side, save_path='robo.pt', batch_size=BATCH_SIZE):\n self.player_number = player_number\n self.player_side = player_side\n self.save_path = save_path\n \n self.batch_size = batch_size\n self.commands = commands\n self.command_arg_counts = command_arg_counts\n\n self.q_func = NN()\n self.q_func_old = copy.deepcopy(self.q_func)\n if os.path.exists(self.save_path):\n self.load()\n self.optimizer = optim.RMSprop(self.q_func.parameters(), lr=0.00015, alpha=0.95, eps=0.01)\n\n self.saved = False\n self.episode = [] # [[state, act, reward_rate, reward, next_state]]\n self.total_reward = 0\n self.call_count = 0\n \n def __call__(self, state, state_reward=0, suggest_command=None):\n input_state = np.array(state, dtype='float32')\n command, act_command ,reward_rate, inference_result = self.predict(input_state, suggest_command)\n\n # input datas to self.episode for training\n self.total_reward += state_reward\n self.call_count += 1\n self.episode.append([input_state, act_command, reward_rate, None, None])\n if len(self.episode) > 0:\n self.episode[-1][3:] = [state_reward, input_state]\n\n if len(self.episode) > MEMORY_SIZE:\n self.episode.pop()\n if self.call_count % TRAIN_INTERVAL == 0:\n self.train()\n\n if self.call_count % 500 == 0 and not self.saved:\n self.save()\n return command, inference_result\n \n def set_episode(self, episode):\n self.episode = episode\n \n def predict(self, state, suggest_command=None):\n result = self.q_func(Variable(torch.from_numpy(state))).data.numpy()\n command, best_act, reward_rate = self.parse_result_to_command(result, suggest_command)\n return command, best_act, reward_rate, result\n \n def parse_result_to_command(self, result, suggest_command=None):\n best_act, splited_result = self.inference_split(result, suggest_command)\n command, reward_rate = self.commands[best_act](splited_result[best_act])\n \n return command, best_act, reward_rate\n\n def inference_split(self, result, suggest_command=None):\n acts_results = []\n act_rewards = []\n start_index = 0\n for i in self.command_arg_counts:\n acts_results.append(result[start_index:start_index+i])\n act_rewards.append(np.sum(result[start_index:start_index+i]))\n start_index += i\n \n if suggest_command != None:\n best_act, act_reward = find_command_and_rate(suggest_command)\n acts_results[best_act] = np.array(act_reward)\n elif random.randint(0, 5) == 0:\n best_act, tmp = random_commands()\n acts_results[best_act] = tmp\n else:\n best_act = np.argmax(act_rewards)\n\n return best_act, acts_results\n\n def train(self):\n episode = np.array(self.episode)\n if len(episode) < self.batch_size:\n return None\n \n np.random.shuffle(episode)\n for i in range(len(episode))[::self.batch_size]:\n batch = episode[i:i+self.batch_size]\n if len(batch) < self.batch_size:\n continue\n states = np.array(batch[:,0].tolist(), dtype='float32')\n best_acts = batch[:,1]\n reward_rates = batch[:,2]\n rewards = batch[:,3]\n next_states = np.array(batch[:,4].tolist(), dtype='float32')\n inferences_a = self.q_func(Variable(torch.from_numpy(states)))\n inferences_b = self.q_func_old(Variable(torch.from_numpy(next_states))).data.numpy()\n target = copy.deepcopy(inferences_a.data.numpy())\n for l in range(self.batch_size):\n update_start = np.sum(self.command_arg_counts[:best_acts[l]])\n update_end = update_start + self.command_arg_counts[best_acts[l]]\n best_act, splited_inference = self.inference_split(inferences_b[l])\n tmp = np.sum(splited_inference[best_act])\n updates = np.array(reward_rates[l]) * (rewards[l] + (GAMMA * tmp))\n target[l,update_start:update_end] = updates\n # if l == 0:\n # print(['turn', 'dash', 'kick', 'wide', 'normal', 'narrow'][best_acts[l]], rewards[l], updates)\n self.optimizer.zero_grad()\n loss = nn.MSELoss()(inferences_a, Variable(torch.from_numpy(target)))\n loss.backward()\n self.optimizer.step()\n \n self.q_func_old = copy.deepcopy(self.q_func)\n \n def end(self, win=True):\n reward = 2000 if win else -500\n self.episode[-1][3] = reward\n self.episode[-1][4] = np.zeros(obs_num)\n timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')\n np.save('dataset_{}.npy'.format(timestamp), np.array(self.episode))\n self.train()\n\n self.episode = []\n self.total_reward = 0\n self.call_count = 0\n \n def save(self):\n torch.save(self.q_func.state_dict(), self.save_path)\n \n def load(self):\n self.q_func.load_state_dict(torch.load(self.save_path))\n self.q_func_old = copy.deepcopy(self.q_func)\n","sub_path":"dqn.py","file_name":"dqn.py","file_ext":"py","file_size_in_byte":9470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"457112804","text":"import random\n\nguessesTaken = 0\nguess = 0 \n\nprint('Hello! What is your name? ')\nplayerName = input()\n\nsecretNumber = random.randint(1,20)\n\nprint(f'Well, {playerName}, I am thinking of a number between 1 and 20.') \n\nfor guessesTaken in range(6):\n\n print('Take a guess')\n guess = int(input())\n \n if guess < secretNumber:\n print('Your guess is to low')\n if guess > secretNumber:\n print('Your guess is to high')\n if guess == secretNumber:\n break\n\nif guess == secretNumber:\n print(f'Good job, {playerName}! Your guessed'\n f'the secret number in {guessesTaken + 1} guesses')\nelse:\n print(f'Nope. The number i was thinking of was {secretNumber}.')\n","sub_path":"guess_the_number.py","file_name":"guess_the_number.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"599808062","text":"import os\r\nimport json\r\nimport sys\r\nimport time\r\nimport subprocess\r\ndir_path = os.path.dirname(os.path.realpath(__file__))\r\nproject_path = dir_path[0:dir_path.find(\"/targets\")]\r\nsys.path.append(project_path + \"/core/abstract_target\")\r\nfrom abstract_target import AbstractTarget\r\n\r\n\r\nclass TargetImpl(AbstractTarget):\r\n\r\n def __init__(self, target_cfg):\r\n super().__init__(target_cfg)\r\n self.speed_list = [\"n/a\"]\r\n\r\n # creates config file for p4 device\r\n def stamper_specific_config(self, cfg):\r\n f = open(self.realPath + \"/data/commands1_middlebox1.txt\", \"w+\")\r\n # delete old entries\r\n f.write(\"table_clear ingress.t_add_timestamp_header\" + \"\\n\")\r\n f.write(\"table_clear ingress.multicast\" + \"\\n\")\r\n f.write(\"table_clear ingress.t_l1_forwarding\" + \"\\n\")\r\n f.write(\"table_clear ingress.t_l2_forwarding\" + \"\\n\")\r\n f.write(\"table_clear ingress.t_l3_forwarding\" + \"\\n\")\r\n f.write(\"table_clear ingress.timestamp2\" + \"\\n\")\r\n f.write(\"table_clear egress.broadcast_mac\" + \"\\n\")\r\n f.write(\"table_clear ingress.t_add_timestamp_header_udp\" + \"\\n\")\r\n f.write(\"table_clear ingress.timestamp2_udp\" + \"\\n\")\r\n # delete old multicast groups (up to 10 groups)\r\n for group in range(1, 11):\r\n for node in range(0, 10):\r\n f.write(\"mc_node_dissociate \" + str(group) + \" \" + str(node) + \"\\n\")\r\n for node in range(0, 10):\r\n f.write(\"mc_node_destroy \" + str(node) + \"\\n\")\r\n for group in range(1, 11):\r\n f.write(\"mc_mgrp_destroy \" + str(group) + \"\\n\")\r\n\r\n node = 0\r\n # multicast grp for loadgen servers:\r\n f.write(\"mc_mgrp_create 1\" + \"\\n\")\r\n for server in cfg[\"loadgen_servers\"]:\r\n f.write(\"mc_node_create \" + str(node) + \" \" + server[\"p4_port\"] + \"\\n\")\r\n f.write(\"mc_node_associate 1 \" + str(node) + \"\\n\")\r\n node = node + 1\r\n\r\n # multicast grp for loadgen clients:\r\n f.write(\"mc_mgrp_create 2\" + \"\\n\")\r\n for client in cfg[\"loadgen_clients\"]:\r\n f.write(\"mc_node_create \" + str(node) + \" \" + client[\"p4_port\"] + \"\\n\")\r\n f.write(\"mc_node_associate 2 \" + str(node) + \"\\n\")\r\n node = node + 1\r\n\r\n # multicast groups for external host, because of bmv2 the original receiver needs to be included\r\n group = 3\r\n for host in cfg[\"loadgen_servers\"] + cfg[\"loadgen_clients\"]:\r\n host[\"mcast_grp\"] = str(group)\r\n f.write(\"mc_mgrp_create \" + str(group) + \"\\n\")\r\n f.write(\"mc_node_create \" + str(node) + \" \" + cfg[\"ext_host\"] + \"\\n\")\r\n f.write(\"mc_node_associate \" + str(group) + \" \" + str(node) + \"\\n\")\r\n node = node + 1\r\n f.write(\"mc_node_create \" + str(node) + \" \" + host[\"p4_port\"] + \"\\n\")\r\n f.write(\"mc_node_associate \" + str(group) + \" \" + str(node) + \"\\n\")\r\n node = node + 1\r\n group = group + 1\r\n\r\n if cfg['forwarding_mode'] == \"1\":\r\n server = cfg[\"loadgen_servers\"][0]\r\n client = cfg[\"loadgen_clients\"][0]\r\n f.write(\r\n \"table_add ingress.t_l1_forwarding ingress.send \" + cfg[\"dut1\"] + \" => \" + server[\r\n \"p4_port\"] + \"\\n\")\r\n f.write(\r\n \"table_add ingress.t_l1_forwarding ingress.send \" + cfg[\"dut2\"] + \" => \" + client[\r\n \"p4_port\"] + \"\\n\")\r\n else:\r\n f.write(\"table_add ingress.t_l1_forwarding ingress.no_op \" + cfg[\"dut1\"] + \" =>\\n\")\r\n f.write(\"table_add ingress.t_l1_forwarding ingress.no_op \" + cfg[\"dut2\"] + \" =>\\n\")\r\n\r\n f.write(\"table_add ingress.t_l1_forwarding ingress.no_op \" + cfg[\"ext_host\"] + \" =>\\n\")\r\n\r\n for server in cfg[\"loadgen_servers\"]:\r\n f.write(\"table_add ingress.t_l1_forwarding ingress.send \" + server[\"p4_port\"] + \" => \" + cfg[\"dut1\"] + \"\\n\")\r\n for client in cfg[\"loadgen_clients\"]:\r\n f.write(\"table_add ingress.t_l1_forwarding ingress.send \" + client[\"p4_port\"] + \" => \" + cfg[\"dut2\"] + \"\\n\")\r\n\r\n if int(cfg['forwarding_mode']) >= 2:\r\n # MC l2 group\r\n print(\"create table entries for l2 forwarding\")\r\n f.write(\"table_add ingress.t_l2_forwarding ingress.send_to_mc_grp \" + cfg[\"dut1\"] + \" 0xffffffffffff => 1\\n\")\r\n f.write(\"table_add ingress.t_l2_forwarding ingress.send_to_mc_grp \" + cfg[\"dut2\"] + \" 0xffffffffffff => 2\\n\")\r\n\r\n for server in cfg[\"loadgen_servers\"]:\r\n f.write(\"table_add ingress.t_l2_forwarding ingress.send \" + cfg[\"dut1\"] + \" 0x\" +\r\n server['loadgen_mac'].replace(\":\", \"\") + \" => \" + server[\"p4_port\"] + \"\\n\")\r\n\r\n for client in cfg[\"loadgen_clients\"]:\r\n f.write(\"table_add ingress.t_l2_forwarding ingress.send \" + cfg[\"dut2\"] + \" 0x\" +\r\n client['loadgen_mac'].replace(\":\", \"\") + \" => \" + client[\"p4_port\"] + \"\\n\")\r\n\r\n if cfg['forwarding_mode'] == \"3\":\r\n print(\"create table entries for l3 forwarding\")\r\n # IPv4 forwarding\r\n for server in cfg[\"loadgen_servers\"]:\r\n f.write(\"table_add ingress.t_l3_forwarding ingress.send \" + cfg[\"dut1\"] + \" \" + server[\"loadgen_ip\"] + \" => \" + server[\"p4_port\"] + \"\\n\")\r\n\r\n for client in cfg[\"loadgen_clients\"]:\r\n f.write(\"table_add ingress.t_l3_forwarding ingress.send \" + cfg[\"dut2\"] + \" \" + client[\"loadgen_ip\"] + \" => \" + client[\"p4_port\"] + \"\\n\")\r\n\r\n f.write(\"table_add egress.broadcast_mac egress.change_mac \" + cfg[\"ext_host\"] + \" => 0xffffffffffff\" + \"\\n\")\r\n\r\n if cfg[\"stamp_tcp\"] == \"checked\":\r\n offsets_start = [\"0x5\", \"0x8\"]\r\n offsets_end = [\"0x9\", \"0xc\"]\r\n for i in range(0, 2):\r\n if cfg[\"dut_1_duplicate\"] == \"checked\":\r\n f.write(\"table_add ingress.t_add_timestamp_header ingress.add_timestamp_header \" + offsets_start[i] + \" \" + cfg[\"dut2\"] + \" => \" + offsets_end[i] + \" 0\\n\")\r\n f.write(\"table_add ingress.timestamp2 ingress.add_timestamp2 \" + offsets_end[i] + \" 0x0f10 \" + cfg[\"dut1\"] + \" => \" + hex(int(cfg[\"multicast\"]) - 1) + \" 0\\n\") # multicast -1 because it begins at 0\r\n\r\n if cfg[\"dut_2_duplicate\"] == \"checked\":\r\n f.write(\"table_add ingress.t_add_timestamp_header ingress.add_timestamp_header \" + offsets_start[i] + \" \" + cfg[\"dut1\"] + \" => \" + offsets_end[i] + \" 1\\n\")\r\n f.write(\"table_add ingress.timestamp2 ingress.add_timestamp2 \" + offsets_end[i] + \" 0x0f10 \" + cfg[\"dut2\"] + \" => \" + hex(int(cfg[\"multicast\"]) - 1) + \" 1\\n\")\r\n\r\n if cfg[\"dut_1_duplicate\"] == \"checked\" and cfg[\"ext_host\"] != \"\":\r\n for server in cfg[\"loadgen_servers\"]:\r\n f.write(\"table_add ingress.multicast ingress.send_to_mc_grp \" + cfg[\"dut1\"] + \" \" + server[\"p4_port\"] + \" => \" + server[\"mcast_grp\"] + \"\\n\")\r\n\r\n if cfg[\"dut_2_duplicate\"] == \"checked\" and cfg[\"ext_host\"] != \"\":\r\n for client in cfg[\"loadgen_clients\"]:\r\n f.write(\"table_add ingress.multicast ingress.send_to_mc_grp \" + cfg[\"dut2\"] + \" \" + client[\"p4_port\"] + \" => \" + client[\"mcast_grp\"] + \"\\n\")\r\n\r\n ### UDP\r\n if cfg[\"stamp_udp\"] == \"checked\":\r\n if cfg[\"dut_1_duplicate\"] == \"checked\":\r\n f.write(\"table_add ingress.t_add_timestamp_header_udp ingress.add_timestamp_header_udp \" + cfg[\"dut2\"] + \" => \" + \" 0\\n\")\r\n f.write(\"table_add ingress.timestamp2_udp ingress.add_timestamp2 0x0f10 \" + cfg[\"dut1\"] + \" => \" + hex(int(cfg[\"multicast\"]) - 1) + \" 0\\n\") # multicast -1 because it begins at 0\r\n\r\n if cfg[\"dut_2_duplicate\"] == \"checked\":\r\n f.write(\"table_add ingress.t_add_timestamp_header_udp ingress.add_timestamp_header_udp \" + cfg[\"dut1\"] + \" => \" + \" 1\\n\")\r\n f.write(\"table_add ingress.timestamp2_udp ingress.add_timestamp2 0x0f10 \" + cfg[\"dut2\"] + \" => \" + hex(int(cfg[\"multicast\"]) - 1) + \" 1\\n\") # multicast -1 because it begins at 0\r\n\r\n f.close()\r\n\r\n\r\n # returns a dict[\"real_ports\"] and [\"logical_ports\"]\r\n def port_lists(self):\r\n temp = {\"real_ports\": [], \"logical_ports\": []}\r\n for i in range(0, 100):\r\n temp[\"real_ports\"].append(str(i))\r\n temp[\"logical_ports\"].append(str(i)) # = p4 ports\r\n return temp\r\n\r\n # deploy config file (table entries) again to p4 device (in case of changes)\r\n def deploy(self, cfg):\r\n self.stamper_specific_config()\r\n lag = \"SimplePreLAG\"\r\n cli = cfg[\"bmv2_dir\"] + \"/tools/runtime_CLI.py\"\r\n json_path = self.realPath + \"/data/\" + cfg[\"program\"] + \".json\"\r\n cmd = [cli, \"--pre\", lag, \"--json\", json_path, \"--thrift-port\", str(22223)]\r\n with open(self.realPath + \"/data/commands1_middlebox1.txt\", \"r\") as f:\r\n try:\r\n output = subprocess.check_output(cmd, stdin=f)\r\n except subprocess.CalledProcessError as e:\r\n print (e)\r\n\r\n # if not overwritten = everything is zero\r\n def read_p4_device(self, cfg):\r\n def error_cfg():\r\n for key in [\"total_deltas\", \"delta_counter\", \"min_delta\", \"max_delta\"]:\r\n cfg[key] = -1\r\n for key in [\"dut1\", \"dut2\", \"ext_host\"]:\r\n for direction in [\"ingress\", \"egress\"]:\r\n cfg[key + \"_num_\" + direction + \"_packets\"] = cfg[key + \"_num_\" + direction + \"_bytes\"] = -1\r\n for host in (cfg[\"loadgen_servers\"] + cfg[\"loadgen_clients\"]):\r\n for direction in [\"ingress\", \"egress\"]:\r\n host[\"num_\" + direction + \"_packets\"] = host[\"num_\" + direction + \"_bytes\"] = -1\r\n cfg[\"dut2_num_egress_stamped_packets\"] = cfg[\"dut2_num_egress_stamped_bytes\"] = cfg[\"dut1_num_ingress_stamped_packets\"] = cfg[\"dut1_num_ingress_stamped_bytes\"] = cfg[\"dut1_num_egress_stamped_packets\"] = cfg[\"dut1_num_egress_stamped_bytes\"] = cfg[\"dut2_num_ingress_stamped_packets\"] = cfg[\"dut2_num_ingress_stamped_bytes\"] = 0\r\n\r\n # generating the input for the bmv2 cli\r\n in_c = \"counter_read ingress.ingress_counter \"\r\n in_stamped_c = \"counter_read ingress.ingress_stamped_counter \"\r\n out_c = \"counter_read egress.egress_counter \"\r\n out_stamped_c = \"counter_read egress.egress_stamped_counter \"\r\n cli_input = \"register_read ingress.time_average 0\\nregister_read ingress.time_average 1\\nregister_read ingress.time_delta_min_max 0\\nregister_read ingress.time_delta_min_max 1\\n\"\r\n for host in [\"dut1\", \"dut2\", \"ext_host\"]:\r\n cli_input = cli_input + in_c + cfg[host] + \"\\n\"\r\n cli_input = cli_input + out_c + cfg[host] + \"\\n\"\r\n cli_input = cli_input + in_stamped_c + cfg[host] + \"\\n\"\r\n cli_input = cli_input + out_stamped_c + cfg[host] + \"\\n\"\r\n\r\n for host in (cfg[\"loadgen_servers\"] + cfg[\"loadgen_clients\"]):\r\n cli_input = cli_input + in_c + host[\"p4_port\"] + \"\\n\"\r\n cli_input = cli_input + out_c + host[\"p4_port\"] + \"\\n\"\r\n cli_input = cli_input + in_stamped_c + host[\"p4_port\"] + \"\\n\"\r\n cli_input = cli_input + out_stamped_c + host[\"p4_port\"] + \"\\n\"\r\n\r\n\r\n try:\r\n cmd = [cfg[\"bmv2_dir\"] + \"/targets/simple_switch/sswitch_CLI.py\", \"--thrift-port\", \"22223\"]\r\n output = subprocess.run(cmd, stdout=subprocess.PIPE, input=cli_input.encode()).stdout.decode('UTF-8')\r\n lines = output.split(\"\\n\")\r\n for line in lines:\r\n print(line)\r\n\r\n if len(lines) > 10: # make sure there is no error, if it's not greater than 10 lines; else bmv2 not running\r\n # parsing output of bmv2 CLI\r\n start = 0\r\n for line in lines:\r\n start = start + 1\r\n if line.find(\"Control utility for runtime P4 table manipulation\") > -1:\r\n break\r\n\r\n cfg[\"total_deltas\"] = int(lines[start][lines[start].find(\"[0]=\")+5:])*1000 # because bmv2 is in microseconds but nanoseconds are expected\r\n cfg[\"delta_counter\"] = int(lines[start+1][lines[start+1].find(\"[1]=\") + 5:])\r\n cfg[\"min_delta\"] = int(lines[start+2][lines[start+2].find(\"[0]=\") + 5:])*1000\r\n cfg[\"max_delta\"] = int(lines[start+3][lines[start+3].find(\"[1]=\") + 5:])*1000\r\n counter = start+4\r\n for key in [\"dut1\", \"dut2\", \"ext_host\"]:\r\n for direction in [\"ingress\", \"egress\", \"ingress_stamped\", \"egress_stamped\"]:\r\n cfg[key+\"_num_\"+direction+\"_packets\"] = int(lines[counter][lines[counter].find(\"packets=\")+8:lines[counter].find(\",\")])\r\n cfg[key+\"_num_\"+direction+\"_bytes\"] = int(lines[counter][lines[counter].find(\"bytes=\")+6:-1])\r\n counter = counter + 1\r\n for host in (cfg[\"loadgen_servers\"] + cfg[\"loadgen_clients\"]):\r\n for direction in [\"ingress\", \"egress\", \"ingress_stamped\", \"egress_stamped\"]:\r\n host[\"num_\"+direction+\"_packets\"] = int(lines[counter][lines[counter].find(\"packets=\")+8:lines[counter].find(\",\")])\r\n host[\"num_\"+direction+\"_bytes\"] = int(lines[counter][lines[counter].find(\"bytes=\")+6:-1])\r\n counter = counter + 1\r\n\r\n else: # if an error occurs set everything to -1\r\n print(\"Error in BMV2 read_p4_device. Sure the mininet/bmv2 instance is running?\")\r\n error_cfg()\r\n\r\n except subprocess.CalledProcessError as e:\r\n print(\"Error in BMV2 read_p4_device\")\r\n print (e)\r\n error_cfg()\r\n\r\n return cfg\r\n\r\n def get_pid(self):\r\n lines = subprocess.run([self.realPath + \"/scripts/mn_status.sh\"], stdout=subprocess.PIPE).stdout.decode(\"utf-8\").split(\"\\n\")\r\n try:\r\n if int(lines[0]) > 0:\r\n pid = int(lines[0])\r\n else:\r\n pid = 0\r\n except:\r\n pid = 0\r\n return pid\r\n\r\n def p4_dev_status(self, cfg):\r\n pid = self.get_pid()\r\n print(pid)\r\n if pid > 0:\r\n dev_status = \"Yes! PID: \" + str(pid)\r\n running = True\r\n try:\r\n with open(self.realPath + \"/data/mn.log\", \"r\") as log:\r\n lines_pm = [\"There is no need to deploy the current config explicitly.\",\r\n \"The settings were applied at the start of mininet.\",\r\n \"Mininet link and port configuration: \"]\r\n for line in log.readlines():\r\n lines_pm.append(line)\r\n except:\r\n lines_pm = [\"Error while reading mininet output\"]\r\n else:\r\n dev_status = \"not running\"\r\n running = False\r\n lines_pm = [\"No portmanager available\",\r\n \"Are you sure you selected a target before?\"]\r\n\r\n return lines_pm, running, dev_status\r\n\r\n\r\n # starts specific p4 software on device\r\n def start_p4_dev_software(self, cfg):\r\n subprocess.run([self.realPath + \"/scripts/start_mininet.sh\", self.realPath + \"/scripts/netgen.py\", cfg[\"bmv2_dir\"]])\r\n\r\n def stop_p4_dev_software(self, cfg):\r\n pid = self.get_pid()\r\n if pid > 0:\r\n subprocess.run([self.realPath + \"/scripts/stop_mininet.sh\"])\r\n\r\n # reset registers of p4 device\r\n def reset_p4_registers(self, cfg):\r\n cli_input = \"register_reset ingress.time_average\\nregister_reset ingress.time_delta_min_max\\n\"\r\n cli_input += \"counter_reset egress.egress_counter\\ncounter_reset ingress.ingress_counter\"\r\n cli_input += \"counter_reset egress.egress_stamped_counter\\ncounter_reset ingress.ingress_stamped_counter\\n\"\r\n cmd = [cfg[\"bmv2_dir\"] + \"/targets/simple_switch/sswitch_CLI.py\", \"--thrift-port\", \"22223\"]\r\n\r\n output = subprocess.run(cmd, stdout=subprocess.PIPE, input=cli_input.encode()).stdout.decode('UTF-8')\r\n\r\n def check_if_p4_compiled(self, cfg):\r\n return True if self.get_pid() > 0 else False, \"If BMV2 is running, the selected program \" + str(cfg[\"program\"]) + \" is compiled.\"","sub_path":"targets/bmv2/bmv2_middlebox_v8.py","file_name":"bmv2_middlebox_v8.py","file_ext":"py","file_size_in_byte":16279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"33439102","text":"\nimport os\nimport inspect\nimport nodechecker.notification.notification\nimport nodechecker.notification.snmp\nimport nodechecker.config\nimport nodechecker.node\n\nnode = None\nconf = None\nsender = None\n\n\ndef setup():\n global node, conf, sender\n node = nodechecker.node.Node(hostname='test1', port=10, cloud_zone='cloudzone1', ip_address_public='1.2.3.4',\n instance_id=1, cluster_id=1, machine_id=1)\n test_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n p1_dir = os.path.abspath(os.path.join(test_dir, os.pardir))\n p2_dir = os.path.abspath(os.path.join(p1_dir, os.pardir))\n conf = nodechecker.config.Config(os.path.join(p2_dir, 'conf', 'nodechecker', 'etc', 'nodechecker.conf'))\n #conf = nodechecker.config.Config(os.path.join(test_dir, 'nodechecker.conf'))\n sender = nodechecker.notification.snmp.TrapSender(conf, node)\n\n\ndef test_send():\n global node, conf, sender\n ntf_1 = nodechecker.notification.notification.Notification(category='fatal', severity='error')\n ntf_2 = nodechecker.notification.notification.Notification(category='dead', severity='warn')\n\n notifications = [ntf_1, ntf_2]\n error = 0\n try:\n sender.send(notifications)\n except Exception:\n error = 1\n assert error == 0\n\n\ndef test_truncate():\n global node, conf, sender\n word_1 = ''\n word_2 = '123456789'\n word_3 = 3\n\n assert sender.truncate(word_1, 0) == ''\n assert sender.truncate(word_1, 1) == ''\n assert sender.truncate(word_2, 0) == ''\n assert sender.truncate(word_2, 1) == '1'\n assert sender.truncate(word_2, 9) == '123456789'\n assert sender.truncate(word_2, 10) == '123456789'\n\n # should throw TypeError exception\n thrown = False\n try:\n sender.truncate(word_3, 0) == ''\n except TypeError:\n thrown = True\n assert thrown is True\n","sub_path":"nodechecker/nodechecker/lib/python/test/snmp_tests/unit_tests/test_snmp.py","file_name":"test_snmp.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"314735748","text":"import dataclasses\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional\n\nimport log\nfrom classproperties import classproperty\n\nfrom . import hooks\nfrom .converters import Converter, map_type\nfrom .managers import InstanceManager, ModelManager\n\n\n@dataclass\nclass ModelMeta:\n datafile_attrs: Optional[Dict[str, Converter]] = None\n datafile_pattern: Optional[str] = None\n\n datafile_manual: bool = False\n datafile_defaults: bool = False\n\n\nclass Model:\n\n Meta: ModelMeta = ModelMeta()\n\n def __post_init__(self):\n with hooks.disabled():\n log.debug(f'Initializing {self.__class__} object')\n\n self.datafile = build_datafile(self)\n\n path = self.datafile.path\n exists = self.datafile.exists\n\n if path:\n log.debug(f'Datafile path: {path}')\n log.debug(f'Datafile exists: {exists}')\n\n if exists:\n self.datafile.load(first_load=True)\n elif path:\n self.datafile.save()\n\n hooks.apply(self, self.datafile, build_datafile)\n\n log.debug(f'Initialized {self.__class__} object')\n\n @classproperty\n def datafiles(cls) -> ModelManager: # pylint: disable=no-self-argument\n return ModelManager(cls)\n\n\ndef build_datafile(obj, root=None) -> InstanceManager:\n try:\n return object.__getattribute__(obj, 'datafile')\n except AttributeError:\n log.debug(f\"Building 'datafile' for {obj.__class__} object\")\n\n m = getattr(obj, 'Meta', None)\n pattern = getattr(m, 'datafile_pattern', None)\n attrs = getattr(m, 'datafile_attrs', None)\n manual = getattr(m, 'datafile_manual', False)\n defaults = getattr(m, 'datafile_defaults', False)\n\n if attrs is None and dataclasses.is_dataclass(obj):\n attrs = {}\n log.debug(f'Mapping attributes for {obj.__class__} object')\n for field in dataclasses.fields(obj):\n self_name = f'self.{field.name}'\n if pattern is None or self_name not in pattern:\n attrs[field.name] = map_type(field.type)\n\n return InstanceManager(\n obj, attrs=attrs, pattern=pattern, manual=manual, defaults=defaults, root=root\n )\n\n\ndef create_model(cls, *, attrs=None, pattern=None, manual=None, defaults=None):\n \"\"\"Patch datafile attributes on to an existing dataclass.\"\"\"\n log.debug(f'Converting {cls} to a datafile model')\n\n if not dataclasses.is_dataclass(cls):\n raise ValueError(f'{cls} must be a dataclass')\n\n # Patch Meta\n\n m = getattr(cls, 'Meta', ModelMeta())\n\n if attrs is not None:\n m.datafile_attrs = attrs\n if pattern is not None:\n m.datafile_pattern = pattern\n\n if not hasattr(cls, 'Meta') and manual is not None:\n m.datafile_manual = manual\n if not hasattr(cls, 'Meta') and defaults is not None:\n m.datafile_defaults = defaults\n\n cls.Meta = m\n\n # Patch __init__\n\n init = cls.__init__\n\n def modified_init(self, *args, **kwargs):\n with hooks.disabled():\n init(self, *args, **kwargs)\n Model.__post_init__(self)\n\n cls.__init__ = modified_init\n cls.__init__.__doc__ = init.__doc__\n\n return cls\n","sub_path":"datafiles/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"555244154","text":"for i in range(int(input())):\n a, b = map(int, input().split())\n for j in range(1, a+b+1, 2):\n a = a - j\n if a < 0:\n print(\"Bob\")\n break\n b = b - (j+1)\n if b < 0:\n print(\"Limak\")\n break","sub_path":"CodeChef/bear_candies.py","file_name":"bear_candies.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"84745171","text":"#configuration du support#\n\nfrom tkinter import* \nfrom random import*\nfenetre = Tk()\nfenetre.title('Jeu de compatibilite')\nfenetre.configure(width=400,height=200,bg='#FFCCCC')\n\nL_prenom_1=Label(fenetre,text=\"Entrez le nom 1:\",fg='#CC0033',width=20)\nL_prenom_2=Label(fenetre,text=\"Entrez le nom 2:\",fg='#CC0033',width=20)\nPrenom_1=StringVar()\nPrenom_2=StringVar()\nE_prenom_1=Entry(fenetre,width=20)\nE_prenom_2=Entry(fenetre,width=20)\nB1=Button(fenetre,text=\"Valider\",width=20,command=recuperation)\n\nL_prenom_1.place(x=50, y=10)\nL_prenom_2.place(x=50, y=50)\nB1.place(x=125, y=150)\nE_prenom_1.place(x=200, y=10)\nE_prenom_2.place(x=200, y=50)\n\n#Configuraton deuxième fenêtre#\n\ndef recuperation():\n P_1 = E_prenom_1.get()\n P_2 = E_prenom_2.get()\n L_prenom_1.place_forget()\n L_prenom_2.place_forget()\n E_prenom_1.place_forget()\n E_prenom_2.place_forget()\n B1.place_forget()\n L_astro_1= Label(text=\"Entrez le signe astrologique de nom 1:\")\n L_astro_2= Label(text=\"Entrez le signe astrologique de nom 2:\")\n L_astro_1.place(x=40,y=0)\n L_astro_2.place(x=40,y=50)\n E_astro_1=Entry(fenetre,width=20)\n E_astro_2=Entry(fenetre,width=20)\n B2= Button(fenetre,text=\"Valider\",width=20,command=alea)\n B2.place(x=55,y=80)\n\n#configuration de la fenêtre de résultat#\n\ndef alea():\n nb=randint(1,100)\n L5= Label(fenetre,text=\"Calcul du pourcentage en cours...\",fg='black')\n L5.configure(text=\"Le pourcentage de compatibilite est de\"+ str(nb)+'%')\n L5.place(x=100,y=50)\n B3= Button(fenetre,text=\"Quitter\",width=10,command=fenetre.destroy)\n B3.place(x=150,y=100)\n\n\n\n#main window\nfenetre.mainloop()","sub_path":"Projet_brouillon.py","file_name":"Projet_brouillon.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"346437654","text":"import sys\n\nftable = open(sys.argv[1], 'r')\ntext = ftable.read().split(\"\\n\")\n\nclust = []\nfor line in text:\n#\tprint(line)\n\tfields = line.split()\n\tif len(fields) != 4:\n\t\tcontinue\n\tfound = False\n\tfor i in range(0, len(clust)):\n\t\tif fields[0] in clust[i]:\n\t\t\tif (not (fields[1] in clust[i]) and float(fields[3])>0.85):\n\t\t\t\tclust[i].append(fields[1])\n\t\t\tfound = True\n\t\t\tbreak\n\tif not found:\n\t\tclust.append([])\n\t\tclust[len(clust)-1].append(fields[0])\n\t\tif float(fields[3])>0.85:\n\t\t\tclust[len(clust)].append(fields[1])\n#\tprint(clust)\n\n#print(clust)\n#print(len(clust), sum([len(i) for i in clust]))\n\ncfile = open(sys.argv[2], 'r')\ntext = cfile.read().split(\"\\n\")\n\ncl2cl = {}\nfor line in text:\n\tfields = line.split()\n\tif len(fields) > 0:\n\t\tif fields[0] == \"group:\":\n\t\t\tng = int(fields[1])\n\t\telse:\n\t\t\tfor i in range(0, len(clust)):\n\t\t\t\tif fields[0] in clust[i]:\n\t\t\t\t\tcl2cl[i] = ng\n#print(cl2cl) \n\nfor i in range(1, ng+1):\n\tprint(\"Family #{0}\".format(i))\n\tno = 0\n\tfor j in cl2cl.keys():\n\t\tif cl2cl[j] == i:\n\t\t\tno += 1\n\t\t\tprint(\"\\tObject #{0}\".format(no))\n\t\t\tfor k in clust[j]:\n\t\t\t\tprint(\"\\t\\t{0}\".format(k))\n","sub_path":"old/clust.py","file_name":"clust.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"290995233","text":"#coding=utf-8\n#-------------------------------------------------------------------------------------------\n#作者:吴俊威 日期:2018年10月\n#内容:即有宝脚本生成与运行\n#--------------------------------------------------------------------------------------------\n# import time\nfrom run_main import *\nfrom jy_case.jyb_temp import *\nfrom appium import webdriver\n# import time\nfrom mobiletest.appcomm import *\nfrom common.fun_t import *\nfrom common.mysql_pub import *\nfrom common.mysql_pubtwo import *\nfrom common.oracle_pub import *\nfrom common.logger import Log\ncpath = PATH(\"..\\config\\yaml\\jyb\\jybcase1.yaml\")\n\ndef app_run_test(getid,uname,marknum):\n Log().info(\"即有宝提单开始执行\")\n # OracleUtil(dbname).oracle_sql(\"update dafy_sales.registers set status='n' where reg_number=1647 and reg_val_code=1805\") #关闭协议支付\n # OracleUtil(dbname).oracle_sql(\"update dafy_sales.sys_parameters set para_value=0 where para_id='LIVE_BODY_CHECK_SWITCH'\") #关闭活体检测\n try:\n markval=str(uname)+\"_\"+str(getid)+\"_\"+str(marknum)\n con_name,con_num,pc_type,pc_ip = getrun_db(getid)\n delpath=PATH(\"../case\")\n filename = 'test_'+str(uname)+\"_\"+str(getid)\n del_files(delpath,filename)\n time.sleep(2)\n for j in range(con_num):\n try:\n getparam,paramcount = param_db(uname)\n print(\"统计行:%s\"%paramcount)\n count_sys = 0\n for i in range(paramcount):\n try:\n filep = PATH(\"../case/test_\")+str(uname)+\"_\"+str(getid)+\"_\"+str(i)+\".py\"\n if getparam[i]['paraml'] == \"a\":\n remove_lines(PATH(\"../jy_case/jyb_temp.py\"),filep,\"#默认误删\")\n print(\"生成a合同case\")\n if getparam[i]['paraml'] == \"y\":\n remove_lines(PATH(\"../jy_case/jyb_temp.py\"),filep,\"#默认误删\")\n remove_lines(filep,filep,\"流程测试a合同\")\n print(\"生成y合同case\")\n if getparam[i]['paraml'] == \"s\":\n remove_lines(PATH(\"../jy_case/jyb_temp.py\"),filep,\"#默认误删\")\n remove_lines(filep,filep,\"流程测试a合同\")\n remove_lines(filep,filep,\"流程测试y合同\")\n print(\"生成s合同case\")\n if getparam[i]['paraml'] == \"pr\":\n remove_lines(PATH(\"../jy_case/jyb_temp.py\"),filep,\"#默认误删\")\n remove_lines(filep,filep,\"流程测试r合同\")\n remove_lines(filep,filep,\"流程测试s合同\")\n remove_lines(filep,filep,\"流程测试a合同\")\n remove_lines(filep,filep,\"流程测试y合同\")\n print(\"生成pr合同case\")\n if getparam[i]['paraml'] == \"r\":\n remove_lines(PATH(\"../jy_case/jyb_temp.py\"),filep,\"#默认误删\")\n remove_lines(filep,filep,\"流程测试s合同\")\n remove_lines(filep,filep,\"流程测试a合同\")\n remove_lines(filep,filep,\"流程测试y合同\")\n print(\"生成r合同case\")\n with open(filep,'r',encoding='UTF-8') as ui:\n data = ui.readlines()\n for inx,line in enumerate(data):\n if inx == 14:\n val = str(\"newcon_name=\")+\"\\\"\"+str(\"默认空箺\")+\"\\\"\"+\"\\n\"+str(\"con_name=\")+\"\\\"\"+str(con_name)+\"\\\"\"+\"\\n\"+str(\"cpath=\")+\"PATH(\\\"..\\config\\yaml\\jyb\\jybcase1.yaml\\\")\"+\"\\n\"+str(\"pc_type=\")+\"\\\"\"+str(pc_type)+\"\\\"\"+\"\\n\"\\\n +str(\"pc_ip=\")+\"\\\"\"+str(pc_ip)+\"\\\"\"+\"\\n\"+str(\"getparam=\")+str(getparam[i])+\"\\n\"+str(\"uname=\")+\"\\\"\"+str(uname)+\"\\\"\"+\"\\n\"+str(\"markval=\")+\"\\\"\"+str(markval)+\"\\\"\"+\"\\n\"+str(\"class jyb_order_\")+str(uname)+\"_\"+str(getid)+\"_\"+str(i+1)+str(\"(unittest.TestCase):\")+\"\\n\"\n data[inx] = val\n else:\n data[inx] = line\n with open(filep,'w',encoding='UTF-8') as oi:\n oi.writelines(data)\n except Exception as e:\n print(e)\n count_sys = count_sys+i+1\n print(count_sys)\n except Exception as e:\n print(e)\n time.sleep(2)\n ruleval=\"test_\"+str(uname)+\"_\"+str(getid)+\"_*.py\"\n all_case = add_case(caseName=\"case\", rule=ruleval)\n run_casenew(all_case,\"result_wei.html\")\n report_path = os.path.join(cur_path, \"report\")\n print(report_path)\n report_file = get_reportfile(report_path,'result_wei.html')\n shutil.copyfile(report_file,os.path.join(cur_path, \"mobiletest/templates/result_wei.html\"))\n if count_sys > 0:\n run_sat = \"ok\"\n else:\n run_sat = \"fail\"\n except Exception as e:\n print(e)\n run_sat = \"fail\"\n return run_sat,markval\n","sub_path":"jy_case/jytest.py","file_name":"jytest.py","file_ext":"py","file_size_in_byte":5336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"227001615","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author: Marc\n# @Date: 2015-03-02 21:23:23\n# @Last Modified by: Marc\n# @Last Modified time: 2015-03-04 21:16:28\n\nWTF_CSRF_ENABLED \t\t= True\nSECRET_KEY \t\t\t\t= 'qjefncjaiarto85730ij#'\n\n# Sijax\nSIJAX_STATIC_PATH \t\t= 'static/js/sijax/'\nSIJAX_JSON_URI\t\t\t= '/static/js/sijax/json2.js'\n\n# Pagination\nPER_PAGE \t\t\t\t= 10\nCSS_FRAMEWORK \t\t\t= 'bootstrap3'\nLINK_SIZE \t\t\t\t= 'sm'\n# decide whether or not a single page returns pagination\nSHOW_SINGLE_PAGE = False","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"104282527","text":"from keras import layers, models, optimizers\nfrom keras import backend as K\nimport numpy as np\n\nclass Actor:\n '''\n Actor (Policy) Model.\n \n Model: policy function mu(s | theta^{mu}).\n inputs: states values\n outputs: predicted actions.values\n Optimization: gradient descent\n '''\n\n def __init__(self, state_size, action_size, action_low, action_high, learning_rate):\n \"\"\"Initialize parameters and build model.\n \n Params\n ======\n state_size (int): Dimension of each state\n action_size (int): Dimension of each action\n action_low (array): Min value of each action dimension\n action_high (array): Max value of each action dimension\n learning_rate \n \"\"\"\n\n self.state_size = state_size\n self.action_size = action_size\n self.action_low = action_low\n self.action_high = action_high\n self.action_range = self.action_high - self.action_low\n self.learning_rate = learning_rate\n # model\n self.model = None\n # function for policy update\n self.train_fn = None\n # create model\n self.build_model()\n\n def build_model(self):\n '''Build an actor (policy) network.'''\n\n ########################### Network ###########################\n # input layer (states)\n states = layers.Input(shape=(self.state_size,), name='states')\n\n # hidden1\n h1 = layers.Dense(units=4, activation=None, use_bias=False)(states)\n h1 = layers.BatchNormalization()(h1)\n h1 = layers.Activation('relu')(h1)\n h1 = layers.Dropout(0.5)(h1)\n \n # hidden2\n h2 = layers.Dense(units=16, activation=None, use_bias=False)(h1)\n h2 = layers.BatchNormalization()(h2)\n h2 = layers.Activation('relu')(h2)\n h2 = layers.Dropout(0.5)(h2)\n '''\n # hidden3\n h3 = layers.Dense(units=32, activation=None, use_bias=False)(h2)\n h3 = layers.BatchNormalization()(h3)\n h3 = layers.Activation('relu')(h3)\n h3 = layers.Dropout(0.5)(h3)\n '''\n # output layer with sigmoid activation; output range -> [0,1]\n raw_actions = layers.Dense(units=self.action_size, activation='sigmoid',\n name='raw_actions')(h2)\n\n # Scale [0, 1] output for each action dimension to proper range\n actions = layers.Lambda(lambda x: (x * self.action_range) + self.action_low,\n name='actions')(raw_actions)\n\n # Create Keras model\n self.model = models.Model(inputs=states, outputs=actions)\n\n ##################### Loss & Optimization ######################\n \n # Define loss function using action value (Q value) gradients\n action_gradients = layers.Input(shape=(self.action_size,))\n loss = K.mean(-action_gradients * actions)\n\n # Define optimizer and training function\n optimizer = optimizers.Adam(lr=self.learning_rate)\n updates_op = optimizer.get_updates(params=self.model.trainable_weights, loss=loss)\n self.train_fn = K.function(\n inputs=[self.model.input, action_gradients, K.learning_phase()],\n outputs=[],\n updates=updates_op)\n\nclass Critic:\n '''\n Critic (Value) Model.\n \n Model: q_hat(s,a,w).\n inputs: states and action values\n output: predicted Q-values of the inputs\n Optimization:\n target: better estimated reward of the greedy-policy\n R_t+1 + gamma * Q(s_t+1, policy(s_t+1))\n loss: estimated reward\n mean squared error of \"(target) - (predicted Q-values of the inputs)\"\n '''\n\n def __init__(self, state_size, action_size, learning_rate):\n \"\"\"Initialize parameters and build model.\n Params\n ======\n state_size (int): Dimension of each state\n action_size (int): Dimension of each action\n learning_rate:\n \"\"\"\n self.state_size = state_size\n self.action_size = action_size\n self.learning_rate = learning_rate\n # model\n self.model = None\n # action gradient for policy update\n self.get_action_gradients = None\n # create model\n self.build_model()\n\n def build_model(self):\n \"\"\"Build a critic (value) network that maps (state, action) pairs -> Q-values.\"\"\"\n \n ########################### Network ###########################\n # input layers\n states = layers.Input(shape=(self.state_size,), name='states')\n actions = layers.Input(shape=(self.action_size,), name='actions')\n\n # hidden layer for state pathway\n h1_states = layers.Dense(units=64, activation=None, use_bias=False)(states)\n h1_states = layers.BatchNormalization()(h1_states)\n h1_states = layers.Activation('relu')(h1_states)\n h1_states = layers.Dropout(0.5)(h1_states)\n \n h2_states = layers.Dense(units=128, activation=None, use_bias=False)(h1_states)\n h2_states = layers.BatchNormalization()(h2_states)\n h2_states = layers.Activation('relu')(h2_states)\n h2_states = layers.Dropout(0.5)(h2_states)\n '''\n h3_states = layers.Dense(units=32, activation=None, use_bias=False)(h2_states)\n h3_states = layers.BatchNormalization()(h3_states)\n h3_states = layers.Activation('relu')(h3_states)\n h3_states = layers.Dropout(0.5)(h3_states)\n '''\n # Add hidden layer(s) for action pathway\n h1_actions = layers.Dense(units=64, activation=None, use_bias=False)(actions)\n h1_actions = layers.BatchNormalization()(h1_actions)\n h1_actions = layers.Activation('relu')(h1_actions)\n h1_states = layers.Dropout(0.5)(h1_states)\n \n h2_actions = layers.Dense(units=128, activation=None, use_bias=False)(h1_actions)\n h2_actions = layers.BatchNormalization()(h2_actions)\n h2_actions = layers.Activation('relu')(h2_actions)\n h2_states = layers.Dropout(0.5)(h2_states)\n '''\n h3_actions = layers.Dense(units=32, activation=None, use_bias=False)(h2_actions)\n h3_actions = layers.BatchNormalization()(h3_actions)\n h3_actions = layers.Activation('relu')(h3_actions)\n h3_states = layers.Dropout(0.5)(h3_states)\n '''\n # Combine state and action pathways\n add_net = layers.Add()([h2_states, h2_actions])\n add_net = layers.Activation('relu')(add_net)\n\n # Add final output layer to prduce action values (Q values)\n Q_values = layers.Dense(units=1, name='q_values')(add_net)\n\n # Create Keras model\n self.model = models.Model(inputs=[states, actions], outputs=Q_values)\n \n ###################### Loss & Optimization ######################\n \n # Define optimizer and compile model for training with built-in loss function\n optimizer = optimizers.Adam(lr=self.learning_rate)\n self.model.compile(optimizer=optimizer, loss='mse')\n\n ########## gradient caluculation for the actor network ##########\n \n # Compute action gradients (derivative of Q values w.r.t. to actions)\n action_gradients = K.gradients(Q_values, actions)\n\n # Define an additional function to fetch action gradients (to be used by actor model)\n self.get_action_gradients = K.function(\n inputs=[*self.model.input, K.learning_phase()],\n outputs=action_gradients)","sub_path":"agents/actor_critic.py","file_name":"actor_critic.py","file_ext":"py","file_size_in_byte":7517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"360530156","text":"length = 81 + 1\ninformation = \"@RELATION hog\\n\\n\"\nfor i in range(1,length):\n information += \"@ATTRIBUTE a\" + str(i) + \" REAL\\n\"\ninformation += \"@ATTRIBUTE class {1,2,3,4,5}\\n\\n\"\ninformation += \"@DATA\\n\"\n\nlabels = open(\"/home/emre/Desktop/labels.txt\", \"r\")\nread = \"/home/emre/Desktop/Feature Vectors/HOG/SCUT-FBP-\"\nresult = \"/home/emre/Desktop/Project/arff files/hog.arff\"\n\nfile = open(result, \"w+\")\nfile.write(information)\n\nfor i in range(1, 501):\n\n foo = open(read + str(i) + \".txt\", \"r\")\n for j in range(length-1):\n token = foo.readline()\n float_number = float(token)\n file.write(str(float_number) + \", \")\n foo.close()\n\n label = int(labels.readline())\n file.write(str(label) + \"\\n\")\n\nfile.close()\nlabels.close()","sub_path":"arffGenerator/HogGenerator.py","file_name":"HogGenerator.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"494573419","text":"\"\"\"ImportManager\n\nManages imported modules and protects against concurrent imports.\n\nKeeps lists of all imported Python modules and templates as well as other\nconfig files used by Webware for Python. Modules which are not directly\nimported can be monitored using hupper. This can be used to detect changes in\nsource files, templates or config files in order to reload them automatically.\n\"\"\"\n\n\nimport sys\nimport warnings\n\nfrom os.path import getmtime, isfile, join\nfrom importlib.util import module_from_spec, spec_from_file_location\nfrom importlib.machinery import (\n ModuleSpec, SourceFileLoader, SourcelessFileLoader)\n\n\nclass ImportManager:\n \"\"\"The import manager.\n\n Keeps track of the Python modules and other system files that have been\n imported and are used by Webware.\n \"\"\"\n\n _instance = None\n\n def __new__(cls, *args, **kwargs):\n \"\"\"Create ImportManager as a singleton.\"\"\"\n if not cls._instance:\n cls._instance = super().__new__(cls, *args, **kwargs)\n return cls._instance\n\n def __init__(self):\n \"\"\"Initialize import manager.\"\"\"\n self._fileList = {}\n self._moduleFiles = {}\n self._notifyHook = None\n self._reloader = self.getReloader()\n\n def getReloader(self):\n \"\"\"Get the current reloader if the application is monitored.\"\"\"\n reloader = None\n with warnings.catch_warnings():\n # ignore deprecation warnings from hupper\n warnings.filterwarnings('ignore', category=DeprecationWarning)\n try:\n import hupper\n except ImportError:\n pass\n else:\n if hupper.is_active():\n try:\n reloader = hupper.get_reloader()\n except RuntimeError:\n pass\n if reloader:\n print('Application is monitored for reloading.')\n print()\n return reloader\n\n def moduleFromSpec(self, spec):\n \"\"\"Load the module with the given module spec.\"\"\"\n if not spec or not isinstance(spec, ModuleSpec):\n raise TypeError(f'Invalid spec: {spec!r}')\n try:\n module = module_from_spec(spec)\n except Exception:\n # Also record file paths which weren't successfully loaded, which\n # may happen due to a syntax error in a servlet, because we also\n # want to know when such a file is modified:\n if spec.origin:\n self.recordFile(spec.origin)\n raise\n self.recordModule(module)\n spec.loader.exec_module(module)\n return module\n\n def findSpec(self, name, path, fullModuleName=None):\n \"\"\"Find the module spec for the given name at the given path.\"\"\"\n if not name or not isinstance(name, str):\n raise TypeError(f'Invalid name: {name!r}')\n if not path or not isinstance(path, str):\n raise TypeError(f'Invalid path: {path!r}')\n\n # find package\n packageDirectory = join(path, name)\n packageFileName = '__init__.py'\n filePath = join(packageDirectory, packageFileName)\n if isfile(filePath):\n return spec_from_file_location(name, filePath)\n\n # find package as byte code without source\n filePath += 'c'\n if isfile(filePath):\n return spec_from_file_location(name, filePath)\n\n # find module\n fileName = f'{name}.py'\n filePath = join(path, fileName)\n if isfile(filePath):\n if fullModuleName:\n name = fullModuleName\n loader = SourceFileLoader(name, filePath)\n return spec_from_file_location(name, filePath, loader=loader)\n\n # find module as optimized byte code without source\n filePath += 'c'\n if isfile(filePath):\n loader = SourcelessFileLoader(name, filePath)\n return spec_from_file_location(name, filePath, loader=loader)\n\n raise ImportError(f'No module named {name!r}')\n\n def fileList(self, update=True):\n \"\"\"Return the list of tracked files.\"\"\"\n if update:\n # Update list of files of imported modules\n moduleNames = [modname for modname in sys.modules\n if modname not in self._moduleFiles]\n if moduleNames:\n self.recordModules(moduleNames)\n return self._fileList\n\n def notifyOfNewFiles(self, hook):\n \"\"\"Register notification hook.\n\n Called by someone else to register that they'd like to know\n when a new file is imported.\n \"\"\"\n self._notifyHook = hook\n\n def watchFile(self, path, moduleName=None, getmtime=getmtime):\n \"\"\"Add more files to watch without importing them.\"\"\"\n mtime = getmtime(path)\n self._fileList[path] = mtime\n if moduleName:\n self._moduleFiles[moduleName] = path\n # send notification that this file was imported\n if self._notifyHook:\n self._notifyHook(path, mtime)\n # let reloader know that this was imported\n if self._reloader:\n self._reloader.watch_files([path])\n\n def recordModule(self, module, isfile=isfile):\n \"\"\"Record a module.\"\"\"\n moduleName = getattr(module, '__name__', None)\n if not moduleName or moduleName not in sys.modules:\n return\n fileList = self._fileList\n # __orig_file__ is used for PSP and Cheetah templates; we want\n # to record the source filenames, not the auto-generated modules:\n f = getattr(module, '__orig_file__', None)\n if f and f not in fileList:\n try:\n if isfile(f):\n self.watchFile(f, moduleName)\n except OSError:\n pass\n else:\n f = getattr(module, '__file__', None)\n if f and f not in fileList:\n # record the .py file corresponding to each .pyc\n if f[-4:].lower() == '.pyc':\n f = f[:-1]\n try:\n if isfile(f):\n self.watchFile(f, moduleName)\n else:\n self.watchFile(join(f, '__init__.py'))\n except OSError:\n pass\n\n def recordModules(self, moduleNames=None):\n \"\"\"Record a list of modules (or all modules).\"\"\"\n if moduleNames is None:\n moduleNames = sys.modules\n for modname in moduleNames:\n mod = sys.modules[modname]\n self.recordModule(mod)\n\n def recordFile(self, filename, isfile=isfile):\n \"\"\"Record a file.\"\"\"\n if isfile(filename):\n self.watchFile(filename)\n\n def fileUpdated(self, filename, update=True, getmtime=getmtime):\n \"\"\"Check whether file has been updated.\"\"\"\n fileList = self.fileList(update)\n try:\n oldTime = fileList[filename]\n except KeyError:\n return True\n try:\n newTime = getmtime(filename)\n except OSError:\n return True\n if oldTime >= newTime:\n return False\n fileList[filename] = newTime\n # Note that the file list could be changed while running this\n # method in a monitor thread, so we don't use iteritems() here:\n for moduleName, moduleFile in self._moduleFiles.items():\n if moduleFile == filename:\n module = sys.modules.get(moduleName)\n return not module or not getattr(\n module, '__donotreload__', False)\n return True # it's not a module, we must reload\n\n def updatedFile(self, update=True, getmtime=getmtime):\n \"\"\"Check whether one of the files has been updated.\"\"\"\n fileList = self.fileList(update)\n for filename, oldTime in list(fileList.items()):\n try:\n newTime = getmtime(filename)\n except OSError:\n return filename\n if oldTime >= newTime:\n continue\n fileList[filename] = newTime\n for moduleName, moduleFile in self._moduleFiles.items():\n if moduleFile == filename:\n module = sys.modules.get(moduleName)\n if module and getattr(module, '__donotreload__', False):\n break\n return filename # it's a module that needs to be reloaded\n else:\n return filename # it's not a module, we must reload\n\n def delModules(self, includePythonModules=False, excludePrefixes=None):\n \"\"\"Delete imported modules.\n\n Deletes all the modules that have been imported unless they are part\n of Webware. This can be used to support auto reloading.\n \"\"\"\n moduleFiles = self._moduleFiles\n fileList = self._fileList\n for modname in moduleFiles:\n if modname == __name__:\n continue\n filename = self._moduleFiles[modname]\n if not includePythonModules:\n if not filename or filename.startswith(sys.prefix):\n continue\n for prefix in excludePrefixes or []:\n if modname.startswith(prefix):\n break\n else:\n try:\n del sys.modules[modname]\n except KeyError:\n pass\n try:\n del moduleFiles[modname]\n except KeyError:\n pass\n try:\n del fileList[filename]\n except KeyError:\n pass\n","sub_path":"webware/ImportManager.py","file_name":"ImportManager.py","file_ext":"py","file_size_in_byte":9681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"326723846","text":"\r\n# execfile('product_discovery_functions.py'); \r\n\r\n\r\n\"\"\"\r\ndependency: execfile('feed_generation_functions.py');\r\n\"\"\"\r\n\r\n\r\ndef find_prod_names(cached_data1, score_maps1, para, to_print=True):\r\n\t\"\"\"\r\n\t\tcompute_fun() function for compute_blog_data_concept_names()\r\n\t\"\"\"\r\n\tprod_names=para['prod_names']; \r\n\ti=para['i'];\r\n\treturn [{'name':name,} for name in set(prod_names[i]) ]; \r\n\r\ndef find_is_concept_names(cached_data1, score_maps1, para=None, to_print=True):\r\n\t\"\"\"\r\n\t\tcompute_fun() function for compute_blog_data_concept_names()\r\n\t\tuse global function check_product_name()\r\n\t\"\"\"\r\n\tif not para or not para['concepts']:\r\n\t\tif not para: para=defaultdict(list); \r\n\t\tpara['concepts']=['is_concept', 'noun_concept']; # 'noun_title'\r\n\tif 'score_maps' in para.keys(): \r\n\t\tscore_maps1=para['score_maps'];\r\n\tfilters_map=[];\r\n\tfor concept_fn in para['concepts']:\r\n\t\tfilters_map.append(\t{'name':'is_product', 'type':'rel', 'fn':concept_fn,\r\n\t\t\t\t\t'keywords1':score_maps1['is_obj_names1'], \r\n\t\t\t\t\t'keywords2':score_maps1['is_obj_names2'], \r\n\t\t\t\t\t} );\r\n\t#print(filters_map);\r\n\t#\r\n\t#sb=subject_builder();\r\n\t#sb.subjectize_relations(cached_data1['relations']);\r\n\t#print_list(cached_data1['relations'], ['class', 'sbj','verb','adj','obj']);\r\n\tsf=subject_filter();\r\n\tsf.filters_map=filters_map;\r\n\tsf.relations=cached_data1['relations']; \r\n\tsf.blog_pos=cached_data1['blog_pos'];\r\n\trel=sf.search_objects('is_product', to_print=0);\r\n\t#print(sf.var);\r\n\tif to_print: print_list([t for t in sf.var['is_product'] ], ['sbj','verb','adj','obj','class']); \r\n\t#\r\n\tprods=[];\r\n\tnames=[];\r\n\tfor rel in sf.var['is_product']:\r\n\t\t#print(rel);\r\n\t\tif not rel['sbj']: continue; \r\n\t\tname=T(rel['sbj']);\r\n\t\tif not name or name in names: continue;\r\n\t\tnames.append(name);\r\n\t\ttry: \r\n\t\t\tif not check_product_name(name, to_print=to_print): continue;\r\n\t\texcept: \r\n\t\t\tpass; \r\n\t\t#\r\n\t\tprods.append({'name':name, 'rel':rel});\r\n\t\t#\r\n\treturn prods;\r\n\r\ndef find_howto_names(cached_data1, score_maps1=None, para=None, to_print=True):\r\n\t\"\"\"\r\n\t\tcompute_fun() function for compute_blog_data_concept_names()\r\n\t\"\"\"\r\n\trb=relationship_builder(None);\r\n\tfor pos in cached_data1['blog_pos']: replace_howto_tags(pos); \r\n\trb.set_pos(cached_data1['blog_pos']);\r\n\trules=rb.get_howto_rules();\r\n\trb.parse_np_relations(rules, to_print=0);\r\n\tprods=[];\r\n\tnames=[];\r\n\tfor rel in rb.np_relations:\r\n\t\tif rel['np_sbj']: rel['sbj']=rel['np_sbj'][0];\r\n\t\tif rel['np_obj']: rel['obj']=rel['np_obj'][0];\r\n\t\tif rel['np_verb']: rel['verb']=rel['np_verb'][0];\r\n\t\t#\r\n\t\tif not rel['obj'] or not rel['verb']: continue; \r\n\t\tname=T(rel['verb']+rel['obj']);\r\n\t\tif not name or name in names: continue;\r\n\t\tnames.append(name);\r\n\t\ttry: \r\n\t\t\tif not check_product_name(name, to_print=to_print): continue; \r\n\t\texcept: \r\n\t\t\tpass; \r\n\t\t#\r\n\t\tprods.append({'name':name, 'rel':rel});\r\n\t\t#\r\n\treturn prods;\r\n\r\ndef find_rule_topics(cached_data1, score_maps1=None, para=None, to_print=True):\r\n\t\"\"\"\r\n\t\tcompute_fun() function for compute_blog_data_concept_names()\r\n\t\"\"\"\r\n\trules=[]; \r\n\trb=relationship_builder(None);\r\n\trb.set_pos(cached_data1['blog_pos']);\r\n\tif para and para['rules']: \r\n\t\trules=para['rules']\r\n\telse:\r\n\t\trules=rb.get_baby_rules();\r\n\trb.parse_np_relations(rules, to_print=0);\r\n\tprods=[];\r\n\tnames=[];\r\n\tfor rel in rb.np_relations:\r\n\t\tif rel['np_sbj']: rel['sbj']=rel['np_sbj'][0];\r\n\t\tif rel['np_obj']: rel['obj']=rel['np_obj'][0];\r\n\t\tif rel['np_verb']: rel['verb']=rel['np_verb'][0];\r\n\t\t#\r\n\t\tname=T(rel['sbj']);\r\n\t\tif not name or name in names: continue;\r\n\t\tnames.append(name);\r\n\t\ttry:\r\n\t\t\tif not check_product_name(name, to_print=to_print): continue; \r\n\t\texcept: \r\n\t\t\tpass; \r\n\t\t#\r\n\t\tprods.append({'name':name, 'rel':rel});\r\n\t\t#\r\n\treturn prods;\r\n\r\n\r\ndef compute_blog_data_concept_names(blog_data, type_id, subtype_id, score_maps1, compute_fun, para=None, to_recompute=False, to_print=True, to_compute_context=True, to_save=True): \r\n\tproduct_names=[ [] for i in range(0, len(blog_data)) ]; \r\n\tif type_id==None: type_id='default';\r\n\tfor i in range(len(blog_data)): \r\n\t\tif to_print:\r\n\t\t\tif 'title' in blog_data[i].keys():\r\n\t\t\t\tprint('concept_names (%s - %s): post %d/%d: %s'%(type_id, subtype_id, i, len(blog_data), escape_html(blog_data[i]['title']))); \r\n\t\t\telif 'name' in blog_data[i].keys():\r\n\t\t\t\tprint('concept_names (%s - %s): post %d/%d: %s'%(type_id, subtype_id, i, len(blog_data), escape_html(blog_data[i]['name']))); \t\t\t\r\n\t\tpost=[];\r\n\t\tif isinstance(blog_data[i], dict) and 'data_t' in blog_data[i].keys(): \r\n\t\t\tpost=[blog_data[i]];\r\n\t\telse:\r\n\t\t\tpost=query_post_data(blog_data[i], category=workspace, solr_server=SOLR_SERVER);\r\n\t\tif not post: continue;\r\n\t\tif 'data_t' not in post[0].keys(): continue; \r\n\t\tcached_data1=decode_post_data(post[0]['data_t']);\r\n\t\tif not cached_data1: continue;\r\n\t\t#\r\n\t\trs=[];\r\n\t\ttry:\r\n\t\t\trs,s=solr_query_var({'category':workspace+'__concept_prods', 'type_id_s':type_id, 'subtype_id_s':subtype_id, 'post_id_s':cached_data1['id'] }, page=-1 );\r\n\t\t\t#rs,s=solr_query_var({'category':workspace+'__concept_prods', 'type_id_s':'default', 'post_id_s':blog_data[0]['id'] }, page=-1 )\r\n\t\texcept: \r\n\t\t\tpass; \r\n\t\t#\r\n\t\tprods=[];\r\n\t\tif rs and not to_recompute: \r\n\t\t\tif 'prods_t' in rs[0].keys(): \r\n\t\t\t\tprods=decode_post_data(rs[0]['prods_t']);\r\n\t\telse:\r\n\t\t\tif para: para['i']=i;\r\n\t\t\tprods=compute_fun(cached_data1, score_maps1, para=para, to_print=to_print);\r\n\t\t\tfor prod in prods: \r\n\t\t\t\tprod['type_id']=type_id;\r\n\t\t\t\tprod['subtype_id']=subtype_id;\r\n\t\t\t#\r\n\t\t\tif to_compute_context:\r\n\t\t\t\trb=relationship_builder(score_maps1);\r\n\t\t\t\trb.blog_id=[0 for j in range(len(cached_data1['blog_pos']))]; #use original idset\r\n\t\t\t\trb.blog_pos1=cached_data1['blog_pos'];\r\n\t\t\t\trb.relations=cached_data1['relations']; \r\n\t\t\t\tfor prod in prods: \r\n\t\t\t\t\t(left_verbs, right_verbs, adj_words, adj_attrs)=([],[],[],[]);\r\n\t\t\t\t\tprod_relations1=rb.search_subject_relations(prod['name'], rb.relations, short_name=10, long_name=True);\r\n\t\t\t\t\tfor rel in prod_relations1: \r\n\t\t\t\t\t\tif rel['class']=='left_verb': \r\n\t\t\t\t\t\t\tleft_verbs.append(T(rel['verb']));\r\n\t\t\t\t\t\telif rel['class']=='right_verb': \r\n\t\t\t\t\t\t\tright_verbs.append(T(rel['verb']));\r\n\t\t\t\t\t\telif rel['class']=='sent_phrase': \r\n\t\t\t\t\t\t\tadj_words.append(T(rel['adj']));\r\n\t\t\t\t\t\t\tif rel['obj']: \r\n\t\t\t\t\t\t\t\tadj_attrs.append(T(rel['adj']+rel['obj'])); \r\n\t\t\t\t\tprod['left_verbs']=left_verbs; \r\n\t\t\t\t\tprod['right_verbs']=right_verbs; \r\n\t\t\t\t\tprod['adj_words']=adj_words; \r\n\t\t\t\t\tprod['adj_attrs']=adj_attrs; \r\n\t\t\t#\r\n\t\t\trecord={'category':workspace+'__concept_prods', \r\n\t\t\t\t'type_id_s':type_id, \r\n\t\t\t\t'subtype_id_s':subtype_id, \r\n\t\t\t\t'post_id_s':cached_data1['id'], \r\n\t\t\t\t'date_dt': cached_data1['date_dt'],\r\n\t\t\t\t'updated_dt': datetime.now(),\r\n\t\t\t\t'prod_names_t': ':'+':'.join([r['name'] for r in prods])+':',\r\n\t\t\t\t'prods_t': encode_post_data(prods),\r\n\t\t\t\t}; \r\n\t\t\tif to_save:\r\n\t\t\t\tif rs: \r\n\t\t\t\t\trecord['id']=rs[0]['id']; \r\n\t\t\t\telse:\r\n\t\t\t\t\trecord['id']=solr_new_id('%s-%s-%s-%s'%(workspace+'__concept_prods', type_id, subtype_id, cached_data1['id']));\r\n\t\t\t\ts=solr_update_var(record); \r\n\t\t\t\ts=solr_commit();\r\n\t\t\telse: \r\n\t\t\t\tprint(\"record not saved!!\"); \r\n\t\t\t#\r\n\t\t#print(prods); \r\n\t\tproduct_names[i]=prods;\r\n\t\tif to_print: print_list(prods, ['name','left_verbs','right_verbs','adj_words','adj_attrs']); \r\n\t\t#if to_print: print_list([t['rel'] for t in prods], ['sbj','verb','adj','obj','class']); \r\n\treturn product_names;\r\n\r\n\r\ndef index_product_names(workspace, pnames): \r\n\t\"\"\"\r\n\t\t(need to use mysql, name search is not reliable here)\r\n\t\tindex inhouse product names, \r\n\t\treturn a list of the associated ids\r\n\t\"\"\"\r\n\tcategory_id=workspace + '__product_name' \r\n\tproduct_ids=[]; \r\n\tfor i, pname in enumerate(pnames): \r\n\t\tp,s=solr_query_var({'category': category_id, 'name': pname['name']});\r\n\t\tpid='';\r\n\t\tif p: \r\n\t\t\tpid=p[0]['id']; \r\n\t\telse: \r\n\t\t\tpid=solr_new_id('%s-%s'%(category_id, pname['name']));\r\n\t\t\tp,s=solr_update_var({'category': category_id, 'name': pname['name'], 'id':pid});\r\n\t\t\tsolr_commit(); \r\n\t\tproduct_ids.append(pid);\r\n\treturn product_ids; \r\n\r\n\r\ndef index_product_articles(workspace, product_title_names, blog_post, product_title_index, product_ids, to_recompute=False):\r\n\t\"\"\"\r\n\t\tindex product names found from each article\r\n\t\tproduct_title_names: product names found from articles\r\n\t\tblog_pos: articles\r\n\t\tproduct_title_index: product indices associated with each name\r\n\t\tproduct_ids: product id associated with each product index, product id is the id for workspace + '__product_name'\r\n\t\"\"\"\r\n\tcategory_id=workspace + '__product_index' \r\n\tfor i,names in enumerate(product_title_names):\r\n\t\tbid=blog_post[i]['id']; \r\n\t\tb,s=solr_query_var({'category': category_id, 'bid': bid});\r\n\t\tif b and not to_recompute: continue; \r\n\t\tif to_recompute: \r\n\t\t\tb,s=solr_delete_var({'category': category_id, 'bid': bid});\r\n\t\t\tsolr_commit(); \r\n\t\tpid_names=defaultdict(list); \r\n\t\tfor name in names: #each product name\r\n\t\t\tfor p in product_title_index[name]: # each product index associated with the product name\r\n\t\t\t\tpid_names[product_ids[p]].append(name); #use product id\r\n\t\tfor pid in pid_names.keys(): #create one record for each (bid, pid) \r\n\t\t\trecord={'category': category_id, 'bid': bid, 'pid':pid, 'names':encode_post_data(pid_names[pid]) }; \r\n\t\t\trecord['id']=solr_new_id('%s-%s-%s'%(category_id, bid, pid));\r\n\t\t\tb,s=solr_update_var(record); \r\n\t\tsolr_commit();\r\n\r\ndef apriori_products(product_names, L, min_support, min_confidence):\r\n\tproduct_sets=[set(names) for names in product_names ];\r\n\tN=len(product_sets); \r\n\tLLC=[defaultdict(int) for i in range(L+1)]; \r\n\tfor names in product_sets: \r\n\t\tfor name in names: \r\n\t\t\tLLC[1][(name,)]+=1; \r\n\tLLcache=[[defaultdict(list) for i in range(L+1)] for j in range(N) ]; \r\n\tfor j in range(N): \r\n\t\tLLcache[j][1]=[(name,) for name in product_sets[j] if LLC[1][(name,)]>=min_support]\r\n\t#\r\n\tCF=[[] for i in range(L+1)];\r\n\tLL=[[] for i in range(L+1)];\r\n\tLL[1]=sorted([(nn,c) for nn,c in LLC[1].items() if c>=min_support], key=lambda k: k[1], reverse=True); \r\n\t#\r\n\tfor l in range(2,L+1):\r\n\t\tfor i,names in enumerate(product_sets):\r\n\t\t\tif len(names)>=30: print(i, len(names));\r\n\t\t\t#subsets=subset_combinations([name for name in names if name in LL[l-1]], l);\r\n\t\t\tsubsets=subset_combinations2(LLcache[i], LLC, l, min_support);\r\n\t\t\tfor nn in subsets: \r\n\t\t\t\tLLC[l][tuple(sorted(nn))]+=1; \r\n\t\thas_confidence=(min_confidence==None);\r\n\t\tif min_confidence != None: \r\n\t\t\tfor nn,c in LLC[l].items(): \r\n\t\t\t\tif c>=min_support: \r\n\t\t\t\t\tfor nn1 in [nn2 for k in range(1, l) for nn2 in subset_combinations(nn, k)]: \r\n\t\t\t\t\t\tcf=LLC[l][nn]*1.0/LLC[len(nn1)][tuple(nn1)];\r\n\t\t\t\t\t\tif cf >= min_confidence:\r\n\t\t\t\t\t\t\thas_confidence=True;\r\n\t\t\t\t\t\t\tCF[len(nn1)].append([cf, (nn1, LLC[len(nn1)][tuple(nn1)]), (list(set(nn)-set(nn1)), LLC[l][nn])]);\r\n\t\tLL[l]=sorted([(nn,c) for nn,c in LLC[l].items() if c>=min_support and has_confidence ], key=lambda k: k[1], reverse=True);\r\n\treturn LLC, LL, CF; \r\n\r\ndef subset_combinations2(LLcache1, LLC, L, min_support):\r\n\tnames_list=[names for names in LLcache1[L-1] if LLC[L-1][tuple(names)]>=min_support]; \r\n\t#if len(names_list)>30: print(names_list);\r\n\tfound_names=set(); \r\n\told_names=set([tuple(names) for names in names_list]);\r\n\tfor i in range(0, len(names_list)):\r\n\t\tfor j in range(i, len(names_list)): \r\n\t\t\tnewset=set(names_list[i])|set(names_list[j]);\r\n\t\t\tif len(newset)!=L: continue; \r\n\t\t\tif tuple(newset) in found_names: continue; \r\n\t\t\tis_goodset=True;\r\n\t\t\tfor subset in subset_combinations(list(newset), L-1): \r\n\t\t\t\tif tuple(subset) not in old_names: \r\n\t\t\t\t\tis_goodset=False; \r\n\t\t\t\t\tbreak;\r\n\t\t\tif not is_goodset: continue; \r\n\t\t\tfound_names.add(tuple(newset) );\r\n\t\t\t#if len(names_list)>30: print(newset);\r\n\tLLcache1[L]=found_names; \r\n\t#if len(names_list)>20: \r\n\t#\tprint('------');\r\n\t#\tprint(found_names);\r\n\treturn found_names;\r\n\r\ndef subset_combinations(names, L):\r\n\t#exhaustive combinations of len L\r\n\tN=len(names);\r\n\tif N[<[^\\(\\*\\)]*/NN.*><.*/CD>]*', overlap=False);\r\n\t\t\t\tfor noun in nouns: \r\n\t\t\t\t\trelease_filtered_names[i].append(T(noun));\r\n\t\t\t\tproducts[cached_data1['id']].append(r['product_s']); \r\n\t\tprint('---'); \r\n\t\tprint(release_filtered_names[i]);\r\n\t\tprint(' '); \r\n\t#\r\n\treturn release_filtered_names;\r\n\r\ndef filter_prod_names(cached_data1, search_methods, score_maps1):\r\n\t\"\"\"\r\n\t\tfilter cached_data1 for potential product names \r\n\t\"\"\"\r\n\tsub=subject_builder(); \r\n\tsub.set_relations(cached_data1['relations'], to_print=0);\r\n\trb=relationship_builder(score_maps1);\r\n\trb.blog_id=[0]*len(cached_data1['blog_pos']);\r\n\trb.blog_pos1=cached_data1['blog_pos'];\r\n\trb.relations=cached_data1['relations'];\r\n\tfound_sbjs=[]; \r\n\tsummr=text_summarizer();\r\n\ta=htql.Tools(); \r\n\tif 'release_filter' in search_methods: \r\n\t\tfor sbj, items in sub.subjects.items():\r\n\t\t\tfor item in items: \r\n\t\t\t\tif item['target']=='sbj':\r\n\t\t\t\t\tscore=rb.item_left_verb_score(item['rel'], score_maps1['release_filter_keyword_map']);\r\n\t\t\t\t\tif score>0.5:\r\n\t\t\t\t\t\tfound_sbjs.append({'sbj':sbj, 'verb':item['rel']['verb'], 'method':'release_verb', 'isentence':item['rel']['isentence'], 'class':item['rel']['class'] });\r\n\tif 'offer_verb' in search_methods: \r\n\t\tfor sbj, items in sub.subjects.items():\r\n\t\t\tfor item in items: \r\n\t\t\t\tif item['target']=='sbj':\r\n\t\t\t\t\tscore=rb.item_right_verb_score(item['rel'], score_maps1['offer_keyword_map']);\r\n\t\t\t\t\tif score>0.5:\r\n\t\t\t\t\t\tfound_sbjs.append({'sbj':sbj, 'verb':item['rel']['verb'], 'method':'offer_verb', 'isentence':item['rel']['isentence'], 'class':item['rel']['class'] });\r\n\tif 'release_noun' in search_methods: \r\n\t\trb.np_relations=[];\r\n\t\trules=rb.get_renoun_rules(score_maps1['release_noun_names1']);\r\n\t\trb.parse_np_relations(rules, to_print=0);\r\n\t\tfor item in rb.np_relations: \r\n\t\t\tif item['np_sbj'] and item['np_obj']:\r\n\t\t\t\tfound_sbjs.append({'sbj':item['np_sbj'][0], 'verb':item['np_obj'][0], 'method':'release_noun', 'isentence':item['isentence'], 'class':item['class']});\r\n\tif 'num_amount' in search_methods: \r\n\t\trb.np_relations=[];\r\n\t\trules=rb.get_renum_rules(score_maps1['num_amount_names1']);\r\n\t\trb.parse_np_relations(rules, to_print=0);\r\n\t\tfor item in rb.np_relations: \r\n\t\t\tif item['np_obj']:\r\n\t\t\t\tfor item1 in item['np_sbj']: \r\n\t\t\t\t\tfound_sbjs.append({'sbj':item1, 'verb':item['np_obj'][0], 'method':'num_amount', 'isentence':item['isentence'], 'class':item['class']});\r\n\tsbj_names=[]; \r\n\treleased_prods=[];\r\n\tfor item in found_sbjs:\r\n\t\tsbj=item['sbj'];\r\n\t\tprodname=T(sbj);\r\n\t\tif prodname in sbj_names: continue; \r\n\t\tsbj_names.append(prodname); \r\n\t\tproduct_phrases=summr.find_product_phrases(rb, prodname);\r\n\t\tis_obj=[t[0].lower() for phrase in product_phrases['is_phrases'] for t in phrase['r']['obj'] ] + prodname.lower().split(); \r\n\t\tis_obj+=[n[:-1] for n in is_obj if n[-1]=='s'] + [n[:-1] for n in is_obj if n[-1]=='.'];\r\n\t\tis_names=[T(phrase['r']['obj']) for phrase in product_phrases['is_phrases'] ];\r\n\t\tcompany_names=[T(phrase['r']['obj']) for phrase in product_phrases['release_phrases'] ];\r\n\t\toffer_names=[T(phrase['r']['obj']) for phrase in product_phrases['offer_phrases'] ];\r\n\t\t#\r\n\t\tprod_relations=rb.search_subject_relations(prodname, short_name=3, long_name=True);\r\n\t\tsent_attrs=rb.relation_sent_scores(prod_relations);\r\n\t\tsent_scores=[t['score'] for t in sent_attrs if t['score']<-0.01 or t['score']>0.01];\r\n\t\t#\r\n\t\tprint(cached_data1['blog_pos'][item['isentence']]);\r\n\t\tsbj_extended=sbj; \r\n\t\tif 'num_amount' not in search_methods: \r\n\t\t\tsbj1=a.reSearchList(cached_data1['blog_pos'][item['isentence']], \"<.*/VBG>?\"+''.join(['<%s/%s>'%(escape_relist(s[0]), escape_relist(s[1]) ) for s in sbj])+r\"([<[^(that|which|before|after)]*/IN><.*/VBG>][<.*/DT|NN|NNP|JJ|NNS|CC|CD|PRP|VBG>]+)*\");\r\n\t\t\tif sbj1: sbj_extended=sbj1[0];\r\n\t\tprint(' ');\r\n\t\tprint(('-->', T(sbj_extended), '<--' ,T(item['verb']), item['method'], T(cached_data1['blog_pos'][item['isentence']]) ) ); \r\n\t\tprint(is_names);\r\n\t\tprint(company_names);\r\n\t\tprint(offer_names);\r\n\t\tprint(' ');\r\n\t\treleased_prod={'category':workspace+'__released_prod', \r\n\t\t\t\t\t'post_id_s':cached_data1['id'],\r\n\t\t\t\t\t'product_s': T(sbj_extended), \r\n\t\t\t\t\t'isentence_i': item['isentence'],\r\n\t\t\t\t\t'verb_s': T(item['verb']), \r\n\t\t\t\t\t'class_s': item['class'],\r\n\t\t\t\t\t'sbj_pos_s': encode_post_data(sbj), \r\n\t\t\t\t\t'is_obj_s': encode_post_data(is_obj), \r\n\t\t\t\t\t'is_names_s': encode_post_data(is_names), \r\n\t\t\t\t\t'company_names_s': encode_post_data(company_names), \r\n\t\t\t\t\t'offer_names_s': encode_post_data(offer_names),\r\n\t\t\t\t\t'sent_attrs_t': encode_post_data(sent_attrs),\r\n\t\t\t\t\t'blog_date_dt': cached_data1['date_dt'],\r\n\t\t\t\t};\r\n\t\told,s=solr_query_var({'category':workspace+'__released_prod', \r\n\t\t\t\t\t'post_id_s':cached_data1['id'],\r\n\t\t\t\t\t'product_s': T(sbj_extended), \r\n\t\t\t\t\t'isentence_i': item['isentence'],\r\n\t\t\t\t\t'verb_s': T(item['verb']), \r\n\t\t\t\t});\r\n\t\tif old: released_prod['id']=old[0]['id']; \r\n\t\telse: released_prod['id']=solr_new_id('%s-%s-%s'%(released_prod['category'], released_prod['post_id_s'], released_prod['product_s']));\r\n\t\ts=solr_update_var(released_prod); \r\n\t\ts=solr_commit();\r\n\t\treleased_prods.append(released_prod);\r\n\treturn released_prods; \r\n\r\n\r\n\r\n\r\n\"\"\"\r\nworkspace='blog-electronics';\r\nexecfile('load_data.py');\r\nblog_data=load_var('blog_data');\r\n\r\n\r\nb,s=solr_query_var({'category':workspace, 'date_dt':(datetime.now() - timedelta(4), datetime.now() ) }, page=None); \r\nfor i,b1 in enumerate(b): \r\n\tcached_data1=decode_post_data(b1['data_t']); \r\n\tdevices=[v for v in cached_data1['relations'] if v['class']=='sbj_is' and (set(T(v['obj']).lower().split()) & set(['product','device', 'tool', 'tv', 'smartphone', 'computer', 'camera', 'phone', 'platform', 'pc', 'version', 'update', 'system', 'software', 'hardware', 'gadget', 'laptop', 'tablet', 'console', 'game']) ) ];\r\n\t#devices=[v for v in cached_data1['relations'] if v['class']=='sbj_is' and (set(T(v['obj']).lower().split()) & set(['company', 'investor', 'corporation']) ) ];\r\n\t#devices=[v for v in cached_data1['relations'] if v['class']=='sbj_is' and (set(T(v['obj']).lower().split()) & set(['person', 'chief', 'director', 'ceo','chairman','manager','businessman', 'reporter', 'executive', 'president', 'officer', 'cto', 'cfo']) ) ];\r\n\t#devices=[v for v in cached_data1['relations'] if v['class']=='sbj_is' ];\r\n\tif devices:\r\n\t\tprint(i, '=========== ', cached_data1['name'], ' ==========');\r\n\t\tprint_list(devices, ['sbj','verb','obj']); \r\n\t\tfor device in devices: \r\n\t\t\tprint('----------------------');\r\n\t\t\trel=[s['rel'] for s in cached_data1['subjects'][tuple(device['sbj'])] if s['target']=='sbj' ];\r\n\t\t\tprint_list(rel, ['sbj','verb','adj','obj','class']);\r\n\t\r\ni=537;\r\ncached_data1=decode_post_data(b[i]['data_t']); \r\nsubjects=cached_data1['subjects']\r\n\r\n\r\n\t\r\n\"\"\"\r\n","sub_path":"www/cgi-bin/product_discovery_functions.py","file_name":"product_discovery_functions.py","file_ext":"py","file_size_in_byte":19779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"149740374","text":"from __future__ import division, print_function, unicode_literals\r\n\r\nfrom sacred import Experiment\r\nfrom sacred.observers import FileStorageObserver\r\nfrom utils.custom_observer import CustomObserver\r\n\r\nfrom config import ingredient_config\r\nfrom utils.path_utils import filelist, remove_files\r\nimport logging\r\n\r\nimport os\r\nfrom collections import OrderedDict\r\nimport joblib\r\nimport numpy as np\r\nimport json\r\nimport pandas as pd\r\nimport random\r\nimport glob\r\nfrom functools import partial\r\nimport shutil\r\nimport re\r\nimport random\r\nimport collections\r\n\r\nimport utils.scoring\r\n#from utils.results import aggregate\r\nfrom utils.excel_writer import df_to_excel\r\nfrom utils.observers import get_observers\r\nfrom utils.plotting import plot_curves\r\nfrom utils.df_helper import filter_df, best_by_group, best_row, stringify_cols, stringify\r\n\r\nfrom utils.path_utils import find_files, copy_files\r\nfrom visualization.figures import bar_chart_grouped\r\n\r\nfrom utils.proj_setup import setup_dir\r\n\r\nfrom constants import *\r\n\r\n\r\n# Define experiment and load ingredients\r\nex = Experiment('step211_event_detect_cv_best', ingredients=[ingredient_config])\r\n\r\n\r\n@ex.config\r\ndef cfg(config):\r\n \r\n \r\n \r\n '''\r\n Input and outputs\r\n '''\r\n \r\n # Source\r\n source = 'cv_tune_event_detect'\r\n \r\n # Destination\r\n dest = 'cv_best_event_detect'\r\n \r\n \r\n '''\r\n Paths\r\n '''\r\n \r\n # Source directory\r\n source_ = config[source]\r\n dest_ = config[dest]\r\n scratch = setup_dir(dest_, config['root'], config['scratch'])\r\n \r\n \r\n \r\n cmap = 'tab10'\r\n alpha = 0.8\r\n figsize=(8,3)\r\n width = 0.2\r\n\r\n # Labeling\r\n\r\n '''\r\n Evaluation metrics\r\n '''\r\n average = config['average']\r\n metric = config['metric']\r\n\r\n column_map = config['column_map'] \r\n\r\n float_format = config['float_format']\r\n \r\n \r\n\r\n\r\n cases = OrderedDict()\r\n\r\n\r\n header = 'Determinant'\r\n cases['base'] = {'Determinant': '_MICRO', 'label': 'micro'}\r\n\r\n\r\n\r\n groupby = []\r\n order = {}\r\n\r\n params = ['rnn_type', 'rnn_hidden_size', 'xfmr_type', 'num_epochs', 'max_len', 'dropout_input', 'attn_type', 'attn_size', 'attn_dropout']\r\n\r\n \r\n\r\n #for k, v in cases.items():\r\n # v['eval_range'] = END_TO_END\r\n\r\n \r\n\r\n # Create observers\r\n file_observ = FileStorageObserver.create(dest_)\r\n cust_observ = CustomObserver(dest_)\r\n ex.observers.append(file_observ)\r\n ex.observers.append(cust_observ)\r\n \r\ndef filt(row, criteria):\r\n\r\n out = all([(row[c] is v) or (row[c] == v) for c, v in criteria.items()])\r\n\r\n return out\r\n \r\ndef as_list(X, ndigits = 3):\r\n \r\n \r\n X = [str(round(x, ndigits)) for x in X]\r\n \r\n return '[{}]'.format(', '.join(X)) \r\n \r\n\r\n \r\n \r\n@ex.automain\r\ndef main(source_, dest_, \r\n column_map, metric, \r\n float_format,\r\n average, \r\n params, cases,\r\n cmap, alpha, figsize, width, groupby, order, header\r\n ):\r\n \r\n\r\n\r\n # Find all result files\r\n files = find_files(source_, SCORES_FILE, recursive=True)\r\n logging.info(\"source_:\\t{}\".format(source_))\r\n logging.info(\"Score filenames:\\t{}\".format(SCORES_FILE))\r\n logging.info(\"Result file count:\\t{}\".format(len(files)))\r\n logging.info(\"Looping on subsets...\")\r\n\r\n df_dict = OrderedDict()\r\n logging.info(\"\\nLoading files\")\r\n n = len(files)\r\n for i, fn in enumerate(files):\r\n \r\n # Use result directory as description\r\n descrip = os.path.basename(os.path.dirname(fn))\r\n \r\n logging.info(\"Loading {} of {}: {}\".format(i + 1, n, descrip))\r\n \r\n # Load result\r\n df_dict[descrip] = pd.read_csv(fn)\r\n \r\n '''\r\n Load results into dataframe\r\n '''\r\n for case, criteria in cases.items():\r\n \r\n dfs = []\r\n logging.info(\"\\nProcessing: {}\".format(case))\r\n n = len(files)\r\n for descrip, df in df_dict.items():\r\n \r\n # Get parameters\r\n extracted_params = []\r\n for p in params:\r\n if (p not in criteria):\r\n if (p in df.iloc[0]): \r\n extracted_params.append((p, df.iloc[0][p])) \r\n else:\r\n extracted_params.append((p, 0)) \r\n\r\n # Iterate over rows in dataframe \r\n extracted_perf = [] \r\n for idx, row in df.iterrows():\r\n if filt(row, criteria):\r\n \r\n extracted_perf.append((metric, row[metric]))\r\n \r\n if len(extracted_perf) > 0:\r\n # Combine performance and params tupls\r\n extracted = extracted_perf + list(criteria.items()) + extracted_params\r\n\r\n # Build data frame\r\n cols, vals = zip(*extracted)\r\n cols = list(cols)\r\n df_tmp = pd.DataFrame([vals], columns=cols)\r\n\r\n columns = df_tmp.columns.tolist()\r\n assert len(columns) == len(set(columns)), \\\r\n \"duplicate column: {}\".format(columns)\r\n\r\n # Collect results\r\n dfs.append(df_tmp)\r\n \r\n # Concatenate dataframe and resort columns\r\n df = pd.concat(dfs)\r\n\r\n '''\r\n Create spreadsheet\r\n '''\r\n # Columns with float format\r\n columns_float = [c for c in df.columns.values.tolist() \\\r\n if c not in params] \r\n \r\n # Write to disk \r\n fn = os.path.join(dest_, '{}.xlsx'.format(case)) \r\n \r\n df_to_excel(df, fn,\r\n columns_disp = None,\r\n columns_float = columns_float,\r\n columns_int = [],\r\n columns_3_color_scale = columns_float,\r\n column_map = column_map,\r\n float_format = float_format,\r\n )\r\n\r\n\r\n return \"Complete\"\r\n \r\n","sub_path":"code/step211_event_detect_cv_best.py","file_name":"step211_event_detect_cv_best.py","file_ext":"py","file_size_in_byte":5924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"48715601","text":"import pandas as pd\n\ndf=pd.DataFrame([\n ['green', 'M', 10.1, 'class1'],\n ['red', 'L', 13.5, 'class2'],\n ['blue', 'XL', 15.3, 'class1']])\n\ndf.columns=['color','size','price','classlabel']\n\nsize_mapping={\n \"M\":1,\n \"L\":2,\n \"XL\":3}\ninverse_size_mapping={k:v for v,k in size_mapping.items()}\n\n\ndf['size']=df['size'].map(size_mapping)\nimport numpy as np\n\nclass_mapping={\n lab:idx for idx,lab in enumerate(np.unique(df['classlabel']))}\n\ndf['classlabel']=df['classlabel'].map(class_mapping)\n\nprint(df)\n\nfrom sklearn.preprocessing import LabelEncoder,OneHotEncoder\n\nX=df[['color','size','price']].values\n\ncolor_le=LabelEncoder()\nX[:,0]=color_le.fit_transform(X[:,0])\n\n\nprint(X)\n\nohe=OneHotEncoder(categorical_features=[0])\nohe.fit_transform(X).toarray()\n\nprint(ohe,X)\n\n\n","sub_path":"chapter4/pddata.py","file_name":"pddata.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"358658814","text":"import pandas as pd\nimport os, pickle\nfrom os.path import join\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom glob import glob\nfrom matplotlib.ticker import AutoMinorLocator\n\nfrom toPrecision import toPrecision\nimport FunctionsMLFSOMPeaks as myfunc\n\nimage_folder = '/Users/atakisi/Desktop/MLFSOM/data_gaussian_N4_1.5A'\n\ndf_peaks = myfunc.ReadGaussianPeakIntensities(image_folder)\ndf_shells = myfunc.ShellIntensities(df_peaks,20)\n\nplt.close('all')\nfig, ax = plt.subplots()\nplt.ion()\n\n# data\nd_space = df_shells.d_max*0.5+df_shells.d_min*0.5\nD_half = df_shells.D_half\nplt.scatter(d_space,D_half,edgecolors='black',s=150)\n# fitting line\nx = np.linspace(1.4, 10, 100)\nK = 0.52\ny = K * x**2\nax.plot(x, y, linestyle = '--', color='tab:red', linewidth=2)\n\n\nax.set_ylim(ymin=1)\nax.set_xticks([1,10])\n\nax.set_xscale('log')\nax.set_yscale('log')\nax.set_xlabel('Resolution ($\\mathrm{\\\\AA}$)',fontsize='x-large')\nax.set_ylabel('Half-dose (arbitrary)',fontsize='x-large')\nax.tick_params(axis='both', which='both', length=0, labelsize='x-large',pad=10)\nax.grid(which='major',linewidth=0.4)\nax.grid(which='minor',linewidth=0.2)\nax.set_facecolor('0.95')\nfor axis in ['top','bottom','left','right']: ax.spines[axis].set_visible(False)\nplt.tight_layout()\n\nplt.show()\n\n\n","sub_path":"trash.py","file_name":"trash.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"567665860","text":"from api.core.base import BaseEngine\nfrom api.core.models import AnimeMetaInfo, AnimeDetailInfo, Video, VideoCollection\nfrom api.utils.logger import logger\n\n\nclass EYunZun(BaseEngine):\n \"\"\"该引擎网络不稳定, 有时响应响应很长时间\"\"\"\n\n def __init__(self):\n self._base_url = \"https://api.eyunzhu.com/api/vatfs/resource_site_collect\"\n self._search_api = self._base_url + \"/search\"\n self._detail_api = self._base_url + \"/getVDetail\"\n\n def search(self, keyword: str):\n logger.info(f\"Searching for: {keyword}\")\n resp = self.get(self._search_api, params={\"kw\": keyword, \"per_page\": 100, \"page\": 1}) # 取前 100 条结果\n if resp.status_code != 200 or resp.json()[\"code\"] != 1:\n logger.warning(f\"Response error: {resp.status_code} {self._search_api}\")\n return\n\n data = resp.json()\n anime_meta_list = data.get(\"data\").get(\"data\") if data else []\n for meta in anime_meta_list:\n anime = AnimeMetaInfo()\n anime.title = meta[\"name\"]\n anime.cover_url = meta[\"pic\"]\n anime.category = meta[\"type\"]\n anime.detail_page_url = str(meta[\"vid\"])\n anime.desc = meta[\"label\"]\n yield anime\n\n def get_detail(self, detail_page_url: str):\n resp = self.get(self._detail_api, params={\"vid\": detail_page_url})\n if resp.status_code != 200 or resp.json()[\"code\"] != 1:\n logger.warning(f\"Response error: {resp.status_code} {self._search_api}\")\n return AnimeDetailInfo()\n\n detail = resp.json().get(\"data\") # 视频详情信息\n anime_detail = AnimeDetailInfo()\n anime_detail.title = detail[\"name\"]\n anime_detail.cover_url = detail[\"pic\"]\n anime_detail.desc = detail[\"label\"]\n anime_detail.category = detail[\"type\"]\n\n vc = VideoCollection()\n vc.name = \"视频列表\"\n video_set = dict(detail[\"playUrl\"])\n for name, url in video_set.items():\n vc.append(Video(name, url))\n anime_detail.append(vc)\n return anime_detail\n","sub_path":"api/engines/eyunzhu.py","file_name":"eyunzhu.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"399534012","text":"import pandas as pd\nimport numpy as np\n\nimport pathlib\n\ndf = pd.read_excel(str(pathlib.Path().absolute())+\"/Data/Bengaluru.xls\")\n\ndef test():\n print(\"working\")\n \ndef locality():\n df = pd.read_excel(str(pathlib.Path().absolute())+\"/Data/Bengaluru.xls\")\n df = df.set_index('S.No.')\n df = df.dropna(subset=['PIN'])\n df.drop(df[df['PIN'] == '-' ].index , inplace=True)\n graph=df['PIN'].value_counts()\n graph=graph.dropna()\n x=(graph.tolist())\n y=[]\n for i in graph.index.tolist():\n y.append(str(i))\n return(x,y)\n\ndef country():\n df = pd.read_excel(str(pathlib.Path().absolute())+\"/Data/Bengaluru.xls\")\n country=df['Port of Origin of journey'].value_counts()\n y=(country[0:20].tolist())\n x=[]\n for i in country[0:20].index.tolist():\n x.append(str(i))\n return(x,y)\n\ndef gender():\n Diagonised = pd.read_excel(str(pathlib.Path().absolute())+\"/Data/D_Bengaluru.xlsx\")\n Gender=Diagonised[\"Gender\"].value_counts()\n y=(Gender.tolist())\n x=[]\n for i in Gender.index.tolist():\n x.append(str(i))\n return(x,y)\n\ndef Type_of_Infection_source():\n Diagonised = pd.read_excel(str(pathlib.Path().absolute())+\"/Data/D_Bengaluru.xlsx\")\n Type_of_Infection_source=Diagonised[\"Type of Infection\\nsource\"].value_counts()\n y=(Type_of_Infection_source.tolist())\n x=[]\n for i in Type_of_Infection_source.index.tolist():\n x.append(str(i))\n return(x,y)\n\ndef age():\n Diagonised = pd.read_excel(str(pathlib.Path().absolute())+\"/Data/D_Bengaluru.xlsx\")\n Age=Diagonised[\"Age\"].value_counts()\n y=(Age.tolist())\n x=[]\n for i in Age.index.tolist():\n x.append(str(i))\n return(x,y)","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"147743027","text":"a = []\nprint('Вводьте стрічки з нового рядка, після останньої натисніть \"Enter\"\\n')\nwhile True:\n\tq = input()\n\tif q == '':\n\t\tbreak\n\telse:\n\t\ta.append(q)\n\nwith_x, without_x = [], []\n\nfor i in a:\n\twith_x.append(i) if i.startswith('x') else without_x.append(i)\n\nwith_x.sort()\nwithout_x.sort()\n\na = with_x + without_x\n\nprint(a)","sub_path":"Задачі 1/0.3 Списки/2. Ті, що починаються з X на початку.py","file_name":"2. Ті, що починаються з X на початку.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"218093528","text":"\"\"\"\nDjango settings for fourpoints project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.6/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\nLOG_DIR = os.path.join(BASE_DIR, 'logs')\n\ntry:\n os.makedirs(LOG_DIR)\nexcept:\n pass\n\nADMINS = (\n ('Xindong Ding', 'dxd.spirits@gmail.com'),\n)\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 'f^mv=5w3_+6fl=a0qed(z5-ij-g@@9o#dh79xj5e6442am^yf^'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = False\n\nTEMPLATE_DEBUG = False\n\nALLOWED_HOSTS = ['*']\n\n# Application definition\n\nINSTALLED_APPS = (\n 'suit',\n \n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n \n 'rest_framework',\n 'rest_framework.authtoken',\n 'corsheaders',\n \n 'users',\n 'polls',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.gzip.GZipMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'fourpoints.urls'\n\nWSGI_APPLICATION = 'fourpoints.wsgi.application'\n\n# Templates\n\nfrom django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP\n\nTEMPLATE_CONTEXT_PROCESSORS = TCP + (\n 'django.core.context_processors.request',\n)\n\n# Rest framework\n\nREST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework.renderers.UnicodeJSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n ),\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n #'rest_framework.authentication.SessionAuthentication',\n #'rest_framework.authentication.BasicAuthentication',\n 'rest_framework.authentication.TokenAuthentication',\n ),\n 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',),\n}\n\n# CORS\n\nCORS_ORIGIN_ALLOW_ALL = True\nCORS_ALLOW_HEADERS = (\n 'x-requested-with',\n 'content-type',\n 'accept',\n 'origin',\n 'authorization',\n 'cache-control'\n)\n\n# Logging\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'formatters': {\n 'verbose': {\n 'format': '[%(asctime)s] \"%(levelname)s %(module)s\" %(message)s',\n 'datefmt': '%d/%b/%Y %I:%M:%S'\n },\n 'simple': {\n 'format': '%(levelname)s %(message)s'\n },\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n },\n 'console':{\n 'level':'DEBUG',\n 'class':'logging.StreamHandler',\n 'formatter': 'verbose'\n },\n 'log_file': {\n 'level':'DEBUG',\n 'class': 'logging.handlers.WatchedFileHandler',\n 'filename': os.path.join(LOG_DIR, 'apps.log'),\n 'formatter': 'verbose'\n },\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n 'apps': {\n 'handlers': ['mail_admins', 'log_file'],\n 'level': 'INFO',\n 'propagate': True,\n },\n }\n}\n\n# Database\n# https://docs.djangoproject.com/en/1.6/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'fourpoints',\n 'USER': 'root',\n 'PASSWORD': 'root',\n 'HOST': 'localhost',\n 'PORT': '3306',\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.6/topics/i18n/\n\n#LANGUAGE_CODE = 'en-us'\nLANGUAGE_CODE = 'zh-CN'\n\nTIME_ZONE = 'Asia/Shanghai'\n\nUSE_I18N = False\nUSE_L10N = False\nUSE_TZ = False\n\nDATE_FORMAT = 'Y-m-d'\nTIME_FORMAT = 'H:i:s'\nDATETIME_FORMAT = 'Y-m-d H:i:s'\n\n# Absolute filesystem path to the directory that will hold user-uploaded files.\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\n# URL that handles the media served from MEDIA_ROOT.\nMEDIA_URL = '/media/'\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.6/howto/static-files/\n\nSTATIC_ROOT = os.path.join(BASE_DIR, 'static')\nSTATIC_URL = '/static/'\n\nSTATICFILES_DIRS = (\n # Additional locations of static files\n os.path.join(BASE_DIR, 'staticfiles'),\n)\n\nTEMPLATE_DIRS = (\n # Always use forward slashes and absolute paths.\n os.path.join(BASE_DIR, 'templates'),\n)\n\n# Local settings\n\ntry:\n LOCAL_SETTINGS #@UndefinedVariable \nexcept NameError:\n try:\n from settings_local import * #@UnusedWildImport\n except ImportError:\n pass\n","sub_path":"fourpoints/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"424036776","text":"from django.conf.urls import url,include\nfrom .views import (\n\t\t\t\t\tMovieDetailView,\n\t\t\t\t\tMovieListView,\n\t\t\t\t\tMovieCreateView,\n\t\t\t\t\tMovieUpdateView,\n\t\t\t\t\tMovieDeleteView\n\t\t\t\t\t)\nfrom django.views.generic.base import RedirectView\n\nurlpatterns = [\n\turl(r'^$', RedirectView.as_view(url=\"/\")),\n\turl(r'^$', MovieListView, name='list'),\n url(r'^search/$', MovieListView,name='list'),\n url(r'^create/$', MovieCreateView.as_view(),name='create'),\n url(r'^(?P\\d+)/$', MovieDetailView.as_view(),name='detail'),\n url(r'^(?P\\d+)/update/$', MovieUpdateView.as_view(),name='update'),\n url(r'^(?P\\d+)/delete/$', MovieDeleteView.as_view(),name='delete'),\n]\n","sub_path":"src/movie/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"534885996","text":"# coding: utf-8\r\n\"\"\"\r\nBase para desarrollo de modulos externos.\r\nPara obtener el modulo/Funcion que se esta llamando:\r\n GetParams(\"module\")\r\n\r\nPara obtener las variables enviadas desde formulario/comando Rocketbot:\r\n var = GetParams(variable)\r\n Las \"variable\" se define en forms del archivo package.json\r\n\r\nPara modificar la variable de Rocketbot:\r\n SetVar(Variable_Rocketbot, \"dato\")\r\n\r\nPara obtener una variable de Rocketbot:\r\n var = GetVar(Variable_Rocketbot)\r\n\r\nPara obtener la Opcion seleccionada:\r\n opcion = GetParams(\"option\")\r\n\r\n\r\nPara instalar librerias se debe ingresar por terminal a la carpeta \"libs\"\r\n\r\n pip install -t .\r\n\r\n\"\"\"\r\nimport os.path\r\nimport sys\r\n\r\nbase_path = tmp_global_obj[\"basepath\"]\r\ncur_path = base_path + 'modules' + os.sep + 'Google-SpreadSheets' + os.sep + 'libs' + os.sep\r\n\r\ncur_path_x64 = os.path.join(cur_path, 'Windows' + os.sep + 'x64' + os.sep)\r\ncur_path_x86 = os.path.join(cur_path, 'Windows' + os.sep + 'x86' + os.sep)\r\n\r\nif cur_path_x64 not in sys.path and sys.maxsize > 2**32:\r\n sys.path.append(cur_path_x64)\r\nelif cur_path_x86 not in sys.path and sys.maxsize > 32:\r\n sys.path.append(cur_path_x86)\r\n\r\nfrom googleapiclient import discovery\r\nfrom google_auth_oauthlib.flow import InstalledAppFlow\r\nfrom google.auth.transport.requests import Request\r\nfrom openpyxl.utils.cell import get_column_letter\r\n\r\nimport traceback\r\nimport pickle\r\nimport re\r\n\r\n\"\"\"\r\n Obtengo el modulo que fueron invocados\r\n\"\"\"\r\nmodule = GetParams(\"module\")\r\n\r\nglobal creds\r\nglobal mod_gss_session\r\n\r\nsession = GetParams(\"session\")\r\nif not session:\r\n session = ''\r\n \r\ntry:\r\n if not mod_gss_session : #type:ignore\r\n mod_gss_session = {}\r\nexcept NameError:\r\n mod_gss_session = {}\r\n\r\nif module == \"GoogleSuite\":\r\n cred = None\r\n credential_path = GetParams(\"credentials_path\")\r\n\r\n if session == '':\r\n filename = \"token_spreadsheets.pickle\"\r\n else:\r\n filename = \"token_spreadsheets_{s}.pickle\".format(s=session)\r\n \r\n filename = os.path.join(base_path, filename)\r\n \r\n try:\r\n if not os.path.exists(credential_path):\r\n raise Exception(\r\n \"El archivo de credenciales no existe en la ruta especificada\")\r\n\r\n SCOPES = [\r\n 'https://www.googleapis.com/auth/spreadsheets',\r\n 'https://www.googleapis.com/auth/drive.file',\r\n 'https://www.googleapis.com/auth/drive',\r\n 'https://www.googleapis.com/auth/script.projects',\r\n 'https://www.googleapis.com/auth/script.external_request',\r\n 'https://www.googleapis.com/auth/drive.scripts'\r\n ]\r\n\r\n if os.path.exists(filename):\r\n with open(filename, 'rb') as token:\r\n cred = pickle.load(token)\r\n # If there are no (valid) credentials available, let the user log in.\r\n if not cred or not cred.valid:\r\n if cred and cred.expired and cred.refresh_token:\r\n cred.refresh(Request())\r\n else:\r\n flow = InstalledAppFlow.from_client_secrets_file(\r\n credential_path, SCOPES)\r\n cred = flow.run_local_server()\r\n # Save the credentials for the next run\r\n with open(filename, 'wb') as token:\r\n pickle.dump(cred, token)\r\n \r\n # global creds\r\n mod_gss_session[session] = cred\r\n \r\n except Exception as e:\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n\r\nif not mod_gss_session[session]:\r\n raise Exception(\"There's no credentials, nor valid token. Please, generate your credentials.\")\r\n\r\nif module == \"CreateSpreadSheet\":\r\n\r\n ss_name = GetParams('ss_name')\r\n result = GetParams('result')\r\n\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n spreadsheet_body = {\r\n \"properties\": {\r\n \"title\": ss_name\r\n }\r\n }\r\n\r\n request = service.spreadsheets().create(body=spreadsheet_body)\r\n response = request.execute()\r\n if result:\r\n SetVar(result, response[\"spreadsheetId\"])\r\n \r\nif module == \"CreateSheet\":\r\n\r\n ss_id = GetParams('ss_id')\r\n name = GetParams('name')\r\n result = GetParams('result')\r\n\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n body = {\r\n \"requests\": [\r\n {\r\n \"addSheet\": {\r\n \"properties\": {\r\n \"title\": name,\r\n }\r\n }\r\n }\r\n ]\r\n }\r\n\r\n request = service.spreadsheets().batchUpdate(spreadsheetId=ss_id,\r\n body=body)\r\n response = request.execute()\r\n\r\n if result:\r\n sheetId = response[\"replies\"][0][\"addSheet\"][\"properties\"][\"sheetId\"]\r\n SetVar(result, sheetId)\r\n\r\nif module == \"UpdateSheetProperties\":\r\n\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams('sheetName')\r\n newName = GetParams('newName')\r\n hidden = GetParams('hidden')\r\n \r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n \r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n \r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n if not newName:\r\n newName = sheet\r\n \r\n if not hidden:\r\n hidden = False\r\n else:\r\n hidden = eval(hidden)\r\n \r\n body = {\r\n \"requests\": [\r\n {\r\n \"updateSheetProperties\": {\r\n \"properties\": {\r\n \"sheetId\": sheet_id,\r\n \"title\": newName,\r\n \"hidden\": hidden\r\n },\r\n \"fields\": \"title, hidden\",\r\n }\r\n }\r\n ]\r\n }\r\n\r\n request = service.spreadsheets().batchUpdate(spreadsheetId=ss_id,\r\n body=body)\r\n response = request.execute()\r\n\r\nif module == \"DeleteSheet\":\r\n\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams('sheetName')\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n \r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n\r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n body = {\r\n \"requests\": [\r\n {\r\n \"deleteSheet\": {\r\n \"sheetId\": sheet_id\r\n }\r\n }\r\n\r\n ]\r\n }\r\n\r\n request = service.spreadsheets().batchUpdate(spreadsheetId=ss_id,\r\n body=body)\r\n response = request.execute()\r\n\r\nif module == \"UpdateRange\":\r\n\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n range_ = GetParams('range')\r\n text = GetParams('text')\r\n\r\n try:\r\n if not text.startswith(\"[\"):\r\n text = text.replace('\"', '\\\\\\\"')\r\n text = \"[[ \\\"{}\\\" ]]\".format(text)\r\n \r\n values = eval(text)\r\n \r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n # Checks existence of the given sheet name and update the range\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n range_ = sheet + \"!\" + range_ # Sheet1!A1:A10\r\n \r\n if not 'range_' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n body = {\r\n \"values\": values\r\n }\r\n \r\n request = service.spreadsheets().values().update(spreadsheetId=ss_id, range=range_,\r\n valueInputOption=\"USER_ENTERED\",\r\n body=body)\r\n response = request.execute()\r\n \r\n except Exception as e:\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n\r\ndef get_column_index(col):\r\n try:\r\n abc = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',\r\n 'v', 'w', 'x', 'y', 'z']\r\n around_abc = len(col) - 1\r\n \r\n col = col[-1].lower()\r\n col_index = around_abc * len(abc) + abc.index(col)\r\n return col_index\r\n except Exception as e:\r\n PrintException()\r\n raise e\r\n\r\nif module == \"UpdateFormat\":\r\n\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n range_ = GetParams('range')\r\n merge = GetParams('merge')\r\n unmerge = GetParams('unmerge')\r\n resize = GetParams('resize')\r\n number_format = GetParams('format') # select\r\n pattern = GetParams('pattern') # string\r\n \r\n foreground = GetParams('foreground') # touple\r\n font_family = GetParams('fontFamily') # string\r\n font_size = GetParams('fontSize') # int\r\n \r\n bold = GetParams('bold') # bool\r\n italic = GetParams('italic') # bool\r\n strikethrough = GetParams('strikethrough') # bool\r\n underline = GetParams('underline') # bool\r\n \r\n try:\r\n \r\n if \":\" in range_:\r\n range_\r\n else:\r\n range_ = range_ + \":\" + range_\r\n \r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n # Checks existence of the given sheet name and update the range\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n\r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n regex = r\"([A-Z]+)([0-9]+):([A-Z]+)([0-9]+)\"\r\n range_re = re.findall(regex, range_)\r\n \r\n column_start = get_column_index(range_re[0][0])\r\n column_end = get_column_index(range_re[0][2]) + 1\r\n \r\n row_start = int(range_re[0][1]) - 1\r\n row_end = int(range_re[0][3]) \r\n \r\n body = {\r\n 'requests': [\r\n \r\n ]\r\n }\r\n \r\n if merge:\r\n if eval(merge) == True:\r\n\r\n merge_ = {\r\n \"mergeCells\": {\r\n \"range\": {\r\n \"sheetId\": sheet_id,\r\n \"startRowIndex\": row_start,\r\n \"endRowIndex\": row_end,\r\n \"startColumnIndex\": column_start,\r\n \"endColumnIndex\": column_end\r\n },\r\n \"mergeType\": \"MERGE_ALL\"\r\n }\r\n }\r\n body['requests'].append(merge_)\r\n \r\n if unmerge:\r\n if eval(unmerge) == True:\r\n\r\n unmerge_ = {\r\n \"unmergeCells\": {\r\n \"range\": {\r\n \"sheetId\": sheet_id,\r\n \"startRowIndex\": row_start,\r\n \"endRowIndex\": row_end,\r\n \"startColumnIndex\": column_start,\r\n \"endColumnIndex\": column_end\r\n }\r\n }\r\n }\r\n body['requests'].append(unmerge_)\r\n \r\n if resize:\r\n if eval(resize) == True: \r\n columms_ = {\r\n 'autoResizeDimensions':{\r\n 'dimensions': {\r\n 'sheetId': sheet_id,\r\n 'dimension': 'COLUMNS',\r\n 'startIndex': column_start,\r\n 'endIndex': column_end\r\n } \r\n } \r\n }\r\n body['requests'].append(columms_)\r\n\r\n rows_ = {\r\n 'autoResizeDimensions':{\r\n 'dimensions': {\r\n 'sheetId': sheet_id,\r\n 'dimension': 'ROWS',\r\n 'startIndex': row_start,\r\n 'endIndex': row_end \r\n } \r\n } \r\n }\r\n body['requests'].append(rows_)\r\n \r\n uef = {}\r\n fields = []\r\n \r\n if number_format != '':\r\n uef['numberFormat'] = {'type': number_format, 'pattern': ''} \r\n if pattern != '':\r\n uef['numberFormat']['pattern'] = pattern \r\n fields.append('numberFormat')\r\n \r\n if foreground:\r\n if not uef.get('textFormat'):\r\n uef['textFormat'] = {}\r\n fields.append('textFormat')\r\n \r\n c = foreground.split(',')\r\n # To use RGB format, the API expects a proportion of each over the 255\r\n uef['textFormat'][\"foregroundColorStyle\"] = {\r\n \"rgbColor\": {\r\n \"red\": int(c[0])/255,\r\n \"green\": int(c[1])/255,\r\n \"blue\": int(c[2])/255,\r\n \"alpha\": 1\r\n }\r\n }\r\n \r\n if font_family != '':\r\n if not uef.get('textFormat'):\r\n uef['textFormat'] = {}\r\n fields.append('textFormat')\r\n uef['textFormat']['fontFamily'] = font_family\r\n\r\n if font_size and eval(font_size) >0:\r\n if not uef.get('textFormat'):\r\n uef['textFormat'] = {}\r\n fields.append('textFormat')\r\n uef['textFormat']['fontSize'] = eval(font_size)\r\n \r\n if bold:\r\n if not uef.get('textFormat'):\r\n uef['textFormat'] = {}\r\n fields.append('textFormat')\r\n uef['textFormat']['bold'] = eval(bold)\r\n \r\n if italic:\r\n if not uef.get('textFormat'):\r\n uef['textFormat'] = {}\r\n fields.append('textFormat')\r\n uef['textFormat']['italic'] = eval(italic)\r\n \r\n if strikethrough:\r\n if not uef.get('textFormat'):\r\n uef['textFormat'] = {}\r\n fields.append('textFormat')\r\n uef['textFormat']['strikethrough'] = eval(strikethrough)\r\n \r\n if underline:\r\n if not uef.get('textFormat'):\r\n uef['textFormat'] = {}\r\n fields.append('textFormat')\r\n uef['textFormat']['underline'] = eval(underline)\r\n \r\n if fields != []:\r\n \r\n fields_ = ','.join(fields)\r\n \r\n cell_format= {\r\n 'repeatCell': {\r\n 'range': {\r\n \"sheetId\": sheet_id,\r\n 'startRowIndex': row_start,\r\n 'endRowIndex': row_end,\r\n 'startColumnIndex': column_start,\r\n 'endColumnIndex': column_end,\r\n },\r\n 'cell': {\r\n 'userEnteredFormat': uef\r\n },\r\n 'fields': f'userEnteredFormat({fields_})'\r\n }\r\n }\r\n \r\n body['requests'].append(cell_format)\r\n \r\n request = service.spreadsheets().batchUpdate(spreadsheetId=ss_id, body=body)\r\n response = request.execute()\r\n \r\n except Exception as e:\r\n PrintException()\r\n raise e\r\n\r\nif module == \"ReadCells\":\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n range_ = GetParams('range')\r\n result = GetParams('result')\r\n\r\n try:\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n # Checks existence of the given sheet name and update the range\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n range_ = sheet + \"!\" + range_ # Sheet1!A1:A10\r\n \r\n if not 'range_' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n request = service.spreadsheets().values().get(spreadsheetId=ss_id, range=range_)\r\n\r\n response = request.execute()\r\n try:\r\n value = response[\"values\"]\r\n except:\r\n value = \"\"\r\n\r\n if result:\r\n SetVar(result, value)\r\n except Exception as e:\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n\r\n\r\nif module == \"copyPaste\":\r\n\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n range_ = GetParams('range')\r\n \r\n sheet2 = GetParams(\"sheetName2\")\r\n range_2 = GetParams('range2')\r\n \r\n type_ = GetParams('type')\r\n transponse = GetParams('transponse')\r\n cut = GetParams('cut')\r\n \r\n try:\r\n \r\n if \":\" in range_:\r\n range_\r\n else:\r\n range_ = range_ + \":\" + range_\r\n \r\n if \":\" in range_2:\r\n range_2 \r\n else:\r\n range_2 = range_2 + \":\" + range_2\r\n \r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n # Checks existence of the given sheet name and update the range\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n if element[\"properties\"][\"title\"] == sheet2:\r\n sheet_id2 = element[\"properties\"][\"sheetId\"]\r\n\r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Source sheet could't be found...\")\r\n \r\n if not 'sheet_id2' in locals():\r\n raise Exception(\"Target sheet could't be found...\")\r\n \r\n regex = r\"([A-Z]+)([0-9]+):([A-Z]+)([0-9]+)\"\r\n # <----- Data Origin ----->\r\n range_re = re.findall(regex, range_)\r\n \r\n column_start = get_column_index(range_re[0][0])\r\n column_end = get_column_index(range_re[0][2]) + 1\r\n \r\n row_start = int(range_re[0][1]) - 1\r\n row_end = int(range_re[0][3]) \r\n \r\n # <----- Data Destination ----->\r\n range_re2 = re.findall(regex, range_2)\r\n \r\n column_start2 = get_column_index(range_re2[0][0])\r\n column_end2 = get_column_index(range_re2[0][2]) + 1\r\n \r\n row_start2 = int(range_re2[0][1]) - 1\r\n row_end2 = int(range_re2[0][3]) \r\n \r\n orientation = \"NORMAL\"\r\n if transponse:\r\n if eval(transponse) == True:\r\n orientation = 'TRANSPOSE'\r\n \r\n body = {\r\n 'requests': [\r\n ]\r\n }\r\n \r\n if not cut or eval(cut) == False:\r\n body['requests'] = {\r\n \"copyPaste\": {\r\n \"source\": {\r\n \"sheetId\": sheet_id,\r\n \"startRowIndex\": row_start,\r\n \"endRowIndex\": row_end,\r\n \"startColumnIndex\": column_start,\r\n \"endColumnIndex\": column_end,\r\n },\r\n \"destination\": {\r\n \"sheetId\": sheet_id2,\r\n \"startRowIndex\": row_start2,\r\n \"endRowIndex\": row_end2,\r\n \"startColumnIndex\": column_start2,\r\n \"endColumnIndex\": column_end2,\r\n },\r\n \"pasteType\": type_,\r\n \"pasteOrientation\": orientation,\r\n }\r\n }\r\n else:\r\n body['requests'] = {\r\n \"cutPaste\": {\r\n \"source\": {\r\n \"sheetId\": sheet_id,\r\n \"startRowIndex\": row_start,\r\n \"endRowIndex\": row_end,\r\n \"startColumnIndex\": column_start,\r\n \"endColumnIndex\": column_end,\r\n },\r\n \"destination\": {\r\n \"sheetId\": sheet_id2,\r\n \"rowIndex\": row_start2,\r\n \"columnIndex\": column_start2,\r\n },\r\n \"pasteType\": type_,\r\n }\r\n }\r\n \r\n request = service.spreadsheets().batchUpdate(spreadsheetId=ss_id, body=body)\r\n response = request.execute()\r\n \r\n except Exception as e:\r\n PrintException()\r\n raise e\r\n \r\n\r\nif module == \"GetSheets\":\r\n ss_id = GetParams('ss_id')\r\n result = GetParams('result')\r\n \r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n \r\n request = service.spreadsheets().get(spreadsheetId=ss_id)\r\n response = request.execute()\r\n\r\n sheets = []\r\n for element in response[\"sheets\"]:\r\n sheets.append(element[\"properties\"][\"title\"])\r\n if result:\r\n SetVar(result, sheets)\r\n \r\nif module == \"CountCells\":\r\n try:\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams('sheetName')\r\n result = GetParams('result') # Here is saved the number of rows the command was originaly made for that.\r\n columns = GetParams('columns')\r\n \r\n range_ = \"A1:ZZZ999999\"\r\n\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n \r\n # Checks existence of the given sheet name and update the range\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n range_ = sheet + \"!\" + range_ # Sheet1!A1:A10\r\n \r\n if not 'range_' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n request = service.spreadsheets().values().get(spreadsheetId=ss_id, range=range_)\r\n response = request.execute()\r\n\r\n length = len(response[\"values\"])\r\n \r\n width_aux = max([len(row) for row in response[\"values\"]])\r\n width = [width_aux, get_column_letter(width_aux)] # get_column_letter indexes begin with 1 (not 0)\r\n\r\n if result:\r\n SetVar(result, length)\r\n\r\n if columns:\r\n SetVar(columns, width)\r\n \r\n except Exception as e:\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n\r\nif module == \"DeleteColumn\":\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n col = GetParams('column').lower()\r\n blank = GetParams('blank')\r\n\r\n try:\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n\r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n \r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n sep = col.find(\":\")\r\n if sep == -1:\r\n col_index_1 = get_column_index(col)\r\n col_index_2 = col_index_1 + 1\r\n else: \r\n cols = col.split(\":\")\r\n col_index_1 = get_column_index(cols[0])\r\n col_index_2 = get_column_index(cols[1]) + 1\r\n \r\n if blank is not None:\r\n blank = eval(blank)\r\n\r\n if blank:\r\n shiftDimension = \"ROWS\"\r\n else:\r\n shiftDimension = \"COLUMNS\"\r\n\r\n body = {\r\n \"requests\": [{\r\n \"deleteRange\": {\r\n \"range\": {\r\n \"sheetId\": sheet_id,\r\n \"startColumnIndex\": col_index_1,\r\n \"endColumnIndex\": col_index_2\r\n },\r\n \"shiftDimension\": shiftDimension\r\n }\r\n }]\r\n }\r\n\r\n request = service.spreadsheets().batchUpdate(spreadsheetId=ss_id, body=body)\r\n response = request.execute()\r\n\r\n except Exception as e:\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n\r\nif module == \"DeleteRow\":\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n row = GetParams('row')\r\n blank = GetParams('blank')\r\n\r\n try:\r\n\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n\r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n\r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n sep = row.find(\":\")\r\n if sep == -1:\r\n row_index_1 = int(row) - 1\r\n row_index_2 = int(row)\r\n else: \r\n rows = row.split(\":\")\r\n row_index_1 = int(rows[0])-1\r\n row_index_2 = int(rows[1])\r\n \r\n if blank is not None:\r\n blank = eval(blank)\r\n\r\n if blank:\r\n shiftDimension = \"COLUMNS\"\r\n else:\r\n shiftDimension = \"ROWS\"\r\n\r\n body = {\r\n \"requests\": [{\r\n \"deleteRange\": {\r\n \"range\": {\r\n \"sheetId\": sheet_id,\r\n \"startRowIndex\": row_index_1,\r\n \"endRowIndex\": row_index_2\r\n },\r\n \"shiftDimension\": shiftDimension\r\n }\r\n }]\r\n }\r\n\r\n request = service.spreadsheets().batchUpdate(spreadsheetId=ss_id, body=body)\r\n response = request.execute()\r\n\r\n except Exception as e:\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n\r\nif module == \"AddColumn\":\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n col = GetParams('column').lower()\r\n q = int(GetParams(\"q\"))\r\n blank = GetParams('blank')\r\n\r\n try:\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n\r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n\r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n\r\n col_index = get_column_index(col)\r\n \r\n if blank is not None:\r\n blank = eval(blank)\r\n\r\n if blank == False or col_index == 0:\r\n inheritance = \"false\"\r\n else:\r\n inheritance = \"true\"\r\n\r\n body = {\r\n \"requests\": [{\r\n \"insertDimension\": {\r\n \"range\": {\r\n \"sheetId\": sheet_id,\r\n \"dimension\": \"COLUMNS\",\r\n \"startIndex\": col_index,\r\n \"endIndex\": col_index + q\r\n },\r\n \"inheritFromBefore\": inheritance\r\n }\r\n }]\r\n }\r\n\r\n request = service.spreadsheets().batchUpdate(spreadsheetId=ss_id, body=body)\r\n response = request.execute()\r\n\r\n except Exception as e:\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n\r\nif module == \"AddRow\":\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n row = int(GetParams('row'))\r\n q = int(GetParams(\"q\"))\r\n blank = GetParams('blank')\r\n \r\n try:\r\n\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n\r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n \r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n if blank is not None:\r\n blank = eval(blank)\r\n \r\n row_index = row - 1\r\n\r\n if blank == False or row_index == 0:\r\n inheritance = \"false\"\r\n else:\r\n inheritance = \"true\"\r\n\r\n body = {\r\n \"requests\": [{\r\n \"insertDimension\": {\r\n \"range\": {\r\n \"sheetId\": sheet_id,\r\n \"dimension\": \"ROWS\",\r\n \"startIndex\": row_index,\r\n \"endIndex\": row_index + q\r\n },\r\n \"inheritFromBefore\": inheritance\r\n }\r\n }]\r\n }\r\n\r\n request = service.spreadsheets().batchUpdate(spreadsheetId=ss_id, body=body)\r\n response = request.execute()\r\n\r\n except Exception as e:\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n\r\ndef get_existing_basic_filters(ss_id, service, startRow=0, endRow=1000) -> dict:\r\n params = {'spreadsheetId': ss_id,\r\n 'fields': 'sheets(properties(sheetId,title),basicFilter)'}\r\n response = service.spreadsheets().get(**params).execute()\r\n\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n values_range = []\r\n for sheet in response['sheets']:\r\n if 'basicFilter' in sheet:\r\n values_range = list(sheet.values())[1]['range']\r\n # {'startRowIndex': startRow, 'endRowIndex': endRow, 'startColumnIndex': 4, 'endColumnIndex': 5}\r\n col = chr(values_range['startColumnIndex'] + 65)\r\n col = col + str(values_range['startRowIndex']+1) + \":\" + col + str(values_range['endRowIndex']+1)\r\n return col\r\n\r\ndef apply_filters(ss_id, filters, service):\r\n try:\r\n # All requests are validated before any are applied, so bundling the set and clear filter\r\n # operations in the same request would fail: only 1 basic filter can exist at a time.\r\n\r\n def clear_filters(ss_id, known_filters, service):\r\n requests = []\r\n for sheetId, filter in known_filters.items():\r\n requests.append({'clearBasicFilter': {'sheetId': sheetId}})\r\n if not requests:\r\n return\r\n params = {'spreadsheetId': ss_id,\r\n 'body': {'requests': requests}}\r\n service.spreadsheets().batchUpdate(**params).execute()\r\n\r\n def removekey(d, key):\r\n r = dict(d)\r\n del r[key]\r\n return r\r\n\r\n clear_filters(ss_id, filters, service)\r\n\r\n requests = []\r\n for sheetId, filter in filters.items():\r\n # By removing the starting and ending indices from the 'range' property,\r\n # we ensure the basicFilter will apply to the entire sheet bounds. If one knows the\r\n # desired values for startColumnIndex, startRowIndex, endRowIndex, endColumnIndex,\r\n # then they can be used to create a range-specific basic filter.\r\n # The 'range' property is a `GridRange`:\r\n if 'filterSpecs' not in filter:\r\n filter['filterSpecs'] = [{\r\n 'filterCriteria': {\r\n 'hiddenValues': []\r\n }\r\n }]\r\n requests.append({'setBasicFilter': {'filter': filter}})\r\n if not requests:\r\n return\r\n params = {'spreadsheetId': ss_id,\r\n 'body': {'requests': requests}}\r\n\r\n service.spreadsheets().batchUpdate(**params).execute()\r\n except Exception as e:\r\n PrintException()\r\n raise e\r\n\r\ndef create_filter_structure(ranges, values, sheet_id):\r\n try:\r\n new_filter = {\r\n 'range': ranges\r\n }\r\n startColumnIndex = ranges['startColumnIndex']\r\n endColumnIndex = ranges['endColumnIndex']\r\n new_filter['filterSpecs'] = []\r\n for index in range(startColumnIndex, endColumnIndex):\r\n new_filter['filterSpecs'].append({\r\n 'columnIndex': index,\r\n 'filterCriteria': {\r\n 'hiddenValues': values\r\n }\r\n })\r\n new_filter_with_sheet_id = {\r\n sheet_id: new_filter\r\n }\r\n return new_filter_with_sheet_id\r\n except Exception as e:\r\n PrintException()\r\n raise e\r\n\r\nif module == \"unfilterData\":\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n try:\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n \r\n if sheet == None or sheet == \"\":\r\n sheet_id = 0\r\n else:\r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n\r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n requests = []\r\n requests.append({'clearBasicFilter': {'sheetId': sheet_id}})\r\n \r\n params = {'spreadsheetId': ss_id,\r\n 'body': {'requests': requests}}\r\n \r\n service.spreadsheets().batchUpdate(**params).execute() \r\n \r\n except Exception as e:\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n\r\nif module == \"filterData\":\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n col = GetParams(\"col\").lower()\r\n valor_filtro = GetParams(\"valor_filtro\")\r\n try:\r\n col_index = get_column_index(col)\r\n\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n \r\n if sheet == None or sheet == \"\":\r\n sheet_id = 0\r\n else:\r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n\r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n range_ = sheet+\"!A:\"+col\r\n req = service.spreadsheets().values().get(spreadsheetId=ss_id, range=range_).execute()\r\n \r\n # It checks where the table that is going to be filtered starts and ends \r\n first_row = 0\r\n values = req[\"values\"]\r\n for cell in values:\r\n if cell == []:\r\n first_row += 1\r\n else:\r\n break\r\n last_row = len(req['values'])\r\n \r\n ranges = {\r\n \"sheetId\": sheet_id,\r\n 'startRowIndex': first_row,\r\n 'endRowIndex': last_row,\r\n 'startColumnIndex': col_index,\r\n 'endColumnIndex': col_index + 1,\r\n }\r\n \r\n hidden_values = []\r\n for row in values:\r\n # It appends a blank space to the list so the row is recognized as one in the following \"for\"\r\n if row == []:\r\n row.append(\"\")\r\n for cell in row:\r\n if valor_filtro != cell:\r\n hidden_values.append(cell)\r\n \r\n filters = create_filter_structure(ranges, hidden_values, sheet_id)\r\n apply_filters(ss_id, filters, service)\r\n except Exception as e:\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n\r\nif module == \"filterCells\":\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n res = GetParams(\"res\")\r\n range = GetParams(\"range_\")\r\n row_info = GetParams(\"row_info\")\r\n \r\n try:\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n \r\n data_ = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n \r\n for element in data_[\"sheets\"]:\r\n if sheet == None or sheet == \"\":\r\n sheet = data_[\"sheets\"][0][\"properties\"][\"title\"]\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n \r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n filter_start = element[\"basicFilter\"][\"range\"][\"startRowIndex\"]\r\n \r\n data = service.spreadsheets().get(spreadsheetId=ss_id, fields=\"sheets(data(rowMetadata(hiddenByFilter)),properties/sheetId)\").execute()\r\n\r\n #column_filter = get_existing_basic_filters(ss_id, service)\r\n list_hidden_rows = []\r\n for column in data['sheets']:\r\n if column['properties']['sheetId'] == sheet_id:\r\n for index, item in enumerate(column['data'][0]['rowMetadata']):\r\n if bool(item):\r\n list_hidden_rows.append(index)\r\n \r\n # It makes sure that always start from the first row of the filter, so the row index vs hidden rows can be done\r\n range_first_row = range[1]\r\n \r\n if range_first_row != filter_start:\r\n tmp = list(range)\r\n tmp[1] = filter_start + 1\r\n \r\n range = \"\".join(str(x) for x in tmp)\r\n \r\n \r\n range_ = sheet + \"!\" + range\r\n request = service.spreadsheets().values().get(spreadsheetId=ss_id, range=range_)\r\n response = request.execute()\r\n value = response[\"values\"]\r\n \r\n final_cells = []\r\n final_cells_row = {}\r\n for row_index, item in enumerate(value):\r\n row_index = (row_index + filter_start)\r\n if row_info and eval(row_info) == True:\r\n if row_index not in list_hidden_rows:\r\n final_cells_row[row_index+1] = item \r\n SetVar(res, final_cells_row)\r\n else:\r\n if row_index not in list_hidden_rows:\r\n final_cells.append(item) \r\n SetVar(res, final_cells)\r\n except Exception as e:\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n \r\nif module == \"CopySheet\":\r\n try:\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n ss_id_2 = GetParams('ss_id_2')\r\n result = GetParams('res')\r\n\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n \r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n \r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n body = {\r\n 'destination_spreadsheet_id': ss_id_2\r\n }\r\n \r\n request = service.spreadsheets().sheets().copyTo(spreadsheetId=ss_id, sheetId=sheet_id, body=body)\r\n response = request.execute()\r\n\r\n SetVar(res, True)\r\n except Exception as e:\r\n SetVar(res, False)\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n \r\nif module == \"TextToColumns\":\r\n try:\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n separator = GetParams('separator')\r\n result = GetParams('res')\r\n\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n \r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n \r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n body = {\r\n 'requests':[\r\n {\r\n 'textToColumns': {\r\n 'source': {\r\n 'sheetId': sheet_id,\r\n 'startColumnIndex': 0,\r\n 'endColumnIndex': 1\r\n },\r\n 'delimiterType': separator\r\n }\r\n }\r\n ]\r\n }\r\n \r\n request = service.spreadsheets().batchUpdate(spreadsheetId=ss_id, body=body)\r\n response = request.execute()\r\n\r\n SetVar(res, True)\r\n except Exception as e:\r\n SetVar(res, False)\r\n PrintException()\r\n raise e","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":41533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"357852248","text":"from .models import *\nfrom django.shortcuts import render\nfrom django.views.generic import DetailView\nfrom django.template import Template\nfrom django.template.response import TemplateResponse\n\nclass PageDetail(DetailView):\n queryset = Page.objects.filter(is_published=True)\n \n def get_context_data(self, **kwargs):\n page = self.get_object()\n for block in page.template_set.all()[0].block_set.all():\n kwargs[block.title] = block\n\n js = StaticContent.objects.filter(page=page, type='js')\n kwargs['js'] = js\n css = StaticContent.objects.filter(page=page, type='css')\n kwargs['css'] = css\n menus = Menu.objects.filter(template=page.template_set.all()[0])\n kwargs['menus'] = menus\n \n plugins = PluginBase.objects.filter(page=page)\n if plugins:\n for plugin in plugins: \n plugin.rendered = plugin.render(self.request, **kwargs)\n plugin.save()\n\n return super(PageDetail, self).get_context_data(**kwargs)\n \n def render_to_response(self, context, **response_kwargs):\n tempdata = self.get_object().template_set.all()[0].template_data\n template = Template(tempdata)\n return TemplateResponse(self.request, template, context)\n\n\n","sub_path":"cmsapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"457629643","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.colors import ListedColormap\nimport mstools.helpers.MSILibs as msi\n\n\ndef plot_sorted_snrs_from_dict(snr_d):\n \"\"\"\n Plots sorted SNR plots (with subplots)\n \"\"\"\n length = len(snr_d.keys())\n plt.figure(figsize=(10, 5))\n for i, key in enumerate(snr_d.keys()):\n plt.subplot(1, length, i+1)\n sorted_snr = sorted(snr_d[key])\n plt.title(str(key))\n plt.plot(sorted_snr)\n\n\ndef plot3D(x, y, color_map=ListedColormap(['red', 'orange', 'blue']), x_rot=0, y_rot=70):\n \"\"\"\n Plots basic 3D representation of the data\n \"\"\"\n fig = plt.figure(figsize=(14, 10))\n ax = Axes3D(fig)\n ax.view_init(x_rot, y_rot)\n ax.scatter(x.iloc[:, 0], x.iloc[:, 1], x.iloc[:, 2], c=y, cmap=color_map)\n\n\ndef visualize_on_specimen(x, index, s=1):\n y = msi.load_labels('static/Y.h5')\n x_placeholder = pd.DataFrame(np.zeros((y.shape[0], x.shape[1])))\n x_placeholder.update(x)\n plt.scatter(y['x'].values, y['y'].values, c=x_placeholder.iloc[:, index], s=s)\n","sub_path":"mstools/utils/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"73307142","text":"import webapp2\nimport jinja2\nfrom google.appengine.api import users\nfrom google.appengine.ext import ndb\nimport os\nfrom datetime import datetime\n\nJINJA_ENVIRONMENT = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\n extensions=['jinja2.ext.autoescape'],\n autoescape=True\n)\n\nclass Incomplete(webapp2.RequestHandler):\n def post(self):\n taskboardName = self.request.get('taskBoarddata')\n email = self.request.get('email')\n unique = taskboardName+\"\"+email\n taskTitleName = self.request.get('IncompleteButton')\n taskdata = ndb.Key('taskdata', unique).get()\n for i in range(0,len(taskdata.Title)):\n if taskdata.Title[i] == taskTitleName:\n taskdata.Task_Completion[i] = \"Not Complete\"\n taskdata.Date[i] = \"Not Complete\"\n taskdata.Time[i] = \"Not Complete\"\n taskdata.put()\n self.redirect('/invite?taskBoarddata='+taskboardName+'&email='+email)\n\napp = webapp2.WSGIApplication([\n ('/Incomplete',Incomplete)\n], debug=True)\n","sub_path":"Incomplete.py","file_name":"Incomplete.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"175981371","text":"# This file is part of REANA.\n# Copyright (C) 2022, 2023 CERN.\n#\n# REANA is free software; you can redistribute it and/or modify it\n# under the terms of the MIT License; see LICENSE file for more details.\n\"\"\"Utilities to manage files in a workspace.\"\"\"\n\nimport errno\nimport os\nimport re\nimport stat\nfrom pathlib import Path\nfrom typing import Generator, Union\n\nimport wcmatch.glob\n\nfrom reana_commons.errors import REANAWorkspaceError\n\n# O_NOFOLLOW: do not follow symlinks\n# O_NONBLOCK: do not block when opening special files (e.g. pipes)\nSAFE_FLAGS = os.O_NOFOLLOW | os.O_NONBLOCK\n\"\"\"Flags needed to open a fd without following symlinks.\"\"\"\n\nREAD_SAFE_FLAGS = os.O_RDONLY | SAFE_FLAGS\n\"\"\"Flags to open a fd in read-only mode without following symlinks.\"\"\"\n\nPathLike = Union[str, Path]\n\n\ndef _validate_path_component(component: str) -> None:\n \"\"\"Check that a component of a path is valid.\"\"\"\n if (\n not component\n or os.sep in component\n or os.path.sep in component\n or component in [\".\", \"..\"]\n ):\n raise REANAWorkspaceError(f\"'{component}' is not a valid path component\")\n\n\ndef _open_single_component(name: str, dir_fd: int, flags: int = READ_SAFE_FLAGS) -> int:\n \"\"\"Open a file contained in a directory.\"\"\"\n _validate_path_component(name)\n try:\n fd = os.open(name, flags | SAFE_FLAGS, dir_fd=dir_fd)\n except OSError as e:\n if e.errno == errno.ELOOP:\n raise REANAWorkspaceError(f\"Opening symlink '{name}' is not allowed\")\n raise\n return fd\n\n\ndef open_fd(workspace: PathLike, path: PathLike, flags=READ_SAFE_FLAGS) -> int:\n \"\"\"Open a fd inside a workspace.\"\"\"\n path = Path(path)\n fd = os.open(workspace, READ_SAFE_FLAGS)\n for i, part in enumerate(path.parts):\n # parent directories are always opened in read-only mode\n curr_flags = READ_SAFE_FLAGS\n if i + 1 == len(path.parts):\n # the last component of the path is opened with the provided flags\n curr_flags = flags\n try:\n new_fd = _open_single_component(part, dir_fd=fd, flags=curr_flags)\n finally:\n os.close(fd)\n fd = new_fd\n return fd\n\n\ndef open_file(workspace: PathLike, path: PathLike, mode: str = \"r\"):\n \"\"\"Open a file inside a workspace.\"\"\"\n\n def opener(path, flags):\n fd = open_fd(workspace, path, flags)\n st_mode = os.fstat(fd).st_mode\n if not stat.S_ISREG(st_mode):\n os.close(fd)\n raise REANAWorkspaceError(f\"'{path}' is not a regular file\")\n return fd\n\n return open(path, mode=mode, opener=opener)\n\n\ndef delete(workspace: PathLike, path: PathLike) -> int:\n \"\"\"Delete a file or an empty directory inside a workspace.\"\"\"\n path = Path(path)\n parent_fd = open_fd(workspace, path.parent)\n try:\n st = os.lstat(path.name, dir_fd=parent_fd)\n st_mode = st.st_mode\n st_size = st.st_size\n if stat.S_ISREG(st_mode) or stat.S_ISLNK(st_mode):\n os.unlink(path.name, dir_fd=parent_fd)\n elif stat.S_ISDIR(st_mode):\n os.rmdir(path.name, dir_fd=parent_fd)\n else:\n raise REANAWorkspaceError(f\"'{path}' should be a file or a directory\")\n finally:\n os.close(parent_fd)\n return st_size\n\n\ndef move(workspace: PathLike, src: PathLike, dst: PathLike) -> None:\n \"\"\"Move the file or directory `src` to `dst`.\"\"\"\n src = Path(src)\n dst = Path(dst)\n\n # If `dst` already exists and it is a directory, we move `src` inside it\n if is_directory(workspace, dst):\n dst_fd = open_fd(workspace, dst)\n dst_name = src.name\n else:\n dst_fd = open_fd(workspace, dst.parent)\n dst_name = dst.name\n\n src_fd = None\n try:\n src_fd = open_fd(workspace, src.parent)\n os.replace(src.name, dst_name, src_dir_fd=src_fd, dst_dir_fd=dst_fd)\n finally:\n if src_fd is not None:\n os.close(src_fd)\n if dst_fd is not None:\n os.close(dst_fd)\n\n\ndef lstat(workspace: PathLike, path: PathLike) -> os.stat_result:\n \"\"\"Get the stat of a file inside a workspace.\"\"\"\n path = Path(path)\n dir_fd = open_fd(workspace, path.parent)\n try:\n st = os.lstat(path.name, dir_fd=dir_fd)\n finally:\n os.close(dir_fd)\n return st\n\n\ndef makedirs(workspace: PathLike, path: PathLike) -> None:\n \"\"\"Recursively create directories inside a workspace.\"\"\"\n path = Path(path)\n fd = os.open(workspace, READ_SAFE_FLAGS)\n for part in path.parts:\n try:\n _validate_path_component(part)\n try:\n os.mkdir(part, dir_fd=fd)\n except FileExistsError:\n pass\n new_fd = _open_single_component(part, dir_fd=fd)\n # TODO: check this is actually a directory?\n finally:\n os.close(fd)\n fd = new_fd\n os.close(fd)\n\n\ndef is_directory(workspace: PathLike, path: PathLike) -> bool:\n \"\"\"Check whether a path refers to a directory.\"\"\"\n try:\n st = lstat(workspace, path)\n if stat.S_ISDIR(st.st_mode):\n return True\n except Exception:\n pass\n return False\n\n\ndef walk(\n workspace: PathLike,\n path: PathLike = \"\",\n topdown: bool = True,\n include_dirs: bool = True,\n) -> Generator[str, None, None]:\n \"\"\"Get the list of entries inside a workspace.\"\"\"\n root_fd = open_fd(workspace, path)\n path = Path(path)\n try:\n for dirpath, dirnames, filenames, dirfd in os.fwalk(\n dir_fd=root_fd, topdown=topdown\n ):\n for dirname in dirnames:\n if include_dirs or stat.S_ISLNK(\n os.lstat(dirname, dir_fd=dirfd).st_mode\n ):\n yield str(path.joinpath(dirpath, dirname))\n for filename in filenames:\n yield str(path.joinpath(dirpath, filename))\n finally:\n os.close(root_fd)\n\n\ndef iterdir(workspace: PathLike, path: PathLike) -> Generator[str, None, None]:\n \"\"\"Iterate over the contents of a directory.\"\"\"\n dir_fd = open_fd(workspace, path)\n path = Path(path)\n try:\n for filename in os.listdir(dir_fd):\n yield str(path / filename)\n finally:\n os.close(dir_fd)\n\n\ndef glob(\n workspace: PathLike, pattern: str, topdown: bool = True, include_dirs: bool = True\n) -> Generator[str, None, None]:\n \"\"\"Get the list of entries in a workspace that match a given pattern.\"\"\"\n # `wcmatch` returns two lists of regexps, one for \"include\" and the other\n # for \"exclude\" patterns. We are only interested in the \"include\" patterns.\n include_regex, exclude_regex = wcmatch.glob.translate(\n pattern, flags=wcmatch.glob.GLOBSTAR | wcmatch.glob.DOTGLOB\n )\n if len(include_regex) != 1 or len(exclude_regex) != 0:\n raise REANAWorkspaceError(\"The provided pattern is not valid\")\n compiled_regex = re.compile(include_regex.pop())\n for filepath in walk(workspace, topdown=topdown, include_dirs=include_dirs):\n if compiled_regex.match(filepath):\n yield filepath\n\n\ndef glob_or_walk_directory(\n workspace: PathLike,\n path_or_pattern: str,\n topdown: bool = True,\n include_dirs: bool = True,\n) -> Generator[str, None, None]:\n \"\"\"Get the list of entries inside a directory or that match a given pattern.\"\"\"\n if is_directory(workspace, path_or_pattern):\n yield from walk(workspace, path_or_pattern, topdown, include_dirs)\n else:\n yield from glob(workspace, path_or_pattern, topdown, include_dirs)\n","sub_path":"reana_commons/workspace.py","file_name":"workspace.py","file_ext":"py","file_size_in_byte":7536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"395674888","text":"from lxml import etree\nimport ConfigParser, os, re\n\nsettings = ConfigParser.ConfigParser()\n\nif os.path.split(os.getcwd())[-1] == 'lib':\n settings.read('../conf/assessment.conf')\nelse:\n settings.read('conf/assessment.conf')\n\ndef evaluateReport(report_file):\n alerts = []\n ports = settings.get('NMAP_TEST', 'Ports').split(', ')\n report = etree.parse(report_file)\n for port in ports:\n find_text = etree.XPath( \"/SECANT/NMAP_TEST/ports/port[contains(@portid, \" + port + \")]\")\n if find_text(report):\n alerts.append(\"Port \" + port + \" is open\")\n return alerts","sub_path":"external_tests/ntp_amplification_test/ntp_amplification_test.py","file_name":"ntp_amplification_test.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"639882264","text":"\"\"\" Alice (localhost) \"\"\"\nimport socket, pickle, random\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import serialization, asymmetric\nfrom lib.MyCryptoLibrary import MyCryptoLibrary\n\n\n# Key generation\nalice_private_key = asymmetric.rsa.generate_private_key(\n public_exponent=65537,\n key_size=2048,\n backend=default_backend())\n\n# Assuming that Bob has Alice's PK, thus saving it as PEM format at Bob's PC.\nalice_key_pem = alice_private_key.public_key().public_bytes(\n encoding=serialization.Encoding.PEM,\n format=serialization.PublicFormat.SubjectPublicKeyInfo)\n\nwith open(\"PK_alice.pem\", \"wb\") as key:\n key.write(alice_key_pem)\n\n\ndef retrieve_bobs_pk():\n with open(\"PK_bob.pem\", \"rb\") as pem_file:\n PK = serialization.load_pem_public_key(\n pem_file.read(),\n backend=default_backend())\n return PK\n\n\ndef decrypt_and_verify(data, PK):\n decrypted_message = MyCryptoLibrary.decrypt_message(data[0], alice_private_key)\n MyCryptoLibrary.verify_message(decrypted_message, data[1], PK)\n return decrypted_message\n\n\ndef send_encrypted_signed_message(msg, PK):\n cipher_text = MyCryptoLibrary.encrypt_message(msg, PK)\n signature_alice = MyCryptoLibrary.sign_message(msg, alice_private_key)\n data = (cipher_text, signature_alice)\n data_string = pickle.dumps(data)\n server.send(data_string)\n\n\ndef compute_dice_throw(a, b):\n dice_throw = bin(int(a) ^ int(b))\n converted_dice_throw = (int(dice_throw, 2) % 6) + 1\n print(\"Alice computes throw to be \", converted_dice_throw)\n return converted_dice_throw\n\n\n# TCP with ipv4\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nhost = \"127.0.0.1\"; port = 6677\naddress = (host, port)\n\n# Connect to address\nserver.connect(address)\nrunning = True\nprint(f\"[Connected to {host} at port {port}]\")\n\n\nwhile running:\n # Get prerequisites\n PK_bob = retrieve_bobs_pk()\n\n print(\"********* Alice's dice throw *********\")\n\n # [a1] Alice samples random bit a and random 128 bit string and sends Com(a,r)\n a1 = '1001' # Alice not honest!!!!!!!!!!!!!!!!\n r1 = format(random.getrandbits(128), \"b\")\n c1 = bytes(a1 + r1, encoding=\"utf-8\")\n c_hashed1 = MyCryptoLibrary.hash_message(c1)\n send_encrypted_signed_message(c_hashed1, PK_bob)\n print(\"Sending encrypted Com(a,r) to Bob\")\n\n # [a2] Message b received\n received_data = pickle.loads(server.recv(2048))\n print(\"Alice received b from Bob and tries to verify\")\n b1 = decrypt_and_verify(received_data, PK_bob)\n\n # [a3] Alice sends (a,r) to Bob\n a_r = bytes(a1 + \",\" + r1, encoding=\"utf-8\")\n send_encrypted_signed_message(a_r, PK_bob)\n\n # [a4] Compute output a XOR b under mod 6\n compute_dice_throw(a1, b1)\n\n print()\n print(\"********* Bob's dice throw *********\")\n\n # [a1] Message Com(a,r) received from Bob\n received_data2 = pickle.loads(server.recv(2048))\n print(\"Bob received Com(a,r) from Alice and tries to verify\")\n decrypted_hashed_c_from_bob = decrypt_and_verify(received_data2, PK_bob)\n\n # [a2] Alice sends random bit a to Bob\n a2 = bytes(format(random.getrandbits(4), \"b\"), encoding=\"utf-8\")\n send_encrypted_signed_message(a2, PK_bob)\n\n # [a3] Receive second message (a,r) from Bob\n received_data3 = pickle.loads((server.recv(2048)))\n print(\"Alice received (a,r) from Bob and tries to verify\")\n decrypted_b_r = decrypt_and_verify(received_data3, PK_bob)\n decoded_split_b_r = decrypted_b_r.decode(\"utf-8\").split(\",\")\n bob_b2 = decoded_split_b_r[0]\n opened_commitment = bytes(decoded_split_b_r[0] + decoded_split_b_r[1], \"utf-8\")\n\n # [a4] Alice is hashing a + r for checking and computing dice throw\n opened_commitment_hashed = MyCryptoLibrary.hash_message(opened_commitment)\n\n if decrypted_hashed_c_from_bob == opened_commitment_hashed:\n print(\"Alice is checking if the hashes match\")\n print(\"[Success] No changes we made to the message\")\n bob_b = decoded_split_b_r[0]\n alice_a = a2.decode(\"utf-8\")\n compute_dice_throw(alice_a, bob_b)\n else:\n print(\"[WARNING] Bob changed his message\")\n\n running = False\n\nserver.close()\n","sub_path":"alice_local.py","file_name":"alice_local.py","file_ext":"py","file_size_in_byte":4196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"441091489","text":"from flask import Flask, render_template, request\n\nfrom mbta_helper import find_stop_near\n\napp = Flask(__name__)\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef calculate():\n if request.method == 'POST':\n Location = request.form['location']\n Near_stop,wheelchair = find_stop_near(Location)\n # Country Code = float(request.form['country code'])\n # we want results from api\n if Near_stop and wheelchair:\n return render_template('mbta_result.html',location=Location,near_stop=Near_stop,wheelchair=wheelchair)\n else:\n return render_template('mbta_form.html',error=True)\n return render_template('mbta_form.html', error=None)\n\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"176039889","text":"'''*************************************************************\nFileName [exp_clp_tl.py]\nProjectName [Threshold logic synthesis and verification.]\nSynopsis [Script for collapsing TL circuits experiments.]\nAuthor [Nian-Ze Lee]\nAffiliation [NTU]\nDate [16.01.2020]\n*******************************************************************'''\n\nimport os\nimport glob\nimport argparse\nimport subprocess as sp\nparser = argparse.ArgumentParser( description = \"Parsing collapsing TL circuits experimental settings ...\" )\nparser.add_argument( \"-i\", action=\"store_true\", dest=\"ite\", default=False, help=\"enabling iterative collapsing (default=False)\" )\nparser.add_argument( \"-t\", action=\"store_true\", dest=\"tcad\", default=False, help=\"enabling TCAD suggestion (default=False)\" )\nargs = parser.parse_args()\nopt1 = \" -B 100\" if args.ite else \"\"\nopt2 = \" -t\" if args.tcad else \"\"\nsyn = \"tl_syn; mt\" + opt1 + opt2 + \"; pt; q\"\nsuf1 = \"_i\" if args.ite else \"\"\nsuf2 = \"_t\" if args.tcad else \"\"\nsuf = suf1 + suf2\nfor bch in glob.glob(\"exp_TCAD/collapse/benchmark/iscas_itc/*.blif\"):\n name = os.path.basename(bch)\n log = (\"exp_TCAD/collapse/log/%s_tl%s.log\" % (name, suf))\n tcl = \"r \" + bch + \"; \" + syn\n cmd = \"bin/abc -c \\\"\" + tcl + \"\\\" &> \" + log\n sp.run(cmd, shell=True)\n","sub_path":"exp_TCAD/collapse/script/exp_clp_tl.py","file_name":"exp_clp_tl.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"558514672","text":"import sys\nimport numpy as np\nsys.path.append(\"..\")\n\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\nfrom Vgg19 import Vgg19\n\nbatch_norm = tf.layers.batch_normalization \nvgg_file_path = '/home/cgim/桌面/tensorflow_train/GAN/vgg19.npy'\nclass SRGAN:\n def __init__(self,is_training,vgg_weight):\n self.is_training = is_training\n self.epsilon = 1e-5\n self.weight_decay = 0.00001\n self.vgg_weight = vgg_weight\n self.REAL_LABEL=0.9\n\n def preprocess(self,images,scale=False):\n images = tf.to_float(images)\n if scale:\n images = tf.div(images, 127.5)\n images = tf.subtract(images, 1.0)\n return images\n\n def sample(self, input, type=\"down\",sample_size=4):\n shape = input.get_shape().as_list() # NHWC\n if (type == \"down\"):\n h = int(shape[1] // sample_size)\n w = int(shape[1] // sample_size)\n else:\n h = int(shape[1] * sample_size)\n w = int(shape[1] * sample_size)\n resized_image = tf.image.resize_images(input, [h, w],\n tf.image.ResizeMethod.BILINEAR)\n return resized_image\n\n def Resblock(self,inputs,scope_name):\n with tf.variable_scope(scope_name+\"/layer1\") as scope:\n conv1 = slim.conv2d(inputs,64,[3,3],[1,1])\n norm1 = slim.batch_norm(conv1)\n relu1 = tf.nn.relu(norm1)\n with tf.variable_scope(scope_name+\"/layer2\") as scope:\n conv2 = slim.conv2d(relu1,64,[3,3],[1,1])\n norm2 = slim.batch_norm(conv2)\n return inputs+norm2\n\n def get_content_loss(self,feature_a,feature_b,type=\"VGG\"):\n if type==\"VGG\":\n print(\"Using VGG loss as content loss!\")\n vgg_a, vgg_b = Vgg19(vgg_file_path), Vgg19(vgg_file_path)\n vgg_a.build(feature_a)\n vgg_b.build(feature_b)\n VGG_loss = tf.reduce_mean(tf.losses.absolute_difference(vgg_a.conv4_4, vgg_b.conv4_4))\n h = tf.cast(tf.shape(vgg_a.conv4_4)[1], tf.float32)\n w = tf.cast(tf.shape(vgg_a.conv4_4)[2], tf.float32)\n c = tf.cast(tf.shape(vgg_a.conv4_4)[3], tf.float32)\n content_loss = VGG_loss/(h*w*c)\n else:\n print(\"Using MSE loss of images as content loss!\")\n content_loss=tf.reduce_mean(tf.losses.absolute_difference(feature_a , feature_b))\n return content_loss\n\n def pixel_shuffle_layer(self,x, r, n_split):\n def PS(x, r):\n bs, a, b, c = x.get_shape().as_list()\n x = tf.reshape(x, (-1, a, b, r, r))\n x = tf.transpose(x, [0, 1, 2, 4, 3])\n x = tf.split(x, a, 1)\n x = tf.concat([tf.squeeze(x_) for x_ in x], 2)\n x = tf.split(x, b, 1)\n x = tf.concat([tf.squeeze(x_) for x_ in x], 2)\n return tf.reshape(x, (-1, a * r, b * r, 1))\n xc = tf.split(x, n_split, 3)\n return tf.concat([PS(x_, r) for x_ in xc], 3)\n\n #(64*64--->256*256)\n def generator(self,inputs,name_scope,reuse=False):\n print(\"SRGAN_onlyMSE_generator\")\n with tf.variable_scope(name_scope,reuse=reuse) as scope:\n w_init = tf.truncated_normal_initializer(mean=0.0, stddev=0.02)\n with slim.arg_scope([slim.conv2d],weights_initializer=w_init,padding=\"SAME\",activation_fn=None):\n with slim.arg_scope([slim.conv2d_transpose],weights_initializer=w_init,padding=\"SAME\",activation_fn=None):\n with slim.arg_scope([slim.batch_norm], decay=0.9, epsilon=1e-5, scale=True,\n activation_fn=None,is_training=self.is_training):\n print(\"inputs:\",inputs)\n net = slim.conv2d(inputs,64,[3,3],[1,1])\n net = tf.nn.relu(net)\n\n short_cut = net\n print(\"net1:\", net)\n #8 Resblock\n for i in range(6):\n net = self.Resblock(net, \"ResBlock{}\".format(i))\n \n #DeConv\n net = slim.conv2d_transpose(net, 64, [3,3], [1,1])\n net = slim.batch_norm(net)\n net = net+short_cut\n\n print(\"net2:\",net)\n net = slim.conv2d_transpose(net, 256, [3, 3], [1, 1])\n print(\"net3:\",net)\n net = self.pixel_shuffle_layer(net, 2, 64)\n net = tf.nn.relu(net)\n print(\"net4:\",net)\n net = slim.conv2d_transpose(net, 256, [3, 3], [1, 1])\n print(\"net5:\",net)\n net = self.pixel_shuffle_layer(net, 2, 64)\n net = tf.nn.relu(net)\n\n net = slim.conv2d(net, 3, [3, 3], [1, 1],activation_fn=tf.nn.tanh)\n return net\n\n # (256*256--->1)\n def discriminator(self,inputs,name_scope,reuse=False):\n print(\"SRGAN_onlyMSE_discriminator\")\n with tf.variable_scope(name_scope,reuse=reuse) as scope:\n w_init = tf.truncated_normal_initializer(mean=0.0, stddev=0.02)\n with slim.arg_scope([slim.conv2d], weights_initializer=w_init, padding=\"SAME\", activation_fn=None):\n with slim.arg_scope([slim.conv2d_transpose], weights_initializer=w_init, padding=\"SAME\",activation_fn=None):\n with slim.arg_scope([slim.batch_norm], decay=0.9, epsilon=1e-5, scale=True,activation_fn=None,is_training=self.is_training):\n nfg = 64\n net = slim.conv2d(inputs,nfg,[3,3],[1,1])\n net = tf.nn.leaky_relu(net)\n print(\"net:\",net)\n\n for i in range(1,5):\n net = slim.conv2d(net, nfg, [3, 3], [2, 2])\n net = slim.batch_norm(net)\n net = tf.nn.leaky_relu(net)\n\n net = slim.conv2d(net, nfg*2, [3, 3], [1, 1])\n net = slim.batch_norm(net)\n net = tf.nn.leaky_relu(net)\n nfg *= 2\n print(\"dis{}:\".format(i),net)\n\n net = slim.conv2d(net, nfg, [3, 3], [2, 2])\n net = slim.batch_norm(net)\n logits = tf.nn.leaky_relu(net)\n\n net_flat = tf.layers.flatten(net)\n dense_net = slim.fully_connected(net_flat,1024)\n dense_net = tf.nn.leaky_relu(dense_net)\n logits = slim.fully_connected(dense_net, 1)\n return logits\n\n def get_vars(self):\n all_vars = tf.trainable_variables()\n dis_vars = [var for var in all_vars if 'discriminator' in var.name]\n gen_vars = [var for var in all_vars if 'generator' in var.name]\n \n return gen_vars,dis_vars\n\n def build_CartoonGAN(self,LR,HR):\n #归一化\n LR_pre = self.preprocess(LR, scale=True)\n HR_pre = self.preprocess(HR, scale=True)\n\n #reality --> cartoon\n fake_HR = self.generator(LR_pre,\"generator\")\n\n fake_HR_logits = self.discriminator(fake_HR, \"discriminator\", reuse=False)\n real_HR_logits = self.discriminator(HR_pre, \"discriminator\", reuse=True)\n\n #GAN损失\n real_dis_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n logits=real_HR_logits,labels=tf.ones_like(real_HR_logits)))\n fake_dis_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n logits=fake_HR_logits,labels=tf.zeros_like(fake_HR_logits)))\n fake_gen_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n logits=fake_HR_logits,labels=tf.ones_like(fake_HR_logits)))\n dis_loss = real_dis_loss+fake_dis_loss\n\n print(\"size:\",HR_pre,fake_HR)\n content_loss = self.get_content_loss(HR_pre, fake_HR,\"no_VGG\")\n psnr = self.get_PSNR(HR_pre,fake_HR)\n gen_loss = fake_gen_loss + self.vgg_weight*content_loss\n\n return gen_loss,dis_loss,content_loss,psnr\n\n def get_PSNR(self,real, fake):\n mse = tf.reduce_mean(tf.square(127.5 * (real - fake) + 127.5), axis=(-3, -2, -1))\n psnr = tf.reduce_mean(10 * (tf.log(255 * 255 / tf.sqrt(mse)) / np.log(10)))\n return psnr\n def sample_generate(self,LR):\n LR_pre = self.preprocess(LR, scale=True)\n HR_out = self.generator(LR_pre,name_scope=\"generator\",reuse=True)\n return HR_out\n\n\n\n","sub_path":"GANs_Advanced/SRGAN/net/SRGAN_onlyMSE.py","file_name":"SRGAN_onlyMSE.py","file_ext":"py","file_size_in_byte":8736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"388604599","text":"import sys\nimport os\nimport logging\nimport logging.handlers\nfrom common.variables import LOGGING_LEVEL\nsys.path.append('../')\n\n\nFORMATTER_FOR_CLIENT = logging.Formatter(\n '%(asctime)-27s %(levelname)-10s %(filename)-23s %(message)s')\n\nPATH = os.path.dirname(os.path.abspath(__file__))\nPATH = os.path.join(os.path.split(PATH)[0], r'files\\client.log')\n\n# создаём потоки вывода логов\nSTREAM_HANDLER = logging.StreamHandler(sys.stderr)\nSTREAM_HANDLER.setFormatter(FORMATTER_FOR_CLIENT)\nSTREAM_HANDLER.setLevel(logging.ERROR)\n\nLOG_FILE = logging.FileHandler(PATH, encoding='utf8')\nLOG_FILE.setFormatter(FORMATTER_FOR_CLIENT)\n\n# создаём регистратор и настраиваем его\nLOG_CLIENT = logging.getLogger('client')\nLOG_CLIENT.addHandler(STREAM_HANDLER)\nLOG_CLIENT.addHandler(LOG_FILE)\nLOG_CLIENT.setLevel(LOGGING_LEVEL)\n\n# отладка\nif __name__ == '__main__':\n LOG_CLIENT.critical('Критическая ошибка')\n LOG_CLIENT.error('Ошибка')\n LOG_CLIENT.debug('Отладочная информация')\n LOG_CLIENT.info('Информационное сообщение')\n","sub_path":"logs/configs/config_client_log.py","file_name":"config_client_log.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"452828497","text":"import matplotlib.pyplot as plt\nfrom matplotlib import lines\nimport sys\nfrom math import sqrt\n\ndef print_spanning_tree(points):\n x_list = []\n y_list = []\n\n for (x, y) in points:\n x_list.append(x)\n y_list.append(y)\n\n plt.plot(x_list, y_list, 'ro')\n\n reached = []\n unreached = [] + points\n\n reached.append(unreached[0])\n unreached.pop(0)\n\n while len(unreached) > 0:\n record = sys.maxsize\n r_index = None\n u_index = None\n \n for i in range(len(reached)):\n for j in range(len(unreached)):\n x = (reached[i][0] - unreached[j][0])\n y = (reached[i][1] - unreached[j][1])\n distance = sqrt(x ** 2 + y ** 2)\n\n if distance < record:\n record = distance\n r_index = i\n u_index = j\n \n line = lines.Line2D(\n [reached[r_index][0], unreached[u_index][0]],\n [reached[r_index][1], unreached[u_index][1]]\n )\n plt.axes().add_line(line)\n\n reached.append(unreached[u_index])\n unreached.pop(u_index)\n\n plt.show()\n","sub_path":"src/spanning_tree.py","file_name":"spanning_tree.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"68288019","text":"import numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nimport matplotlib.patches as mpatches\nimport pickle\nimport time\nimport os.path\nimport argparse\nfrom sklearn.metrics import roc_curve, auc, f1_score, confusion_matrix\nimport tensorflow as tf\nimport h5py\nimport re\n\nplt.style.use(\"./matplotlib_LHCb.mplstyle\")\n\nwith open(\"../../../data/Val_md_labels_264972.pickle\", \"rb\") as f:\n test_y = pickle.load(f)\n\nwith h5py.File(\"../../../data/Processed_Val_md_264972.h5\", \"r\") as valData:\n data = valData[\"Val\"][:]\n\nwith open(\"../../../data/inc_pca_mu_354.pickle\", \"rb\") as f:\n inc_pca = pickle.load(f)\n\ndef get_sg(fname, labels=True):\n sg = pd.read_pickle(fname)\n\n if labels:\n lbls = np.ones(sg.shape[0])\n return sg, lbls\n else:\n return sg\n\ndef get_bg(fname, labels=True):\n bg = pd.read_pickle(fname)\n\n if labels:\n lbls = np.zeros(bg.shape[0])\n return bg, lbls\n else:\n return bg\n\ndef get_sg_and_bg(file_sig, file_bkg, labels=True, shuffle=True, random_state=42):\n if labels:\n sgx, sgy = get_sg(file_sig, labels=True)\n bgx, bgy = get_bg(file_bkg, labels=True)\n else:\n sgx = get_sg(file_sig, labels=False)\n bgx = get_bg(file_bkg, labels=False)\n\n miss_in_bg = [col for col in sgx.columns.values if col not in bgx.columns.values]\n\n miss_in_signal = [col for col in bgx.columns.values if col not in sgx.columns.values]\n\n print(\"Dropped in bg: {}\\n\\n Dropped in signal: {}\".format(miss_in_bg, miss_in_signal))\n sgx.drop(miss_in_bg, inplace = True, axis = 1)\n bgx.drop(miss_in_signal, inplace = True, axis = 1)\n data = pd.concat((sgx, bgx))\n indices = np.arange(data.shape[0])\n\n if shuffle:\n np.random.seed(random_state)\n np.random.shuffle(indices)\n data = data.iloc[indices, :]\n\n if labels:\n labels = np.concatenate((sgy, bgy))[indices]\n return data, labels\n else:\n return data\n\nnr_features = data.shape[1]\nnr_classes = len(list(np.unique(test_y)))\n\ndef savefig(list_of_plots, path):\n import matplotlib.backends.backend_pdf\n pdf = matplotlib.backends.backend_pdf.PdfPages(path)\n for fig in list_of_plots:\n pdf.savefig(fig)\n pdf.close()\n\n\ndef build_csv_summary(stats_nr, filename, sortby):\n if type(stats_nr) != list:\n stats_nr = [stats_nr]\n\n curdir = os.path.abspath(os.path.curdir)\n folders = [\"{}/nn_logs{}\".format(curdir, nr) for nr in stats_nr]\n out_file = filename + \".csv\"\n\n columns = [\"stats_nr\", \"NNType\", \"nodes\", \"activations\", \"DropOut\", \"max_acc\", \"max_acc_std\", \"roc_auc\", \"F1\", \"acc\", \"std\", \"train_examples\", \"test_examples\", \"feature_size\", \"optimizer\", \"epochs\", \"time\", \"fcost\", \"batchNorm\", \"PCA\"]\n out_df = pd.DataFrame()\n\n collective_dict = {}\n for col in columns:\n collective_dict[col] = []\n\n for folder,statsNr in zip(folders, stats_nr):\n try:\n with open(folder+\"/stats{}.pickle\".format(statsNr), \"rb\") as f:\n in_dict = pickle.load(f)\n except FileNotFoundError:\n continue\n\n roc_auc = {}\n F1 = {}\n\n if in_dict[\"PCA\"]:\n test_x = inc_pca.transform(data)\n else:\n test_x = data\n\n with open(folder+\"/Models/checkpoint\", \"r\") as f, tf.Session() as sess:\n new_saver = tf.train.import_meta_graph(folder+'/Models/NNModel-0.meta')\n lines = f.readlines()\n pattern = \"nn_logs.*\"\n for line in lines[1:]:\n regExp = re.search(pattern, line)\n filename = regExp.group(0)[:-1]\n regExp = re.search(\"[0-9]+$\", filename)\n e = int(regExp.group(0))\n\n new_saver.restore(sess, filename)\n graph = tf.get_default_graph()\n x = graph.get_tensor_by_name(\"x:0\")\n y = graph.get_tensor_by_name(\"y:0\")\n tr_phase = graph.get_tensor_by_name(\"trainPhase:0\")\n pred_proba = graph.get_tensor_by_name(\"Model/predProba:0\")\n pred = pred_proba.eval({x: test_x, tr_phase: 1})\n pred = np.array([np.argmax(p) for p in pred])\n\n fpr, tpr, _ = roc_curve(test_y, pred)\n roc_auc[\"{}\".format(e)] = auc(fpr, tpr)\n\n #F1\n f1 = f1_score(test_y, pred)\n F1[\"{}\".format(e)]= f1\n\n tf.reset_default_graph()\n max_auc = max(roc_auc.values())\n max_F1 = max(F1.values())\n\n for col in columns:\n try:\n if col == \"acc\":\n collective_dict[\"max_acc\"] += [np.round(np.mean(np.amax(in_dict[col], axis=1)), 4) * 100]\n collective_dict[\"max_acc_std\"] += [np.round(np.std(np.amax(in_dict[col], axis=1)), 4) * 100]\n collective_dict[col] += [np.round(np.mean(in_dict[col][:,-1]), 4) * 100]\n collective_dict[\"std\"] += [np.round(np.std(in_dict[col][:,-1]), 4) * 100]\n elif col == \"train_examples\":\n collective_dict[col] += [in_dict[col]]\n collective_dict[\"test_examples\"] += [int(in_dict[\"test_size\"])]\n elif col == \"features\":\n collective_dict[col] += [len(in_dict[col])]\n elif col in [\"max_acc\", \"max_acc_std\", \"std\", \"test_examples\"]:\n pass\n elif col == \"time\":\n collective_dict[col] += [np.round(in_dict[col], 0)]\n elif col == \"roc_auc\":\n collective_dict[col] += [round(max_auc, 4)]\n elif col == \"F1\":\n collective_dict[col] += [round(max_F1, 4)]\n else:\n collective_dict[col] += [in_dict[col]]\n except KeyError:\n collective_dict[col] += [\"Not implemented\"]\n\n print(folder+\" used for summary.\")\n\n\n for col in columns:\n out_df[col] = collective_dict[col]\n\n out_df.sort_values(by=sortby, ascending = False, inplace = True)\n out_df.to_csv(out_file)\n print(\"\\n\" + out_file + \" successfully built.\\n\")\n\n\ndef build_full_output(stats, histogram, nr, acc, lastEpoch):\n for i in range(100):\n filename1 = \"./Logs/log{}_{}.txt\".format(i, nr)\n filename2 = \"./Figures/fig{}_{}_acc{}_last{}.pdf\".format(i, nr, str(acc)[0], str(lastEpoch)[0])\n if not os.path.isfile(filename1) and not os.path.isfile(filename2):\n with open(filename1, \"w\") as f:\n\n f.write(\"Start date: {}, Corresponding stats: {}\".format(time.strftime(\"%c\"), nr))\n f.write(\"\\n\"+\"#\"*10)\n f.write(\"\\n\\tNetwork Information\")\n f.write(\"\\n\"+\"#\"*10)\n\n f.write(\"\\n\\nNetwork type: {}\".format(stats[\"NNType\"]))\n f.write(\"\\n\\nStructure: {}\".format(stats[\"nodes\"]))\n f.write(\"\\nActivations: {}\".format(stats[\"activations\"]))\n f.write(\"\\nDropout: {}\".format(stats[\"DropOut\"]))\n\n\n f.write(\"\\n\\n\"+\"#\"*10)\n f.write(\"\\n\\tTraining Information\")\n f.write(\"\\n\"+\"#\"*10)\n\n f.write(\"\\n\\nTrainingSet: {}, Epochs: {}, batch_size: {}\".format(stats[\"train_examples\"], stats[\"epochs\"], stats[\"batch\"]))\n f.write(\"\\n\\nOptimizer: {}\".format(stats[\"optimizer\"]))\n f.write(\"\\n\\n#Features: {} - {}\".format(len(stats[\"features\"]), stats[\"feature_size\"]))\n f.write(\"\\n\\nStandardized Features: {}\".format(stats[\"standFeatures\"]))\n f.write(\"\\n\\nLog-transformed Features: {}\".format(stats[\"LogTransformed\"]))\n f.write(\"\\n\\nFeatures: {}\".format(stats[\"features\"]))\n try:\n f.write(\"\\n\\nApplied cuts: {}\".format(stats[\"cuts\"]))\n except KeyError:\n pass\n\n\n f.write(\"\\n\\n\"+\"#\"*10)\n f.write(\"\\n\\tEvaluation Information\")\n f.write(\"\\n\"+\"#\"*10)\n\n test_accs = stats[\"acc\"][:,-1]\n f.write(\"\\n\\nFinal test accuracy: {}\".format(test_accs))\n f.write(\"\\nK-Fold test accuracy: {} pm {}\".format(np.mean(test_accs), np.std(test_accs)))\n\n max_test_acc = np.amax(stats[\"acc\"], axis=1)\n f.write(\"\\n\\nMax test accuracies: {} --- Epoch: {}\".format(max_test_acc, np.argmax(stats[\"acc\"], axis=1)))\n f.write(\"\\nK-Fold max accuracy: {} pm {}\".format(np.mean(max_test_acc), np.std(max_test_acc)))\n\n\n lossess = stats[\"losses\"][:,-1]\n f.write(\"\\nK-Fold cost: {} pm {}\".format(np.mean(lossess), np.std(lossess)))\n\n f.write(\"\\n\\n{}\".format(create_confusion_matrix(stats, nr)))\n f.write(\"\\n\\n\"+\"#\"*10)\n f.write(\"\\n\\tEvaluation Details\")\n f.write(\"\\n\"+\"#\"*10)\n\n f.write(\"\\n\\nLosses: {}\".format(stats[\"losses\"]))\n f.write(\"\\n\\nTraining Accuracy: {}\".format(stats[\"train_acc\"]))\n f.write(\"\\n\\nTest Accuracy: {}\".format(stats[\"acc\"]))\n\n t = stats[\"time\"]\n f.write(\"\\n\\nTraining Time: {}s, {}min, {}h\".format(t, t/60, t/3600))\n\n build_figures(stats, path=filename2, histogram=histogram, nr=nr, acc=acc, lastEpoch=lastEpoch)\n print(\"Log and figures file: {}_{}\".format(i, nr))\n break\n\n\ndef create_confusion_matrix(stats, nr):\n confMatrices = \"Confusion matrix | Precision | Recall: \\n\"\n if stats[\"PCA\"]:\n test_x = inc_pca.transform(data)\n else:\n test_x = data\n\n folder = \"./nn_logs{}\".format(nr)\n with open(folder+\"/Models/checkpoint\", \"r\") as f, tf.Session() as sess:\n new_saver = tf.train.import_meta_graph(folder+'/Models/NNModel-0.meta')\n lines = f.readlines()\n pattern = \"nn_logs.*\"\n for line in lines[1:]:\n regExp = re.search(pattern, line)\n filename = regExp.group(0)[:-1]\n print(\"\\n\\n\\n{}\\n\\n\".format(filename))\n regExp = re.search(\"[0-9]+$\", filename)\n e = int(regExp.group(0))\n\n new_saver.restore(sess, filename)\n graph = tf.get_default_graph()\n x = graph.get_tensor_by_name(\"x:0\")\n y = graph.get_tensor_by_name(\"y:0\")\n tr_phase = graph.get_tensor_by_name(\"trainPhase:0\")\n pred_proba = graph.get_tensor_by_name(\"Model/predProba:0\")\n pred = pred_proba.eval({x: test_x, tr_phase: 1})\n pred = np.array([np.argmax(p) for p in pred])\n\n confMatrices = confMatrices + \"{} Epoch {}\".format(\"---\"*10, e)\n confMatrix = confusion_matrix(test_y, pred)\n confMatrices += \"\\n\\n{}\".format(str(confMatrix))\n\n confMatrix = confMatrix / confMatrix.sum(axis=0, keepdims=True)\n confMatrices += \"\\n\\n{}\".format(str(confMatrix))\n\n confMatrix = confMatrix / confMatrix.sum(axis=1, keepdims=True)\n confMatrices += \"\\n\\n{}\\n\".format(str(confMatrix))\n tf.reset_default_graph()\n\n\n return confMatrices\n\n\ndef build_figures(stats, nr, path = None, histogram = \"Z0_MM\", acc=False, lastEpoch=False):\n epochs = np.arange(stats[\"epochs\"])\n\n figs = []\n\n print(\"Process cost...\")\n fig0 = plt.figure()\n plt.plot(epochs, stats[\"losses\"][0], label = \"Train cost\")\n try:\n plt.plot(epochs, stats[\"val_losses\"][0], label = \"Validation cost\")\n except KeyError:\n pass\n plt.legend(loc = \"upper right\")\n plt.title(\"Structure: {}, Act.: {}, batch_size: {}, \\nepochs: {}, opt.: {}\".format(stats[\"nodes\"], stats[\"activations\"], stats[\"batch\"], stats[\"epochs\"], stats[\"optimizer\"]))\n figs += [fig0]\n\n print(\"Process accuracies...\")\n colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k']*2\n fig2 = plt.figure()\n plt.plot(epochs, stats[\"acc\"][0], label = \"Test Accuracy\")\n plt.plot(epochs, stats[\"train_acc\"][0], \"--\", label = \"Training Accuracy\")\n plt.legend(loc = \"upper left\")\n plt.title(\"Structure: {}, Act.: {}, batch_size: {}, \\nepochs: {}, opt.: {}\".format(stats[\"nodes\"], stats[\"activations\"], stats[\"batch\"], stats[\"epochs\"], stats[\"optimizer\"]))\n figs += [fig2]\n\n margin_q = np.linspace(-1, 1, 50)\n figMargin = plt.figure()\n\n if stats[\"PCA\"]:\n test_x = inc_pca.transform(data)\n else:\n test_x = data\n\n folder = \"./nn_logs{}\".format(nr)\n\n with open(folder+\"/Models/checkpoint\", \"r\") as f, tf.Session() as sess:\n new_saver = tf.train.import_meta_graph(folder+'/Models/NNModel-0.meta')\n lines = f.readlines()\n pattern = \"nn_logs.*\"\n for line in lines[1:]:\n regExp = re.search(pattern, line)\n filename = regExp.group(0)[:-1]\n regExp = re.search(\"[0-9]+$\", filename)\n e = int(regExp.group(0))\n\n new_saver.restore(sess, filename)\n graph = tf.get_default_graph()\n x = graph.get_tensor_by_name(\"x:0\")\n y = graph.get_tensor_by_name(\"y:0\")\n tr_phase = graph.get_tensor_by_name(\"trainPhase:0\")\n pred_proba = graph.get_tensor_by_name(\"Model/predProba:0\")\n pred = pred_proba.eval({x: test_x, tr_phase: 1})\n\n factor = np.array([int(i) if i else int(i)-1 for i in np.equal(np.argmax(pred, axis = 1), test_y)])\n\n margins = np.max(pred, axis = 1) * factor\n\n margin_p = [len(np.where(margins<=q)[0])/len(margins) for q in margin_q ]\n plt.plot(margin_q, margin_p, label = \"Epoch {}\".format(e))\n plt.title(\"Margin CDF\")\n plt.xlabel(\"Margin\")\n plt.ylabel(\"CDF / Fraction\")\n plt.xticks(np.linspace(-1, 1, 11))\n plt.yticks(np.linspace(0, 1, 11))\n plt.legend()\n\n tf.reset_default_graph()\n\n figs += [figMargin]\n\n figs += create_sg_bg_separation_and_ROC(stats, nr, lastEpoch)\n if histogram is not None:\n figs += create_histograms(stats, histogram, nr, acc, lastEpoch)\n\n savefig(figs, path)\n\n\ndef create_sg_bg_separation_and_ROC(stats, nr, lastEpoch):\n print(\"Process ROC...\")\n\n ROCs = []\n folder = \"./nn_logs{}\".format(nr)\n\n if stats[\"PCA\"]:\n test_x = inc_pca.transform(data)\n else:\n test_x = data\n\n with open(folder+\"/Models/checkpoint\", \"r\") as f, tf.Session() as sess:\n new_saver = tf.train.import_meta_graph(folder+'/Models/NNModel-0.meta')\n lines = f.readlines()\n pattern = \"nn_logs.*\"\n for ei, line in enumerate(lines[1:]):\n if lastEpoch and not (ei == 0 or ei+1 == len(lines)-1):\n continue\n\n regExp = re.search(pattern, line)\n filename = regExp.group(0)[:-1]\n regExp = re.search(\"[0-9]+$\", filename)\n e = int(regExp.group(0))\n\n new_saver.restore(sess, filename)\n graph = tf.get_default_graph()\n x = graph.get_tensor_by_name(\"x:0\")\n y = graph.get_tensor_by_name(\"y:0\")\n tr_phase = graph.get_tensor_by_name(\"trainPhase:0\")\n pred_proba = graph.get_tensor_by_name(\"Model/predProba:0\")\n pred = pred_proba.eval({x: test_x, tr_phase: 1})\n\n bgDist = pred[np.where(test_y==0)[0]][:,0]\n sgDist = pred[np.where(test_y==1)[0]][:,0]\n\n fig, ax = plt.subplots(nrows = 1, ncols = 2)\n\n plt.subplot(1, 2, 1)\n x = [bgDist, sgDist]\n plt.hist(x, histtype = \"step\", bins =75, label = [\"background\", \"signal\"])\n plt.title(\"Bg-Sg-Prediction Dist.\")\n plt.xlabel(\"Prediction\")\n plt.legend(loc=\"upper center\")\n\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n for i in range(nr_classes):\n fpr[i], tpr[i], _ = roc_curve(test_y, pred[:, i])\n roc_auc[i] = auc(fpr[i], tpr[i])\n\n plt.subplot(1, 2, 2)\n plt.plot(fpr[1], tpr[1], color='darkorange', lw=2, label='ROC area = %0.4f' % roc_auc[1])\n plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('ROC, Epoch: {}'.format(e))\n plt.legend(loc=\"lower right\")\n ROCs.append(fig)\n\n return ROCs\n\n\ndef create_histograms(stats, histograms, nr, acc, lastEpoch):\n print(\"Process histograms...\")\n hists = []\n curdir = os.path.abspath(os.path.curdir)\n\n sgname = \"../../../data/Val_md_MC_157677.pickle\"\n bgname = \"../../../data/Val_md_hf_107295.pickle\"\n\n if stats[\"PCA\"]:\n test_x = inc_pca.transform(data)\n else:\n test_x = data\n\n origData, test_y = get_sg_and_bg(sgname, bgname, labels=True, shuffle=True, random_state=42)\n\n nr_examples = test_x.shape[0]\n folder = \"./nn_logs{}\".format(nr)\n\n columns = ['runNumber', 'eventNumber', 'nCandidate', 'totCandidates', 'nTracks',\n 'nSPDHits', 'nLongTracks', 'Z0_MM', 'Z0_PT', 'Z0_ENDVERTEX_CHI2',\n 'Z0_ENDVERTEX_NDOF', 'y', 'isolation', 'muplus_MINIP', 'muplus_P', 'muplus_PT',\n 'muplus_PX', 'muplus_PY', 'muplus_PZ', 'muplus_TrEta', 'muplus_TrPChi2',\n 'muplus_TrPhi', 'muplus_cpt_0.1', 'muplus_cpt_0.5', 'muminus_MINIP',\n 'muminus_P', 'muminus_PT', 'muminus_PX', 'muminus_PY', 'muminus_PZ',\n 'muminus_TrEta', 'muminus_TrPChi2', 'muminus_TrPhi', 'muminus_cpt_0.1',\n 'muminus_cpt_0.5', 'nTrack', 'tracks_PT' 'tracks_PX', 'tracks_PY',\n 'tracks_PZ', 'tracks_IP', 'tracks_IPCHI2', 'tracks_eta', 'tracks_phi',\n 'tracks_charge', 'tracks_isMuon', 'weight']\n\n drawn = []\n for histogram in histograms:\n if histogram not in columns:\n print(\"!!!\\n {} does not in exist in this dataframe. IGNORED.\\n!!!\".format(histogram))\n histograms.remove(histogram)\n else:\n drawn.append(False)\n\n\n with open(folder+\"/Models/checkpoint\", \"r\") as f, tf.Session() as sess:\n new_saver = tf.train.import_meta_graph(folder+'/Models/NNModel-0.meta')\n lines = f.readlines()\n pattern = \"nn_logs.*\"\n for ei, line in enumerate(lines[1:]):\n if lastEpoch and not (ei == 0 or ei+1 == len(lines)-1):\n continue\n\n regExp = re.search(pattern, line)\n filename = regExp.group(0)[:-1]\n regExp = re.search(\"[0-9]+$\", filename)\n e = int(regExp.group(0))\n\n new_saver.restore(sess, filename)\n graph = tf.get_default_graph()\n x = graph.get_tensor_by_name(\"x:0\")\n y = graph.get_tensor_by_name(\"y:0\")\n tr_phase = graph.get_tensor_by_name(\"trainPhase:0\")\n pred_proba = graph.get_tensor_by_name(\"Model/predProba:0\")\n pred = pred_proba.eval({x: test_x, tr_phase: 1})\n pred = np.array([np.argmax(p) for p in pred])\n\n signal = np.where(pred==1)[0]\n bg = np.where(pred==0)[0]\n\n truesignal = np.where(test_y==1)[0]\n truebg = np.where(test_y==0)[0]\n\n truepos = np.logical_and(test_y==1, pred==1)\n trueneg = np.logical_and(test_y==0, pred==0)\n falsepos = np.logical_and(test_y==0, pred==1)\n falseneg = np.logical_and(test_y==1, pred==0)\n\n for h, histogram in enumerate(histograms):\n bincuts = np.array([10, 11.0, 11.5, 12.0, 13.0, 14.0, 15.0, 17.5, 20.0, 25.0, 30.0, 40.0, 60.0, 120.0])*1000 if histogram==\"Z0_MM\" else 50\n if not drawn[h]:\n x = [origData[histogram][test_y==1], origData[histogram][test_y==0]]\n fig = plt.figure()\n plt.hist(x, histtype = \"bar\", stacked = \"True\", bins=bincuts, color = [\"#0b0db0\", \"#b21000\"], label = [\"signal\", \"background\"])\n plt.xlabel(histogram)\n plt.title(\"True distribution\")\n plt.legend()\n plt.yscale(\"log\")\n hists += [[-1, fig]]\n fig = plt.figure()\n drawn[h] = True\n\n x = [origData[histogram][truepos], origData[histogram][falsepos], origData[histogram][trueneg], origData[histogram][falseneg]]\n fig = plt.figure()\n plt.hist(x, histtype = \"bar\", stacked = True, bins=bincuts, color = [\"#0b0db0\", \"#7172e1\", \"#b21000\",\"#e17b71\" ], label = [\"true signal\", \"false signal\", \"true background\", \"false background\"])\n plt.xlabel(histogram)\n plt.title(\"Epoch: {}\".format(e))\n plt.legend()\n plt.yscale(\"log\")\n hists += [[int(\"1{}{}0\".format(h, ei)), fig]]\n\n if acc:\n fig = plt.figure()\n n, edges, _ = plt.hist(x, histtype = \"bar\", stacked = False, bins=bincuts)\n count_trueSig = n[0]\n count_predSig = n[0] + n[1]\n count_trueBg = n[2]\n count_predBg = n[2] + n[3]\n count_correct = n[0] + n[2]\n count_signal = n[0] + n[3]\n count_bg = n[1] + n[2]\n count_all = n[0] + n[1] + n[2] + n[3]\n\n acc_sg = list(count_trueSig / count_signal)\n acc_bg = list(count_trueBg / count_bg)\n acc_al = list(count_correct / count_all)\n acc_sg.insert(0, acc_sg[0])\n acc_bg.insert(0, acc_bg[0])\n acc_al.insert(0, acc_al[0])\n\n fig = plt.figure()\n plt.step(edges, acc_bg, color =\"#ff8a65\", label= \"Recall: Bg\", where=\"pre\", linestyle=\"--\")\n plt.step(edges, acc_al, color =\"#7dfd6a\", label= \"Recall: Total\", where=\"pre\", linestyle=\"--\")\n plt.step(edges, acc_sg, color=\"navy\", label=\"Recall: Signal\", where=\"pre\")\n plt.xlabel(histogram)\n plt.title(\"Recall - Epoch: {}\".format(e))\n plt.legend(loc=8, fontsize = \"small\")\n plt.ylim([0,1])\n hists += [[int(\"1{}{}1\".format(h, ei)), fig]]\n\n predsg = list(count_predSig/count_all)\n predbg = list(count_predBg/count_all)\n predsg.insert(0, predsg[0])\n predbg.insert(0, predbg[0])\n\n fig = plt.figure()\n plt.step(edges, predbg, color=\"#ff8a65\", label=\"Pred. Bg\", where=\"pre\", linestyle=\"--\")\n plt.step(edges, predsg, color=\"navy\", label=\"Pred. Sg\", where=\"pre\")\n plt.xlabel(histogram)\n plt.title(\"Predicted rate - Epoch: {}\".format(e))\n plt.legend(loc=8, fontsize = \"small\")\n plt.ylim([0,1])\n hists += [[int(\"1{}{}2\".format(h, ei)), fig]]\n\n predFsg = list(n[1]/count_all)\n predFbg = list(n[3]/count_all)\n predFsg.insert(0, predFsg[0])\n predFbg.insert(0, predFbg[0])\n\n fig = plt.figure()\n plt.step(edges, predFbg, color=\"#ff8a65\", label=\"False negative\", where=\"pre\", linestyle=\"--\")\n plt.step(edges, predFsg, color=\"navy\", label=\"False positive\", where=\"pre\")\n plt.xlabel(histogram)\n plt.title(\"False rate - Epoch: {}\".format(e))\n plt.legend(loc=8, fontsize = \"small\")\n plt.ylim([0,1])\n hists += [[int(\"1{}{}3\".format(h, ei)), fig]]\n\n hists = list(np.array(sorted(hists, key=lambda x: x[0]))[:, 1])\n return hists\n\n\ndef main():\n def str2bool(inpt):\n if inpt in [\"n\", \"N\", \"False\", \"F\", \"f\", \"no\"]:\n inpt = False\n else:\n inpt = True\n return inpt\n \n parser = argparse.ArgumentParser()\n parser.add_argument(\"--nr\", type=int, default=None, help=\"stats number, default: None\")\n parser.add_argument(\"--summary\", type=str2bool, default=True, help=\"True if summary is requested, default: True\")\n parser.add_argument(\"--filename\", type=str, default=\"summary\", help=\"filename of summary, default: 'summary'\")\n parser.add_argument(\"--histogram\", type=str, default=\"Z0_MM\", help=\"variable to plot a histogram, features are seperated by a ':', default: 'Z0_MM'\")\n parser.add_argument(\"--acc\", type=str2bool, default=True, help=\"Presentation of histograms in terms of correct classification, default: True\")\n parser.add_argument(\"--last\", type=str2bool, default=True, help=\"True, if only last epoch should be shown, default: False\")\n parser.add_argument(\"--sortby\", type=str, default=\"roc_auc\", help=\"Sort value for summary. Possible are: 'max_acc' (default), 'roc_auc' and 'F1'\")\n args = parser.parse_args()\n \n curdir = os.path.abspath(os.path.curdir)\n if args.nr is None:\n stats_nr = []\n user_input = 0\n while True:\n user_input = input(\"Stats number: \")\n if user_input == \"\":\n break\n elif float(user_input) < 0:\n stats_nr = [i for i in range(100)]\n break\n try:\n user_input = int(user_input)\n stats_nr += [user_input]\n except:\n print(\"Invalid input. Insert integer!\")\n \n if args.summary:\n build_csv_summary(stats_nr, args.filename, args.sortby)\n else:\n for nr in stats_nr:\n filename = \"{}/nn_logs{}/stats{}.pickle\".format(curdir, nr, nr)\n with open(filename, \"rb\") as f:\n stats = pickle.load(f)\n build_full_output(stats, args.histogram.split(\":\"), nr, args.acc, args.last)\n \n else:\n filename = \"{}/nn_logs{}/stats{}.pickle\".format(curdir, args.nr, args.nr)\n with open(filename, \"rb\") as f:\n stats = pickle.load(f)\n build_full_output(stats, args.histogram.split(\":\"), args.nr, args.acc, args.last)\n\n\n # nmbrs=[0]\n # histograms = \"Z0_MM:nSPDHits:y\"\n # for nmbr in nmbrs:\n # filename = \"./nn_logs{}/stats{}.pickle\".format(nmbr, nmbr)\n # with open(filename, \"rb\") as f:\n # stats = pickle.load(f)\n # build_full_output(stats, histograms.split(\":\"), nmbr, True, False)\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Programme/FCLogSaverRaw.py","file_name":"FCLogSaverRaw.py","file_ext":"py","file_size_in_byte":26488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"433042318","text":"import os\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.cluster import KMeans\r\n\r\n\r\n# 파일 탐색\r\ndef search_files(path):\r\n for root, _, files in os.walk(path):\r\n for file in files:\r\n file_name = os.path.join(root, file).replace('\\\\', '/')\r\n yield file_name\r\n\r\n\r\ndef gather_data(data_dir):\r\n # 미세먼지 데이터가 존재하는 동\r\n weather_dir = f'{data_dir}/pre/weather' # 미세먼지 경로\r\n dong = [file_name.split('/')[-1][:8] for file_name in search_files(weather_dir)]\r\n dong = sorted(list(set(dong)))\r\n\r\n # weather\r\n weather_df = pd.DataFrame()\r\n for f in search_files(weather_dir):\r\n cd = f.split('/')[-1][:8]\r\n if cd in dong:\r\n temp_df = pd.read_csv(f, delimiter=',', index_col=0, parse_dates=True)\r\n temp_df['CD'] = cd\r\n weather_df = pd.concat((weather_df, temp_df))\r\n weather_df = weather_df.groupby('CD').mean() # 평균\r\n\r\n # gs\r\n gs_dir = f'{data_dir}/pre/gs'\r\n gs_df = pd.DataFrame()\r\n for f in search_files(gs_dir):\r\n cd = f.split('/')[-1][:8]\r\n if cd in dong:\r\n temp_df = pd.read_csv(f, delimiter=',', index_col=0, parse_dates=True)\r\n gs_df = pd.concat((gs_df, temp_df))\r\n gs_df['CD'] = gs_df['CD'].apply(str)\r\n gs_df = gs_df.groupby('CD').mean() # 평균\r\n\r\n # flow\r\n flow_dir = f'{data_dir}/pre/time_floating'\r\n flow_df = pd.DataFrame()\r\n for f in search_files(flow_dir):\r\n cd = f.split('/')[-1][:8]\r\n if cd in dong:\r\n temp_df = pd.read_csv(f, delimiter=',', index_col=0, parse_dates=True)\r\n temp_df['CD'] = cd\r\n flow_df = pd.concat((flow_df, temp_df))\r\n flow_df = flow_df.groupby('CD').mean() # 평균\r\n\r\n # card\r\n card_dir = f'{data_dir}/pre/card'\r\n card_df = pd.DataFrame()\r\n for f in search_files(card_dir):\r\n cd = f.split('/')[-1][:8]\r\n if cd in dong:\r\n temp_df = pd.read_csv(f, delimiter=',', index_col=0, parse_dates=True)\r\n # 평균; 업종별 카드 이용금액; 다중공선성으로 성별, 연령대는 제외\r\n temp_df = temp_df.groupby(['MCT_CAT_CD']).mean()[['USE_AMT']].reset_index()\r\n temp_df.index = temp_df['MCT_CAT_CD'].apply(str)\r\n temp_df = temp_df[['USE_AMT']].T\r\n temp_df['CD'] = cd\r\n card_df = pd.concat((card_df, temp_df), sort=True)\r\n card_df = card_df.dropna(axis='columns') # 결측치가 존재하는 컬럼 제거\r\n\r\n # 데이터 통합\r\n result = pd.merge(weather_df, gs_df, on='CD', how='inner')\r\n result = pd.merge(result, flow_df, on='CD', how='inner')\r\n result = pd.merge(result, card_df, on='CD', how='inner')\r\n\r\n # 행정동명 추가\r\n h_code_file = f'{data_dir}/GS리테일_동별 매출지수용 기준값 확인_AMT_NEW.xlsx'\r\n code = pd.read_excel(h_code_file, skiprows=1, sheet_name='참고)구_행정동코드',\r\n usecols=[3, 4], names=['CD', '행정동'])\r\n code['CD'] = code['CD'].apply(str)\r\n result = result.join(code.set_index('CD'), on='CD')\r\n\r\n # 군집분석을 위해 컬럼명 수정\r\n # result.columns = [cn.replace(' ', '').replace('&', '').replace('/', '') for cn in result.columns]\r\n for cn in result.columns:\r\n try:\r\n result = result.rename(columns={f'{cn}': f'C{int(cn)}'})\r\n except ValueError:\r\n pass\r\n\r\n # CD, 행정동\r\n cd_list = result.iloc[:, [0, -1]]\r\n result = result.drop(columns=['CD', '행정동'])\r\n\r\n # 표준화\r\n result_norm = (result - result.mean()) / result.std()\r\n\r\n return result, result_norm, cd_list\r\n\r\n\r\n# 적합한 군집의 갯수 확인\r\ndef select_cluster(input_df, save_dir):\r\n sse = []\r\n for i in range(1, len(input_df)):\r\n km = KMeans(n_clusters=i, algorithm='auto', random_state=42)\r\n km.fit(input_df)\r\n sse.append(km.inertia_)\r\n\r\n plt.plot(range(1, len(input_df)), sse, marker='o')\r\n plt.xlabel('K')\r\n plt.ylabel('SSE')\r\n\r\n # save fig\r\n plt.savefig(f'{save_dir}/n_cluster_sse.png')\r\n\r\n\r\nif __name__ == '__main__':\r\n data_directory = '../data' # data folder directory\r\n directory = f'{data_directory}/km'\r\n if not os.path.exists(directory):\r\n os.makedirs(directory)\r\n\r\n df, df_norm, _cd = gather_data(data_directory)\r\n df_norm.to_csv('test_norm.csv', header=True, index=False)\r\n select_cluster(df, directory)\r\n","sub_path":"code/pre_km.py","file_name":"pre_km.py","file_ext":"py","file_size_in_byte":4467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"339107656","text":"#!/bin/python3\n\nimport os\nimport sys\nfrom datetime import datetime\n\ndef timeConversion(s):\n AM_PM = s[-2:]\n s = s[:8]\n hh, mm, ss = [int(x) for x in s.split(':')]\n\n if AM_PM == 'PM' and hh != 12:\n return('{:02}:{:02}:{:02}'.format(hh+12, mm, ss))\n\n elif AM_PM == 'AM' and hh == 12:\n return('{:02}:{:02}:{:02}'.format(0, mm, ss))\n\n else:\n return('{:02}:{:02}:{:02}'.format(hh, mm, ss))\n\n\n\nif __name__ == '__main__':\n f = open(os.environ['OUTPUT_PATH'], 'w')\n\n s = input()\n\n result = timeConversion(s)\n\n f.write(result + '\\n')\n\n f.close()\n","sub_path":"Time_Conversion.py","file_name":"Time_Conversion.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"522195101","text":"from opengever.base.behaviors.translated_title import TranslatedTitleMixin\nfrom opengever.meeting import _\nfrom opengever.meeting.model import Member\nfrom opengever.meeting.sources import proposal_template_source\nfrom opengever.meeting.sources import sablon_template_source\nfrom opengever.meeting.wrapper import MemberWrapper\nfrom plone.dexterity.content import Container\nfrom plone.supermodel import model\nfrom z3c.relationfield.schema import RelationChoice\n\n\nclass ICommitteeContainer(model.Schema):\n \"\"\"Base schema for a the committee container.\n \"\"\"\n\n protocol_header_template = RelationChoice(\n title=_('label_protocol_header_template',\n default='Protocol header template'),\n source=sablon_template_source,\n required=True,\n )\n\n protocol_suffix_template = RelationChoice(\n title=_('label_protocol_suffix_template',\n default='Protocol suffix template'),\n source=sablon_template_source,\n required=False,\n )\n\n agenda_item_header_template = RelationChoice(\n title=_('label_agenda_item_header_template',\n default='Agenda item header template for the protocol'),\n source=sablon_template_source,\n required=False,\n )\n\n agenda_item_suffix_template = RelationChoice(\n title=_('label_agenda_item_suffix_template',\n default='Agenda item suffix template for the protocol'),\n source=sablon_template_source,\n required=False,\n )\n\n excerpt_header_template = RelationChoice(\n title=_('label_excerpt_header_template',\n default='Excerpt header template'),\n source=sablon_template_source,\n required=False,\n )\n\n excerpt_suffix_template = RelationChoice(\n title=_('label_excerpt_suffix_template',\n default='Excerpt suffix template'),\n source=sablon_template_source,\n required=False,\n )\n\n agendaitem_list_template = RelationChoice(\n title=_('label_agendaitem_list_template',\n default=u'Agendaitem list template'),\n source=sablon_template_source,\n required=False,\n )\n\n toc_template = RelationChoice(\n title=_('label_toc_template',\n default=u'Table of contents template'),\n source=sablon_template_source,\n required=False,\n )\n\n ad_hoc_template = RelationChoice(\n title=_('label_ad_hoc_template',\n default=u'Ad hoc agenda item template'),\n source=proposal_template_source,\n required=False,\n )\n\n paragraph_template = RelationChoice(\n title=_('label_paragraph_template',\n default=u'Paragraph template'),\n source=sablon_template_source,\n required=False,\n )\n\n\n_marker = object()\n\n\nclass CommitteeContainer(Container, TranslatedTitleMixin):\n \"\"\"Committee Container class, a container for all committees.\"\"\"\n\n Title = TranslatedTitleMixin.Title\n\n def _getOb(self, id_, default=_marker):\n \"\"\"We extend `_getOb` in order to change the context for member\n objects to `MemeberWrapper`. That allows us to register the\n members view as regular Browser view without any traversal hacks.\"\"\"\n\n obj = super(CommitteeContainer, self)._getOb(id_, default)\n if obj is not default:\n return obj\n\n if id_.startswith('member'):\n member_id = int(id_.split('-')[-1])\n member = Member.query.get(member_id)\n if member:\n return MemberWrapper.wrap(self, member)\n\n if default is _marker:\n raise KeyError(id_)\n return default\n\n def get_protocol_header_template(self):\n if self.protocol_header_template:\n return self.protocol_header_template.to_object\n return None\n\n def get_protocol_suffix_template(self):\n return getattr(self.protocol_suffix_template, 'to_object', None)\n\n def get_agenda_item_header_template(self):\n return getattr(self.agenda_item_header_template, 'to_object', None)\n\n def get_agenda_item_suffix_template(self):\n return getattr(self.agenda_item_suffix_template, 'to_object', None)\n\n def get_excerpt_header_template(self):\n if self.excerpt_header_template:\n return self.excerpt_header_template.to_object\n return None\n\n def get_excerpt_suffix_template(self):\n if self.excerpt_suffix_template:\n return self.excerpt_suffix_template.to_object\n return None\n\n def get_agendaitem_list_template(self):\n if self.agendaitem_list_template:\n return self.agendaitem_list_template.to_object\n\n return None\n\n def get_toc_template(self):\n if self.toc_template:\n return self.toc_template.to_object\n\n return None\n\n def get_ad_hoc_template(self):\n if self.ad_hoc_template:\n return self.ad_hoc_template.to_object\n\n return None\n\n def get_paragraph_template(self):\n if self.paragraph_template:\n return self.paragraph_template.to_object\n\n return None\n","sub_path":"opengever/meeting/committeecontainer.py","file_name":"committeecontainer.py","file_ext":"py","file_size_in_byte":5077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"13190337","text":"# -*- coding:utf-8 -*-\n__author__ = \"Yang Wei Min\"\nfrom selenium import webdriver\nimport unittest\nimport time\nimport HTMLTestRunner\n\nclass BaiDu(unittest.TestCase):\n def setUp(self):\n self.driver = webdriver.Chrome()\n self.driver.maximize_window()\n self.driver.get(\"http:www.baidu.com/\")\n time.sleep(3)\n\n def test_SearchKeyWords(self):\n self.driver.find_element_by_id(\"kw\").clear()\n time.sleep(1)\n self.driver.find_element_by_id(\"kw\").send_keys(\"Selenium\")\n self.driver.find_element_by_id(\"su\").click()\n\n def tearDown(self):\n self.driver.quit()\n\nif __name__ == \"__main__\":\n suiteTest = unittest.TestSuite()\n #将测试用例添加到测试容器中\n suiteTest.addTest(BaiDu(\"test_SearchKeyWords\"))\n filename = r\"E:\\\\Code\\\\Python\\\\Selenium_Test\\\\Results.html\"\n fp = file(filename,\"wb\")\n runner = HTMLTestRunner.HTMLTestRunner(stream=fp,title=u\"测试百度搜索关键字\",description=u\"测试结果\")\n runner.run(suiteTest)","sub_path":"Selenium_Test/Baidu.py","file_name":"Baidu.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"303423407","text":"from datetime import datetime\nfrom dateutil import rrule\n\nfrom tracpro.test import factories\nfrom tracpro.test.cases import TracProDataTest\nfrom tracpro.polls.models import Answer, Response\n\nfrom ..models import BaselineTerm\n\n\nclass BaselineTermTest(TracProDataTest):\n\n def setUp(self):\n \"\"\"\n There will be a set of results for 3 contacts, in 2 regions\n self.contact1 and self.contact2 are in self.region1\n self.contact4 is in self.region2\n \"\"\"\n super(BaselineTermTest, self).setUp()\n\n contacts = [self.contact1, self.contact2, self.contact4]\n self.start_date = datetime(2015, 1, 1, 8)\n self.end_date = datetime(2015, 1, 3, 8) # Two days of follow up results\n\n self.baselineterm = BaselineTerm.objects.create(\n org=self.unicef,\n name=\"Test BaselineTerm\",\n start_date=self.start_date,\n end_date=self.end_date,\n baseline_poll=self.poll1,\n baseline_question=self.poll1_question1,\n follow_up_poll=self.poll2,\n follow_up_question=self.poll2_question1\n )\n\n # Create a single PollRun for the Baseline Poll\n self.baseline_pollrun = factories.RegionalPollRun(\n poll=self.poll1, conducted_on=self.start_date)\n # Create a Response AKA FlowRun for each contact for Baseline\n answer_value = 10 # Baseline values will be 10, 20 and 30\n for contact in contacts:\n response = factories.Response(\n pollrun=self.baseline_pollrun,\n contact=contact,\n created_on=self.start_date,\n updated_on=self.start_date,\n status=Response.STATUS_COMPLETE)\n # Create an Answer for each contact for Baseline\n Answer.objects.create(\n response=response,\n question=self.poll1_question1,\n value=answer_value,\n submitted_on=self.start_date,\n category=u'')\n answer_value += 10 # Increase next answer's value by 10\n\n # Answers for contacts found in this dictionary\n self.contact_dict = {\n self.contact1: {\"answers\": [9, 8, 8]},\n self.contact2: {\"answers\": [15, 10, 10]},\n self.contact4: {\"answers\": [25, 20, 15]}\n }\n\n # Create a PollRun for each date from start to end dates for the Follow Up Poll\n date_iter = 0\n for follow_up_date in rrule.rrule(rrule.DAILY, dtstart=self.start_date, until=self.end_date):\n follow_up_pollrun = factories.RegionalPollRun(\n poll=self.poll2, conducted_on=follow_up_date)\n for contact in contacts:\n # Create a Response AKA FlowRun for each contact for Follow Up\n response = factories.Response(\n pollrun=follow_up_pollrun,\n contact=contact,\n created_on=follow_up_date,\n updated_on=follow_up_date,\n status=Response.STATUS_COMPLETE)\n answer = self.contact_dict[contact][\"answers\"][date_iter]\n # Create a randomized Answer for each contact for Follow Up\n Answer.objects.create(\n response=response,\n question=self.poll2_question1,\n value=answer,\n submitted_on=follow_up_date,\n category=u'')\n date_iter += 1\n\n def test_baseline_all_regions(self):\n \"\"\" Answers were 10, 20 and 30: Total should be 10 + 20 + 30 = 60 \"\"\"\n baseline_dict, dates = self.baselineterm.get_baseline(regions=None, region_selected=0)\n\n self.assertEqual(len(baseline_dict), 2) # Two regions, two sets of baseline values\n # Two answers, 10 + 20 = 30\n self.assertEqual(\n baseline_dict[self.region1.name][\"values\"],\n [30])\n # One answer, 30 = 30\n self.assertEqual(\n baseline_dict[self.region2.name][\"values\"],\n [30])\n\n def test_baseline_single_region(self):\n \"\"\" Answers were 10 and 20 for region1 \"\"\"\n baseline_dict, dates = self.baselineterm.get_baseline(regions=[self.region1], region_selected=0)\n\n self.assertEqual(len(baseline_dict), 1) # One regions, one baseline\n # Two answers sum = 10 + 20 = 30\n self.assertEqual(\n baseline_dict[self.region1.name][\"values\"],\n [30])\n\n def test_baseline_single_region_multiple_answers(self):\n \"\"\"\n Answers were 10 and 20 for region1\n Add another answer for both region contacts at a later date\n Baseline should be retrieved from all responses\n \"\"\"\n for contact in [self.contact1, self.contact2]:\n response = factories.Response(\n pollrun=self.baseline_pollrun,\n contact=contact,\n created_on=self.end_date,\n updated_on=self.end_date,\n status=Response.STATUS_COMPLETE)\n Answer.objects.create(\n response=response,\n question=self.poll1_question1,\n value=100,\n submitted_on=self.end_date,\n category=u'')\n\n baseline_dict, dates = self.baselineterm.get_baseline(regions=[self.region1], region_selected=0)\n\n self.assertEqual(len(baseline_dict), 1) # One regions, one baseline\n # Two sets of baseline answers\n # sum 1 = 10 + 20 = 30\n # sum 2 = 100 + 100 = 200\n self.assertEqual(\n baseline_dict[self.region1.name][\"values\"],\n [30, 200])\n\n def test_follow_up_all_regions(self):\n \"\"\"\n Region 1 values [9, 8] + [15, 10] = [24, 18]\n Region 2 values [25, 20]\n \"\"\"\n follow_ups, dates, all_regions = self.baselineterm.get_follow_up(regions=None, region_selected=0)\n\n self.assertEqual(len(dates), 3) # 3 dates\n self.assertEqual(len(follow_ups), 2) # 2 regions for the follow up dictionary\n self.assertEqual(len(all_regions), 2) # 2 regions in all the data\n # Sum the follow up data for two contacts in Region 1\n self.assertEqual(\n follow_ups[self.region1.name][\"values\"],\n [24, 18, 18])\n # Data for Region 2 only from one contact\n self.assertEqual(\n follow_ups[self.region2.name][\"values\"],\n [25, 20, 15])\n\n def test_follow_up_single_region(self):\n \"\"\"\n Region 1 values [9, 8] + [15, 10] = [24, 18]\n Region 2 values [25, 20]\n \"\"\"\n follow_ups, dates, all_regions = self.baselineterm.get_follow_up(regions=[self.region2], region_selected=0)\n\n self.assertEqual(len(dates), 3) # 3 dates\n self.assertEqual(len(follow_ups), 1) # One region for the follow up dictionary\n self.assertEqual(len(all_regions), 1) # 1 region\n # Data for Region 2 only from one contact\n self.assertEqual(\n follow_ups[self.region2.name][\"values\"],\n [25, 20, 15])\n","sub_path":"tracpro/baseline/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":7085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"311427165","text":"# -*- coding: utf-8 -*-\n\"\"\"\napply changes to the classification in the db.\n\ninput:\n- glottolog-data/languoids/changes.json\n\"\"\"\nfrom __future__ import unicode_literals\nimport transaction\n\nfrom sqlalchemy import desc\n\nfrom clld.util import jsonload\nfrom clld.db.models.common import Identifier, LanguageIdentifier, IdentifierType\nfrom clld.db.meta import DBSession\n\nfrom glottolog3.models import Languoid, Superseded, LanguoidLevel, LanguoidStatus\nfrom glottolog3.scripts.util import (\n recreate_treeclosure, get_args, glottolog_name, glottolog_names,\n)\n\n\nMAX_IDENTIFIER_PK = None\n\n\ndef create_identifier(identifier, l, **kw):\n global MAX_IDENTIFIER_PK\n if identifier is None:\n MAX_IDENTIFIER_PK += 1\n DBSession.add(Identifier(pk=MAX_IDENTIFIER_PK, id=str(MAX_IDENTIFIER_PK), **kw))\n pk = MAX_IDENTIFIER_PK\n else:\n pk = identifier.pk\n DBSession.add(LanguageIdentifier(language_pk=l.pk, identifier_pk=pk))\n\n\ndef main(args): # pragma: no cover\n global MAX_IDENTIFIER_PK\n\n with transaction.manager:\n MAX_IDENTIFIER_PK = DBSession.query(\n Identifier.pk).order_by(desc(Identifier.pk)).first()[0]\n\n gl_name = glottolog_name()\n gl_names = glottolog_names()\n\n languoids = {l.pk: l for l in DBSession.query(Languoid)}\n for attrs in jsonload(args.data_dir.joinpath('languoids', 'changes.json')):\n replacement = attrs.pop('replacement', None)\n hname = attrs.pop('hname', None)\n\n for name, enum in [('level', LanguoidLevel), ('status', LanguoidStatus)]:\n if name in attrs:\n attrs[name] = enum.from_string(attrs[name])\n\n l = languoids.get(attrs['pk'])\n if l:\n for k, v in attrs.items():\n setattr(l, k, v)\n #\n # We do not assign ISO codes for existing languages, because it could be\n # that the ISO code is now assigned to a family node, due to a change\n # request, e.g. see https://github.com/clld/glottolog-data/issues/40\n #\n if len(l.hid or '') == 3 and not l.iso_code:\n args.log.warn('Language with hid %s but no iso code!' % l.hid)\n else:\n l = Languoid(**attrs)\n DBSession.add(l)\n languoids[l.pk] = l\n\n if len(attrs.get('hid', '')) == 3:\n create_identifier(\n None, l, name=attrs['hid'], type=IdentifierType.iso.value)\n\n create_identifier(\n gl_names.get(l.name),\n l,\n name=l.name,\n description=gl_name.description,\n type=gl_name.type)\n\n if hname:\n l.update_jsondata(hname=hname)\n\n if replacement:\n DBSession.add(Superseded(\n languoid_pk=l.pk,\n replacement_pk=replacement,\n relation='classification update'))\n\n DBSession.flush()\n\n recreate_treeclosure()\n\n\nif __name__ == '__main__':\n main(get_args())\n","sub_path":"glottolog3/scripts/import_tree.py","file_name":"import_tree.py","file_ext":"py","file_size_in_byte":3169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"69734841","text":"import scrapy\nfrom demo.items import DmozItem\nclass DmozSpider(scrapy.spiders.Spider):\n name = \"dmoz\"\n allowed_domains = [\"dmoz.org\"]\n start_urls = [\n \"https://scrapy-chs.readthedocs.io/zh_CN/latest/intro/tutorial.html#id2\"\n ]\n\n def parse(self, response):\n i=0\n for sel in response.xpath('//ul/li'):\n item = DmozItem()\n item['title'] = sel.xpath('a/text()').extract()\n i+=1\n print(i)\n print(item[\"title\"]);\n item['link'] = sel.xpath('a/@href').extract()\n item['desc'] = sel.xpath('text()').extract()\n yield item","sub_path":"demo/demo/spiders/DemoSpider.py","file_name":"DemoSpider.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"474002181","text":"import json\nimport os\nimport sys\nfrom gooey import Gooey, GooeyParser\nfrom argparse import ArgumentParser\n\n\ndef load_json(filename):\n data = {}\n try:\n with open(filename, 'r', encoding=\"utf-8\") as infile:\n data = json.load(infile)\n except FileNotFoundError:\n print(\"file {} not found\".format(os.path.abspath(filename)))\n\n return data\n\n\ndef save_json(filename, data):\n try:\n with open(filename, 'w', encoding=\"utf-8\") as outfile:\n json.dump(data, outfile, indent=4)\n except FileNotFoundError:\n print(\"file {} not found\".format(os.path.abspath(filename)))\n\n\ndef replace_values(json_data, mapping, keys, path=''):\n for k in json_data:\n e = json_data[k]\n p = path + '.' + k\n \n # first check id we must replace the entry\n if p in keys:\n if json_data[k] in mapping:\n json_data[k] = mapping[e]\n else:\n print(\"no mapping found for {} read '{}'\".format(e, p))\n \n if type(e) is dict:\n replace_values(json_data[k], mapping, keys, p)\n \n if type(e) is list:\n for i in e:\n replace_values(i, mapping, keys, p)\n\n\ndef add_arguments(parser):\n parser.add_argument(\n '-p',\n '--project',\n action=\"store\",\n metavar=\"Project File\",\n required=True,\n widget=\"FileChooser\",\n help=\"Select the general project json-file with translation keys.\"\n )\n parser.add_argument(\n '-t',\n '--translation',\n action=\"store\",\n metavar=\"Translation File\",\n required=True,\n widget=\"FileChooser\",\n help=\"Select the translation file (json with key/value pairs).\"\n )\n parser.add_argument(\n '-k',\n '--key-list',\n action=\"store\",\n metavar=\"List of Replaceable Paths\",\n required=False,\n default=\".canvas.name\",\n help=\"Comma separated list of keys which can be translated\"\n )\n\n@Gooey(\n program_name=\"Json-Translator\",\n optional_cols=1\n)\ndef interview_arguments():\n parser = GooeyParser(\n description=\"Replace all keys from translation file find in given json-path.\"\n )\n\n pg = parser.add_argument_group()\n add_arguments(pg)\n return parser.parse_args()\n\n\ndef parse_arguments():\n parser = ArgumentParser(\n description='Replace all keys from translation file find in given json-path.')\n\n add_arguments(parser)\n return parser.parse_args()\n\n\ndef main():\n\n if 1 < len(sys.argv) and \"--nogui\" == sys.argv[1]:\n args = parse_arguments()\n else:\n args = interview_arguments()\n\n project_file = args.project\n project_name = os.path.splitext(os.path.basename(project_file))[0]\n\n translation_file = args.translation\n translation_name = os.path.splitext(os.path.basename(translation_file))[0]\n\n basepath = os.path.dirname(project_file)\n result = basepath + \"/\" + project_name + \"-\" + translation_name + \".json\"\n\n key_list = args.key_list.split(',')\n\n mapping = load_json(translation_file)\n data = load_json(project_file)\n\n print(\"load mapping {} with {} entries\".format(translation_file, len(mapping)))\n print(\"key list contains {} entries\".format(len(key_list)))\n replace_values(data, mapping, key_list)\n\n save_json(result, data)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"translation.py","file_name":"translation.py","file_ext":"py","file_size_in_byte":3405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"494200018","text":"import argparse\nimport csv\nimport json\nimport os\nimport re\nimport zipfile\nfrom collections import OrderedDict\nfrom configparser import ConfigParser\nfrom functools import lru_cache\n\nfrom PIL import Image\n\nfrom scrappers.apps.config.http.engine import RequestsManager\nfrom scrappers.apps.config.logs import default\nfrom scrappers.apps.images.mixins import ScrapperMixins\n\n\nclass ImageDownloader(ScrapperMixins, RequestsManager):\n \"\"\"This class is the base class to send requests\n to the SawFirst website.\n\n Description\n -----------\n\n It creates a requests and scraps all the images from a given page then\n downloads the images on a local or cloud storage.\n\n Parameters\n ----------\n\n celebrity_name: accepts a celebrity name to use in order to use\n either in a file or some kind of request.\n\n div_id: allows you to change the start searching point in\n order to scrap the different images of the page.\n\n headers: add additional headers to the request\n \"\"\"\n app_name = 'image_downloader'\n memory = OrderedDict(csv=[], json=[], html=[])\n\n def __init__(self, current_file, url=None, \n html_path=None, download_dir=None):\n self.current_dir = os.path.dirname(current_file)\n self.logger = default(\n self.__class__.__name__, \n logfile_name=os.path.join(self.current_dir, 'scrappers.log')\n )\n self.url = url\n self.html_path = html_path\n\n path, _, files = list(os.walk(os.path.dirname(current_file)))[0]\n\n self.memory.update({'path': path})\n for item in files:\n self._sort_files(item)\n\n state = self._construct_download_dir(download_dir=download_dir)\n if not state:\n raise FileExistsError('Could not create or find a download directory for your application')\n\n def _sort_files(self, item, base_path=None):\n if '.':\n _, extension = item.split('.', 1)\n try:\n self.memory[extension].append(item)\n except KeyError:\n pass\n else:\n return False\n\n @lru_cache(maxsize=1)\n def load_images(self):\n loaded_images = []\n base, _, images = list(os.walk(self._scrappers_dir))[0]\n for image in images:\n full_path = os.path.join(base, image)\n if full_path.endswith('jpg'):\n loaded_images.append(\n (\n full_path,\n Image.open(full_path)\n )\n )\n return loaded_images\n\n\n @lru_cache(maxsize=1)\n def load(self, filename, run_request=False, limit=0):\n extension, _, full_path = self.lookup(filename, just_path=False)\n with open(full_path, 'r') as f:\n if extension == 'csv':\n reader = csv.reader(f)\n self.urls = list(reader)\n self.urls.pop(0)\n self.urls = [url[1] for url in self.urls]\n\n if extension == 'json':\n data = json.load(f)\n for item in data['gallery']:\n self.urls.append(item['link'])\n\n if run_request:\n self._download_images(limit=limit)\n return self.urls\n\n def save_gallery(self, filename, depth=3, f=None):\n \"\"\"\n Save the links and their parents in an HTML file\n \"\"\" \n sample_tag = self.raw_tags[0]\n parents = sample_tag.find_parents()\n \n if f is not None:\n parent = None\n for item in parents:\n parent = item.parent()[0]\n if 'class' in parent.attrs or 'id' in parent.attrs:\n for _, values in parent.attrs.items():\n if f in values:\n parent = item\n break\n else:\n parent = parents[depth]\n \n with open(os.path.join(self.current_dir, filename), 'w') as f:\n f.write(str(parent))\n\n def save_links(self, filename=None, file_type='csv',\n headers=[], with_index=False):\n if filename is not None:\n filename = f'{filename}.{file_type}'\n\n full_path = os.path.join(self.current_dir, filename) \n\n with open(full_path, 'w', newline='') as f:\n if file_type == 'csv':\n writer = csv.writer(f)\n if with_index:\n if not 'index' in headers:\n headers.insert(0, 'index')\n new_urls = [[index, url]\n for index, url in enumerate(self.urls)]\n else:\n new_urls = [[url] for url in self.urls]\n if headers:\n new_urls.insert(0, headers)\n writer.writerows(new_urls)\n print(f'Saved {len(self.urls)} images in {full_path}')\n\n if file_type == 'json':\n base = {\n 'gallery': []\n }\n for index, link in enumerate(self.urls):\n base['gallery'].append(\n {'index': index, 'link': link}\n )\n json.dump(base, f, indent=4)\n\n def _construct_download_dir(self, download_dir=None, using=None):\n if download_dir is None:\n path = os.path.join(\n os.environ.get('HOMEDRIVE'),\n os.environ.get('HOMEPATH')\n )\n images_dir = os.path.join(path, 'Pictures')\n self.logger.info(f'Created download directory in {path}')\n self.images_dir = images_dir\n return True\n else:\n if using is not None:\n pass\n else:\n self.images_dir = download_dir\n return True\n return False\n\n def lookup(self, filename, just_path=False):\n \"\"\"\n Result\n ------\n\n (key, filename.ext, /path/to/file.ext)\n \"\"\"\n if '.' not in filename:\n raise ValueError('Please specify a file with an extension')\n\n found = False\n\n for key, values in self.memory.items():\n if filename in values:\n found = True\n break\n \n if found:\n full_path = os.path.join(self.memory['path'], values[values.index(filename)])\n self.html_path = full_path\n if just_path:\n return full_path\n return (key, values[values.index(filename)], full_path)\n else:\n return found\n\n def _download_images(self, limit=0):\n # responses = self.get(self.urls)\n responses = self.threaded_get(*self.urls)\n path_exists = os.path.exists(self._scrappers_dir)\n if not path_exists:\n os.mkdir(self._scrappers_dir)\n\n for index, response in enumerate(responses, start=1):\n if limit != 0:\n if index == limit:\n break\n if response.status_code == 200:\n new_name = self.create_name(index)\n full_path = os.path.join(self._scrappers_dir, f'{new_name}.jpg')\n with open(full_path, 'wb') as f:\n for data in response.iter_content(chunk_size=1024):\n if not data:\n break\n f.write(data)\n self.saved_images.append(full_path)\n # self.saved_images.append(\n # Image.load(os.path.join(self._scrappers_dir, name))\n # )\n\n self.logger.warning(f'downloaded {len(self.urls)} images to {self._scrappers_dir}')\n \n def build(self, f, limit=0, regex=None, replace_with=None, pop_value:int=None, zip_files=False):\n if self.html_path is not None:\n soup = self.lazy_request(path=self.html_path)\n \n if self.url is not None:\n soup = self.get_html(*(self.url))\n\n if self.html_path is None and self.url is None:\n raise ValueError('You need to provide either a URL or an HTML path to use for parsing the images. You can also use the .lookup() method.')\n \n try:\n images = soup.find_all('img')\n except Exception:\n raise\n else:\n for image in images:\n url = image['src']\n if f in url and url.endswith('jpg'):\n self.raw_tags.append(image)\n if regex:\n if replace_with is None:\n replace_with = '.jpg'\n self.urls.append(\n self.replace_with_regex(url, regex, replace_with)\n )\n else:\n self.urls.append(url)\n if pop_value is not None:\n self.urls.pop(pop_value)\n print(f'Found {len(self.urls)} images')\n # self._download_images(limit=limit)\n\n if zip_files is not None:\n images = self.load_images()\n with zipfile.ZipFile(os.path.join(self._scrappers_dir, 'images.zip'), mode='w') as z:\n for image in images:\n with open(image[0], 'rb') as img:\n z.write(img.read())\n","sub_path":"apps/images/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":9400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"631561099","text":"#!/usr/bin/env python3\n\nimport os\nimport requests\nfrom datetime import datetime as dt\n\nfrom assistant.utils import thread\n\nAPIKEY_WEATHER = os.environ[\"APIKEY_WEATHER\"]\n\n\nINTERVALS = {\n \"north east\": (22.5, 67.5),\n \"east\": (67.5, 112.5),\n \"south east\": (112.5, 157.5),\n \"south\": (157.5, 202.5),\n \"south west\": (202.5, 247.5),\n \"west\": (247.5, 292.5),\n \"north west\": (292.5, 337.5),\n}\n\n\ndef direction(degree):\n \"\"\"Derive side of the world from a degree.\"\"\"\n\n def belongs(n, interval):\n return True if interval[0] < n <= interval[1] else False\n\n if not belongs(degree, (0, 360)):\n raise ValueError(f\"input degree {degree} does not belong [0, 360]\")\n\n for direction in INTERVALS:\n return direction if belongs(degree, INTERVALS[direction]) else \"north\"\n\n\nclass WeatherRecord(object):\n def __init__(self, r):\n statements = [\n \"self.temp = round(r['main']['temp'])\",\n \"self.temp_max = round(r['main']['temp_max'])\",\n \"self.temp_min = round(r['main']['temp_min'])\",\n \"self.pressure = int(r['main']['pressure'] * 0.75)\",\n \"self.humidity = r['main']['humidity']\",\n \"self.sunrise = None\",\n \"self.sunset = None\",\n \"self.conditions = [x['description'] for x in r['weather']]\",\n \"self.wind_deg = r['wind']['deg']\",\n \"self.wind_dir = direction(self.wind_deg)\",\n \"self.wind_speed = r['wind']['speed']\",\n \"self.dt = dt.utcfromtimestamp(r['dt'])\",\n ]\n\n for statement in statements:\n try:\n exec(statement)\n except Exception:\n variable = statement.split(\" = \")[0]\n exec(f\"{variable} = None\")\n # traceback.print_exc()\n\n\nclass Weather(WeatherRecord):\n def __init__(self, city=None, coordinates=None, zip=None):\n arguments = {}\n if city:\n arguments[\"q\"] = city\n self.city = city\n if coordinates:\n self.lan, self.lon = coordinates\n arguments[\"lat\"], arguments[\"lon\"] = coordinates\n if zip:\n self.zip = zip\n arguments[\"zip\"] = zip\n\n self.params = \"&\".join(f\"{key}={arguments[key]}\" for key in arguments)\n self.params += f\"&units=metric&APPID={APIKEY_WEATHER}\"\n thread((self.__current, self.__forecast), wait_to_finish=True)\n\n def __current(self):\n record = requests.get(\n f\"http://api.openweathermap.org/data/2.5/weather?{self.params}\"\n ).json()\n WeatherRecord.__init__(self, record)\n\n def __forecast(self):\n r = requests.get(\n f\"http://api.openweathermap.org/data/2.5/forecast?{self.params}\"\n ).json()\n records = r[\"list\"]\n r1 = WeatherRecord(records[0])\n self.forecasts = [[r1], [], [], [], [], []]\n count = 0\n for record in records[1:]:\n current = dt.utcfromtimestamp(record[\"dt\"])\n previous = self.forecasts[count][-1].dt\n if current.day != previous.day:\n count += 1\n self.forecasts[count].append(WeatherRecord(record))\n\n def __str__(self):\n conditions = \", \".join(self.conditions)\n return f\"\"\"\nTemperature:\n current {self.temp} °C\n max {self.temp_max} °C\n min {self.temp_min} °C\n\nConditions: {conditions}\n\nWind: {self.wind_speed} m/s, {self.wind_dir}\n\nPressure: {self.pressure} mmHg\n\nHumidity: {self.humidity} %\n\nSunrise: {self.sunrise}\n\nSunset: {self.sunset}\n\"\"\"\n\n def summary(self):\n if self.temp_max - self.temp_min >= 3:\n summary = f\"\"\"\n You can observe {self.conditions[0]} in {self.city} right now,\n the temperature varies between {self.temp_min} and {self.temp_max}\n and is currently {self.temp} degrees\"\"\"\n else:\n summary = f\"\"\"\n You can observe {self.conditions[0]} in {self.city} right now,\n the temperature is currently {self.temp} degrees\"\"\"\n return summary\n\n def tempSummary(self):\n return f\"The current temperature in {self.city} is {self.temp} degrees\"\n\n def fullSummary(self):\n if self.temp_max - self.temp_min >= 3:\n opts = f\"\"\"\n Current temperature in {self.city} is {self.temp} degrees,\n you can observe {self.conditions[0]}.\n The {self.wind_dir}ern wind's speed is {self.wind_speed}\n meters per second. Humidity is {self.humidity} %\"\"\"\n else:\n opts = f\"\"\"\n The temperature in {self.city} varies between\n {self.temp_min} and {self.temp_max} today and\n is currently {self.temp} degrees.\n You can observe {self.conditions[0]}.\n The {self.wind_dir}ern wind's speed is {self.wind_speed}\n meters per second. Humidity is {self.humidity} %\"\"\"\n return opts\n\n def max(self, days_ahead=0):\n return max([temp.temp for temp in self.forecasts[days_ahead]])\n\n def min(self, days_ahead=0, daily=True):\n if daily:\n return min([temp.temp for temp in self.forecasts[days_ahead]])\n else:\n return min(\n [temp.temp for temp in self.forecasts[days_ahead] if temp]\n )\n\n def aver(self, days_ahead=0):\n res = [temp.temp for temp in self.forecasts[days_ahead]]\n return sum(res) / len(res)\n\n def forecast(self, days_ahead=0, hour=12):\n self.forecasts[days_ahead][int(hour / 3)]\n","sub_path":"assistant/modules/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":5655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"451255285","text":"\"\"\"In this file, we test to ensure that the output of\nrun_code is as expected. The tests we do here\nare almost identical to those for check_syntax,\nfound in test_check_syntax.py\n\nWe also test to ensure that run_code does not accidently\nchange any existing error handling settings.\n\n\"\"\"\n\nimport friendly_traceback as friendly\n\n\ndef test_run_code():\n # set-up\n bad_code_syntax = \"True = 1\"\n bad_code_exec = \"a = b\" # Not a syntax error, but a NameError\n good_code = \"c = 1\"\n\n friendly.set_stream(\"capture\")\n original_level = friendly.get_level()\n installed = friendly.is_installed()\n # ----- end of set-up\n\n # When a SyntaxError is raised, run_code returns False\n\n assert not friendly.run_code(source=bad_code_syntax)\n result = friendly.get_output() # content is flushed\n assert \"Python exception\" in result\n assert \"SyntaxError\" in result\n\n assert not friendly.get_output() # confirm that content was flushed\n\n assert not friendly.run_code(source=bad_code_exec)\n result = friendly.get_output()\n assert \"Python exception\" in result\n assert \"NameError\" in result\n\n assert friendly.run_code(source=good_code)\n assert not friendly.get_output() # no new exceptions recorded\n\n try:\n exec(bad_code_syntax, {})\n except Exception:\n assert not friendly.get_output()\n\n # When friendly-traceback is not installed, a call to run_code\n # will end with level set to 0, which corresponds to normal Python\n # tracebacks\n friendly.uninstall()\n friendly.run_code(source=bad_code_syntax)\n assert friendly.get_level() == 0\n friendly.run_code(source=bad_code_syntax, level=4)\n assert friendly.get_level() == 0\n\n # When friendly-traceback is \"installed\", a call to run_code\n # leaves its level unchanged.\n friendly.install()\n\n friendly.set_level(3)\n friendly.run_code(source=bad_code_syntax)\n assert friendly.get_level() == 3\n friendly.run_code(source=bad_code_syntax, level=4)\n assert friendly.get_level() == 3\n\n # Clean up and restore for other tests\n friendly.get_output()\n friendly.set_stream(None)\n if installed:\n friendly.uninstall()\n friendly.set_level(original_level)\n\n\nif __name__ == '__main__':\n test_run_code()\n print(\"Success!\")\n","sub_path":"tests/unit/test_run_code.py","file_name":"test_run_code.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"412747293","text":"import math\nimport numpy as np\n\nclass Persona:\n def __init__(self,i, posx, posy, objx, objy, v, t_contagiado, fijo):\n # movement speed\n self.v=v\n # target position\n self.objx=objx\n self.objy=objy\n #ID and name\n self.indice=i\n self.nombre=\"Persona \"+str(i)\n #State: Susceptible, Infected or Retired\n self.infectado = False\n self.suceptible = True\n self.retirado = False\n #Current position\n self.posx = posx\n self.posy=posy\n #is it fixed (in quarantine)?\n self.fijo = fijo\n\n # displacement per iteration\n if self.fijo:\n\n self.deltax = 0\n self.deltay = 0\n else:\n self.deltax = (self.objx - self.posx) / self.v\n self.deltay = (self.objy - self.posy) / self.v\n #time in which the person was infected\n self.i_contagio=-1\n #time that the infection lasts, recover time\n self.t_contagiado = t_contagiado\n\n\n def __str__(self):\n return self.nombre+\" en posicin \"+str(self.posx)+\", \"+str(self.posy)\n\n def infectar(self,i):\n #infect\n self.infectado=True\n self.suceptible=False\n self.retirado = False\n self.i_contagio=i\n\n def retirar(self):\n #heal\n self.retirado=True\n self.suceptible=False\n self.infectado=False\n\n def set_objetivo(self,objx,objy):\n #this function is used to create a new target position\n self.objx=objx\n self.objy=objy\n if self.fijo:\n self.deltax = 0\n self.deltay=0\n else:\n self.deltax = (self.objx - self.posx) / self.v\n self.deltay = (self.objy - self.posy) / self.v\n print(\"Nuevo OBJ \", self.objx,self.objy,\" \",self.indice)\n\n def check_contagio(self,i):\n #this function is used to heal the person if the established infection time has passed\n if self.i_contagio>-1:\n if i-self.i_contagio>self.t_contagiado:\n self.retirar()\n\n\n def update_pos(self, n_posx, n_posy):\n #this funcion animates the movement\n if(n_posx==0 and n_posy==0):\n self.posx=self.posx+self.deltax\n self.posy=self.posy+self.deltay\n else:\n self.posx=n_posx\n self.posy=n_posy\n\n if abs(self.posx-self.objx)<3 and abs(self.posy-self.objy)<3:\n self.set_objetivo(np.random.random()*100, np.random.random()*100)\n if self.posx>100:\n self.posx=100\n if self.posy>100:\n self.posy=100\n if self.posx<0:\n self.posx=0\n if self.posy<0:\n self.posy=0\n\n def get_color(self):\n if self.infectado:\n return 'red'\n if self.suceptible:\n return 'blue'\n if self.retirado:\n return 'gray'\n\n def get_pos(self):\n return (self.posx,self.posy)\n\n def get_dist(self,x,y):\n #this funcion calculates the distance between this person an another.\n return math.sqrt(abs((self.posx-x)**2+(self.posy-y**2)))\n \n","sub_path":"persona.py","file_name":"persona.py","file_ext":"py","file_size_in_byte":3127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"461985178","text":"import os\nimport re\nimport subprocess\nimport tarfile\nfrom datetime import datetime\nfrom itertools import chain\nfrom tempfile import TemporaryDirectory\n\nfrom pkgcore.ebuild.misc import sort_keywords\nfrom pkgcore.ebuild.repository import UnconfiguredTree\nfrom pkgcore.exceptions import PkgcoreException\nfrom snakeoil.demandload import demand_compile_regexp\nfrom snakeoil.klass import jit_attr\nfrom snakeoil.osutils import pjoin\nfrom snakeoil.strings import pluralism as _pl\n\nfrom .. import base, git, results, sources\nfrom ..log import logger\nfrom . import ExplicitlyEnabledCheck, GentooRepoCheck\n\ndemand_compile_regexp(\n 'ebuild_copyright_regex',\n r'^# Copyright (\\d\\d\\d\\d(-\\d\\d\\d\\d)?) .+')\n\n\nclass GitCommitsRepoSource(sources.RepoSource):\n \"\"\"Repository source for locally changed packages in git history.\n\n Parses git log history to determine packages with changes that\n haven't been pushed upstream yet.\n \"\"\"\n\n required_addons = (git.GitAddon,)\n\n def __init__(self, *args, git_addon):\n super().__init__(*args)\n self._repo = git_addon.commits_repo(git.GitChangedRepo)\n\n\nclass GitCommitsSource(sources.Source):\n \"\"\"Source for local commits in git history.\n\n Parses git log history to determine commits that haven't been pushed\n upstream yet.\n \"\"\"\n\n feed_type = base.commit_scope\n required_addons = (git.GitAddon,)\n\n def __init__(self, *args, git_addon):\n super().__init__(*args, source=git_addon.commits())\n\n\nclass OutdatedCopyright(results.VersionResult, results.Warning):\n \"\"\"Changed ebuild with outdated copyright.\"\"\"\n\n def __init__(self, year, line, **kwargs):\n super().__init__(**kwargs)\n self.year = year\n self.line = line\n\n @property\n def desc(self):\n return f'outdated copyright year {self.year!r}: {self.line!r}'\n\n\nclass BadCommitSummary(results.PackageResult, results.Warning):\n \"\"\"Local package commit with poorly formatted or unmatching commit summary.\n\n Git commit messages for packages should be formatted in the standardized\n fashion described in the devmanual [#]_. Specifically, a\n ``${CATEGORY}/${PN}:`` or ``${CATEGORY}/${P}:`` prefix should be used in\n the summary relating to the modified package.\n\n .. [#] https://devmanual.gentoo.org/ebuild-maintenance/git/#git-commit-message-format\n \"\"\"\n\n def __init__(self, error, summary, commit, **kwargs):\n super().__init__(**kwargs)\n self.error = error\n self.summary = summary\n self.commit = commit\n\n @property\n def desc(self):\n return f'commit {self.commit}, {self.error}: {self.summary!r}'\n\n\nclass DirectStableKeywords(results.VersionResult, results.Error):\n \"\"\"Newly committed ebuild with stable keywords.\"\"\"\n\n def __init__(self, keywords, **kwargs):\n super().__init__(**kwargs)\n self.keywords = tuple(keywords)\n\n @property\n def desc(self):\n return f'directly committed with stable keyword%s: [ %s ]' % (\n _pl(self.keywords), ', '.join(self.keywords))\n\n\nclass _DroppedKeywords(results.PackageResult):\n \"\"\"Unstable keywords dropped from package.\"\"\"\n\n _status = None\n\n def __init__(self, keywords, commit, **kwargs):\n super().__init__(**kwargs)\n self.keywords = tuple(keywords)\n self.commit = commit\n\n @property\n def desc(self):\n keywords = ', '.join(self.keywords)\n return (\n f'commit {self.commit} (or later) dropped {self._status} '\n f'keyword{_pl(self.keywords)}: [ {keywords} ]'\n )\n\n\nclass DroppedUnstableKeywords(_DroppedKeywords, results.Warning):\n \"\"\"Unstable keywords dropped from package.\"\"\"\n\n _status = 'unstable'\n\n\nclass DroppedStableKeywords(_DroppedKeywords, results.Error):\n \"\"\"Stable keywords dropped from package.\"\"\"\n\n _status = 'stable'\n\n\nclass DirectNoMaintainer(results.PackageResult, results.Error):\n \"\"\"Directly added, new package with no specified maintainer.\"\"\"\n\n @property\n def desc(self):\n return 'directly committed with no package maintainer'\n\n\nclass _RemovalRepo(UnconfiguredTree):\n \"\"\"Repository of removed packages stored in a temporary directory.\"\"\"\n\n def __init__(self, repo):\n self.__parent_repo = repo\n self.__tmpdir = TemporaryDirectory()\n self.__created = False\n repo_dir = self.__tmpdir.name\n\n # set up some basic repo files so pkgcore doesn't complain\n os.makedirs(pjoin(repo_dir, 'metadata'))\n with open(pjoin(repo_dir, 'metadata', 'layout.conf'), 'w') as f:\n f.write('masters =\\n')\n os.makedirs(pjoin(repo_dir, 'profiles'))\n with open(pjoin(repo_dir, 'profiles', 'repo_name'), 'w') as f:\n f.write('old-repo\\n')\n super().__init__(repo_dir)\n\n def __call__(self, pkgs):\n \"\"\"Update the repo with a given sequence of packages.\"\"\"\n self._populate(pkgs, eclasses=(not self.__created))\n if self.__created:\n # notify the repo object that new pkgs were added\n for pkg in pkgs:\n self.notify_add_package(pkg)\n self.__created = True\n return self\n\n def _populate(self, pkgs, eclasses=False):\n \"\"\"Populate the repo with a given sequence of historical packages.\"\"\"\n pkg = pkgs[0]\n commit = pkgs[0].commit\n\n paths = [pjoin(pkg.category, pkg.package)]\n if eclasses:\n paths.append('eclass')\n git_cmd = f\"git archive {commit}~1 {' '.join(paths)}\"\n\n old_files = subprocess.Popen(\n git_cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n cwd=self.__parent_repo.location)\n with tarfile.open(mode='r|', fileobj=old_files.stdout) as tar:\n tar.extractall(path=self.location)\n if old_files.poll():\n error = old_files.stderr.read().decode().strip()\n raise PkgcoreException(error)\n\n def __del__(self):\n self.__tmpdir.cleanup()\n\n\nclass GitPkgCommitsCheck(GentooRepoCheck):\n \"\"\"Check unpushed git package commits for various issues.\"\"\"\n\n scope = base.package_scope\n _source = (sources.PackageRepoSource, (), (('source', GitCommitsRepoSource),))\n required_addons = (git.GitAddon,)\n known_results = frozenset([\n DirectStableKeywords, DirectNoMaintainer, BadCommitSummary,\n OutdatedCopyright, DroppedStableKeywords, DroppedUnstableKeywords,\n ])\n\n def __init__(self, *args, git_addon):\n super().__init__(*args)\n self.today = datetime.today()\n self.repo = self.options.target_repo\n self.valid_arches = self.options.target_repo.known_arches\n self._git_addon = git_addon\n\n @jit_attr\n def removal_repo(self):\n \"\"\"Create a repository of packages removed from git.\"\"\"\n return _RemovalRepo(self.repo)\n\n @jit_attr\n def added_repo(self):\n \"\"\"Create/load cached repo of packages added to git.\"\"\"\n return self._git_addon.cached_repo(git.GitAddedRepo)\n\n def removal_checks(self, removed):\n \"\"\"Check for issues due to package removals.\"\"\"\n pkg = removed[0]\n commit = removed[0].commit\n\n try:\n removal_repo = self.removal_repo(removed)\n except PkgcoreException as e:\n logger.warning('skipping git removal checks: %s', e)\n return\n\n old_keywords = set(chain.from_iterable(\n pkg.keywords for pkg in removal_repo.match(pkg.unversioned_atom)))\n new_keywords = set(chain.from_iterable(\n pkg.keywords for pkg in self.repo.match(pkg.unversioned_atom)))\n\n dropped_keywords = old_keywords - new_keywords\n dropped_stable_keywords = dropped_keywords & self.valid_arches\n dropped_unstable_keywords = set()\n for keyword in (x for x in dropped_keywords if x[0] == '~'):\n arch = keyword[1:]\n if arch in self.valid_arches and arch not in new_keywords:\n dropped_unstable_keywords.add(keyword)\n\n if dropped_stable_keywords:\n yield DroppedStableKeywords(\n sort_keywords(dropped_stable_keywords), commit, pkg=pkg)\n if dropped_unstable_keywords:\n yield DroppedUnstableKeywords(\n sort_keywords(dropped_unstable_keywords), commit, pkg=pkg)\n\n def feed(self, pkgset):\n removed = [pkg for pkg in pkgset if pkg.status == 'D']\n if removed:\n yield from self.removal_checks(removed)\n\n for git_pkg in pkgset:\n # check git commit summary formatting\n try:\n summary = git_pkg.message[0]\n except IndexError:\n summary = ''\n summary_prefix_re = rf'^({git_pkg.key}|{git_pkg.cpvstr}): '\n if not re.match(summary_prefix_re, summary):\n error = 'summary missing matching package prefix'\n yield BadCommitSummary(error, summary, git_pkg.commit, pkg=git_pkg)\n\n try:\n pkg = self.repo.match(git_pkg.versioned_atom)[0]\n except IndexError:\n # weird situation where an ebuild was locally committed and then removed\n return\n\n # check copyright on new/modified ebuilds\n try:\n line = next(pkg.ebuild.text_fileobj())\n except StopIteration:\n # empty ebuild, should be caught by other checks\n return\n copyright = ebuild_copyright_regex.match(line)\n if copyright:\n year = copyright.group(1).split('-')[-1]\n if int(year) < self.today.year:\n yield OutdatedCopyright(year, line.strip('\\n'), pkg=pkg)\n\n # checks for newly added ebuilds\n if git_pkg.status == 'A':\n # check for stable keywords\n stable_keywords = sorted(x for x in pkg.keywords if x[0] not in '~-')\n if stable_keywords:\n yield DirectStableKeywords(stable_keywords, pkg=pkg)\n\n # pkg was just added to the tree\n newly_added = not self.added_repo.match(git_pkg.unversioned_atom)\n\n # check for no maintainers\n if not pkg.maintainers and newly_added:\n yield DirectNoMaintainer(pkg=pkg)\n\n\nclass MissingSignOff(results.CommitResult, results.Error):\n \"\"\"Local commit with missing sign offs.\n\n Sign offs are required for commits as specified by GLEP 76 [#]_.\n\n .. [#] https://www.gentoo.org/glep/glep-0076.html#certificate-of-origin\n \"\"\"\n\n def __init__(self, missing_sign_offs, **kwargs):\n super().__init__(**kwargs)\n self.missing_sign_offs = missing_sign_offs\n\n @property\n def desc(self):\n sign_offs = ', '.join(self.missing_sign_offs)\n return (\n f'commit {self.commit}, '\n f'missing sign-off{_pl(self.missing_sign_offs)}: {sign_offs}'\n )\n\n\nclass GitCommitsCheck(GentooRepoCheck, ExplicitlyEnabledCheck):\n \"\"\"Check unpushed git commits for various issues.\"\"\"\n\n scope = base.commit_scope\n _source = GitCommitsSource\n known_results = frozenset([MissingSignOff])\n\n def feed(self, commit):\n # check for missing git sign offs\n sign_offs = {\n line[15:].strip() for line in commit.message\n if line.startswith('Signed-off-by: ')}\n required_sign_offs = {commit.author, commit.committer}\n missing_sign_offs = required_sign_offs - sign_offs\n if missing_sign_offs:\n yield MissingSignOff(tuple(sorted(missing_sign_offs)), commit=commit)\n","sub_path":"src/pkgcheck/checks/git.py","file_name":"git.py","file_ext":"py","file_size_in_byte":11562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"652171023","text":"from sqlalchemy import *\nfrom sqlalchemy.orm import *\nfrom sqlalchemy.ext.declarative import declarative_base\nimport json\nimport re\n\nBase = declarative_base()\n\nclass UserDeviceMap(Base):\n\n __tablename__ = 'user_device_map'\n\n id = Column(Integer, primary_key=True)\n device_id = Column(String)\n user_id = Column(String)\n first_active = Column(DATETIME)\n last_active = Column(DATETIME)\n\n## UserDevicePair = (user_id, device_id)\n# def send2DB(UserDevicePair, engine):\n# # Initialize connect:\n# # Create DBSession object:\n# DBSession = sessionmaker(bind=engine)\n# session = DBSession()\n# new_mapping = UserDeviceMap(user_id=UserDevicePair[0], device_id=UserDevicePair[1],\n# first_active=UserDevicePair[2], last_active=UserDevicePair[3])\n# session.add(new_mapping)\n# session.commit()\n# session.close()\n ##add one week to the record's send_at attribute\n\ndef main():\n valid_id = re.compile('[0-9A-Za-z/-]{36,36}|[0-9a-z]{12,16}')\n\n with open('UserDeviceMap.json', 'r', encoding='utf-8') as f:\n reader = f.readlines()\n f.close()\n mapSet = json.loads(reader[0])\n\n engine = create_engine('mysql+pymysql://HSDBADMIN:NestiaHSPWD@hsdb.cd29ypfepkmi.ap-southeast-1.rds.amazonaws.com:3306/notification?charset=utf8mb4')\n DBSession = sessionmaker(bind=engine)\n session = DBSession()\n for device_id in mapSet.keys():\n if valid_id.search(device_id) or device_id == 'None':\n user_id = ','.join(mapSet[device_id][0])\n UserDevicePair = (user_id, device_id, mapSet[device_id][1], mapSet[device_id][2])\n new_mapping = UserDeviceMap(user_id=UserDevicePair[0], device_id=UserDevicePair[1],\n first_active=UserDevicePair[2], last_active=UserDevicePair[3])\n session.add(new_mapping)\n session.commit()\n print('Sending successful')\n session.close()\n\nmain()\n\n","sub_path":"src/device_user_pair/src/send2DB.py","file_name":"send2DB.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"181078482","text":"\"\"\"\nfuocore.daemon.handlers.helper\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n良好的用文字展示一个对象\n\n展示的时候需要注意以下几点:\n1. 让 awk、grep 等 shell 工具容易处理\n\nTODO: 让代码长得更好看\n\"\"\"\n\n\ndef show_song(song, brief=False):\n artists = song.artists or []\n artists_name = ','.join([artist.name for artist in artists])\n if song.album is not None:\n album_name = song.album.name\n album_uri = str(song.album)\n else:\n album_name = 'Unknown'\n album_uri = ''\n if brief:\n s = '{song}\\t#{title}-{artists_name}-{album_name}'.format(\n song=song,\n title=song.title,\n artists_name=artists_name,\n album_name=album_name)\n return s\n artists_uri = ','.join(str(artist) for artist in artists)\n msgs = (\n 'provider {}'.format(song.source),\n 'uri {}'.format(str(song)),\n 'title {}'.format(song.title),\n 'duration {}'.format(song.duration),\n 'url {}'.format(song.url),\n 'artists {}\\t#{}'.format(artists_uri, artists_name),\n 'album {}\\t#{}'.format(album_uri, album_name),\n )\n return '\\n'.join(msgs)\n\n\ndef show_songs(songs):\n return '\\n'.join([show_song(song, brief=True) for song in songs])\n\n\ndef show_artist(artist):\n msgs = [\n 'provider {}'.format(artist.source),\n 'identifier {}'.format(artist.identifier),\n 'name {}'.format(artist.name),\n ]\n if artist.songs:\n songs_header = ['songs::\\n']\n songs = ['\\t' + each for each in show_songs(artist.songs).split('\\n')]\n msgs += songs_header\n msgs += songs\n return '\\n'.join(msgs)\n\n\ndef show_album(album, brief=False):\n msgs = [\n 'provider {}'.format(album.source),\n 'identifier {}'.format(album.identifier),\n 'name {}'.format(album.name),\n ]\n if album.artists is not None:\n artists = album.artists\n artists_id = ','.join([str(artist.identifier) for artist in artists])\n artists_name = ','.join([artist.name for artist in artists])\n msgs_artists = ['artists {}\\t#{}'.format(artists_id, artists_name)]\n msgs += msgs_artists\n if not brief:\n msgs_songs_header = ['songs::\\n']\n msgs_songs = ['\\t' + each for each in show_songs(album.songs).split('\\n')]\n msgs += msgs_songs_header\n msgs += msgs_songs\n return '\\n'.join(msgs)\n\n\ndef show_playlist(playlist, brief=False):\n if brief:\n content = '{playlist}\\t#{name}'.format(\n playlist=playlist,\n name=playlist.name)\n else:\n parts = [\n 'name {}'.format(playlist.name),\n 'songs::\\n',\n ]\n parts += ['\\t' + show_song(song, brief=True) for song in playlist.songs]\n content = '\\n'.join(parts)\n return content\n\n\ndef show_user(user):\n parts = [\n 'name {}'.format(user.name),\n 'playlists::\\n',\n ]\n parts += ['\\t' + show_playlist(p, brief=True) for p in user.playlists]\n return '\\n'.join(parts)\n","sub_path":"fuocore/protocol/handlers/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":3128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"581872813","text":"import os\nimport struct\nimport datetime\nimport subprocess\nimport time\n\nimport pandas\n\nfrom config import config\nfrom util import pylinuxauto, util\nfrom util.log import logger\n\n\ndef basic_info(filepath):\n \"\"\"\n struct TdxSymbolMap {\n char symbol[6]; // 6 digits\n char dummy1[18]\n char name[8]; // 4 characters in GB2312\n char dummy2[218];\n }\n \"\"\"\n infos = []\n with open(filepath, 'rb') as f:\n # file_object_path = 'D:/new_tdx/quote/sh/' + name +'.csv'\n # file_object = open(file_object_path, 'w+')\n\n f.seek(50)\n i = 0\n while True:\n line = f.read(314)\n if not line:\n break\n code = line[:6].decode()\n # name = line[23:31]\n name = line[23:55]\n name = name.decode('gbk')\n name = name.strip(b'\\x00'.decode())\n i += 1\n print(i, code, name)\n infos.append((code, name))\n\n return infos\n\n\ndef parse_quote(filepath, start_date=None, end_date=None):\n code = os.path.basename(filepath)[2:-4]\n quote = []\n with open(filepath, 'rb') as f:\n while True:\n stock_date = f.read(4)\n stock_open = f.read(4)\n stock_high = f.read(4)\n stock_low = f.read(4)\n stock_close = f.read(4)\n stock_amount = f.read(4)\n stock_vol = f.read(4)\n stock_reservation = f.read(4) # date,open,high,low,close,amount,vol,reservation\n if not stock_date:\n break\n # 4字节如20091229\n stock_date = struct.unpack(\"l\", stock_date)\n # 开盘价*100\n stock_open = struct.unpack(\"l\", stock_open)\n # 最高价*100\n stock_high = struct.unpack(\"l\", stock_high)\n # 最低价*100\n stock_low = struct.unpack(\"l\", stock_low)\n # 收盘价*100\n stock_close = struct.unpack(\"l\", stock_close)\n # 成交额\n stock_amount = struct.unpack(\"f\", stock_amount)\n # 成交量\n stock_vol = struct.unpack(\"l\", stock_vol)\n # 保留值\n stock_reservation = struct.unpack(\"l\", stock_reservation)\n # 格式化日期\n date_format = datetime.datetime.strptime(str(stock_date[0]), '%Y%M%d')\n\n if start_date and date_format.date() < start_date:\n continue\n if end_date and date_format.date() >= end_date:\n continue\n\n row = (code, date_format.strftime('%Y-%M-%d'), str(stock_open[0] / 100), str(\n stock_high[0] / 100.0), str(stock_low[0] / 100.0), str(\n stock_close[0] / 100.0), str(stock_amount[0]), str(stock_vol[0]))\n quote.append(row)\n\n df = pandas.DataFrame(quote, columns=['code', 'trade_date', 'open', 'high', 'low', 'close', 'amount', 'volume'])\n return df\n\n\ndef download_quote():\n # now = datetime.datetime.now()\n # if now.hour < 15:\n # return\n\n if util.get_pid_by_exec('tdxw.exe') < 0:\n logger.info('tdx is stopped, start...')\n subprocess.Popen(['playonlinux', '--run', 'tdxw'])\n\n tdx_window_name = config.tdx_window_name\n tdx_version = 'V7.56'\n handle = pylinuxauto.search_window_handle(tdx_window_name)\n if not handle:\n while not handle:\n time.sleep(1)\n handle = pylinuxauto.search_window_handle(tdx_window_name)\n time.sleep(10)\n logger.info('tdx is running')\n\n name = pylinuxauto.get_window_name(handle)\n if name[-5:] == tdx_version:\n # 登录\n logger.info('tdx login...')\n pylinuxauto.send_key('Return')\n while name[-5:] == tdx_version:\n handle = pylinuxauto.search_window_handle(tdx_window_name)\n name = pylinuxauto.get_window_name(handle)\n time.sleep(1)\n time.sleep(10)\n logger.info('tdx login succeed')\n\n pylinuxauto.active_window_by_name(tdx_window_name)\n\n # 方案一\n pylinuxauto.send_key('alt+F4')\n time.sleep(1)\n pylinuxauto.send_key('Return')\n time.sleep(1)\n pylinuxauto.send_key('Return')\n\n while util.get_pid_by_exec('tdxw.exe') > 0:\n time.sleep(5)\n\n logger.info('tdx quote is downloaded')\n\n return\n\n # 方案二\n # if pylinuxauto.has_popup('tdx'):\n # pylinuxauto.close_popup()\n #\n # pos_option = ('1562', '19')\n # pos_download = ('1625', '240')\n # pylinuxauto.mouse_move(pos_option)\n # time.sleep(0.3)\n # pylinuxauto.click_left()\n # time.sleep(0.3)\n # pylinuxauto.mouse_move(pos_download)\n # pylinuxauto.click_left()\n # time.sleep(0.3)\n # pylinuxauto.send_key('space')\n # time.sleep(0.3)\n # pylinuxauto.send_key('Return')\n #\n # while pylinuxauto.has_popup('tdx'):\n # time.sleep(5)\n","sub_path":"acquisition/quote_tdx.py","file_name":"quote_tdx.py","file_ext":"py","file_size_in_byte":4842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"490714267","text":"import os\nimport wave\nimport time\nimport pickle\nimport sounddevice as sd\nimport warnings\nimport numpy as np\nfrom sklearn import preprocessing\nfrom scipy.io.wavfile import read\nimport python_speech_features as mfcc\nfrom sklearn.mixture import GaussianMixture\nfrom scipy.io.wavfile import write\n\nwarnings.filterwarnings(\"ignore\")\n\ndef calculate_delta(array):\n rows, cols = array.shape\n #print(rows)\n #print(cols)\n deltas = np.zeros((rows, 20))\n N = 2\n for i in range(rows):\n index = []\n j = 1\n while j <= N:\n if i - j < 0:\n first = 0\n else:\n first = i - j\n if i + j > rows - 1:\n second = rows - 1\n else:\n second = i + j\n index.append((second, first))\n j += 1\n deltas[i] = (array[index[0][0]] - array[index[0][1]] + (2 * (array[index[1][0]] - array[index[1][1]]))) / 10\n return deltas\n\n\ndef extract_features(audio, rate):\n mfcc_feature = mfcc.mfcc(audio, rate, 0.025, 0.01, 20, nfft=2048, appendEnergy=True)\n mfcc_feature = preprocessing.scale(mfcc_feature)\n #print(mfcc_feature)\n delta = calculate_delta(mfcc_feature)\n combined = np.hstack((mfcc_feature, delta))\n return combined\n\n\ndef record_audio_train():\n Name = (input(\"Please Enter Your Name:\"))\n for count in range(5):\n FORMAT = \"float32\"\n CHANNELS = 1\n RATE = 16000\n RECORD_SECONDS = 2\n\n print(\"recording started\")\n \n recording = sd.rec(samplerate=RATE, channels=CHANNELS,\n dtype=FORMAT, frames=RATE*RECORD_SECONDS)\n sd.wait()\n\n print(\"recording stopped\")\n if not os.path.exists('training_set'):\n os.makedirs('training_set')\n OUTPUT_FILENAME = Name + \"-sample\" + str(count) + \".wav\"\n WAVE_OUTPUT_FILENAME = os.path.join(\"training_set\", OUTPUT_FILENAME)\n trainedfilelist = open(\"training_set_addition.txt\", 'a')\n trainedfilelist.write(OUTPUT_FILENAME + \"\\n\")\n write(WAVE_OUTPUT_FILENAME, RATE, recording)\n\n\n\ndef record_audio_test():\n FORMAT = \"float32\"\n CHANNELS = 1\n RATE = 16000\n RECORD_SECONDS = 2\n\n print(\"recording started\")\n\n recording = sd.rec(samplerate=RATE, channels=CHANNELS,\n dtype=FORMAT, frames=RATE*RECORD_SECONDS)\n sd.wait()\n \n print(\"recording stopped\")\n \n OUTPUT_FILENAME = \"sample.wav\"\n WAVE_OUTPUT_FILENAME = os.path.join(\"testing_set\", OUTPUT_FILENAME)\n write(WAVE_OUTPUT_FILENAME, RATE, recording)\n\ndef train_model():\n source = \"./training_set/\"\n if not os.path.exists('trained_models'):\n os.makedirs('trained_models')\n dest = \"./trained_models/\"\n train_file = \"./training_set_addition.txt\"\n file_paths = open(train_file, 'r')\n count = 1\n features = np.asarray(())\n for path in file_paths:\n path = path.strip()\n print(path)\n\n sr, audio = read(source + path)\n vector = extract_features(audio, sr)\n\n if features.size == 0:\n features = vector\n else:\n features = np.vstack((features, vector))\n\n if count == 5:\n gmm = GaussianMixture(n_components=20, max_iter=200, covariance_type='diag', n_init=3)\n gmm.fit(features)\n\n # dumping the trained gaussian model\n picklefile = path.split(\"-\")[0] + \".gmm\"\n pickle.dump(gmm, open(dest + picklefile, 'wb'))\n print('+ modeling completed for speaker:', picklefile, \" with data point = \", features.shape)\n features = np.asarray(())\n count = 0\n count = count + 1\n\ndef test_model(audio_data, sr):\n modelpath = \"./trained_models/\"\n\n gmm_files = [os.path.join(modelpath, fname) for fname in os.listdir(modelpath) if fname.endswith('.gmm')]\n\n models = [pickle.load(open(fname, 'rb')) for fname in gmm_files]\n speakers = [fname.split(\"\\\\\")[-1].split(\".gmm\")[0] for fname in gmm_files]\n \n vector = extract_features(audio_data, sr)\n\n log_likelihood = np.zeros(len(models))\n\n for i in range(len(models)):\n gmm = models[i]\n scores = np.array(gmm.score(vector))\n log_likelihood[i] = scores.sum()\n print(log_likelihood)\n winner = np.argmax(log_likelihood)\n if np.max(log_likelihood) > -35:\n print(\"\\tdetected as -\", speakers[winner].split(\"/\")[2])\n return True\n else:\n return False\n","sub_path":"speaker_recog.py","file_name":"speaker_recog.py","file_ext":"py","file_size_in_byte":4462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"365172155","text":"import time\r\nimport urllib.request\r\nimport pylast\r\nimport discord\r\nfrom bs4 import BeautifulSoup\r\nfrom lyricsgenius import Genius\r\nimport lyricsgenius\r\nfrom pyowm import OWM\r\nimport config\r\nimport sqlite3\r\nimport asyncio\r\n\r\nAPI_KEY = config.API_KEY\r\nAPI_SECRET = config.API_SECRET\r\nOMV_KEY = config.OMV_KEY\r\nCLIENT_RUN = config.CLIENT_RUN\r\nLYRICS_KEY = config.LYRICS_KEY\r\n\r\n# Wer das liest ist blöd XD\r\n\r\nuserdict = {}\r\n\r\n# connection\r\nconnection = sqlite3.connect('reminder.db')\r\ncursor = connection.cursor()\r\n\r\n# table createn\r\ntry:\r\n creation = \"\"\"CREATE TABLE IF NOT EXISTS\r\n reminders(id INTEGER PRIMARY KEY, user_id INTEGER, reminder_text TEXT, reminder_time INTEGER, channel INTEGER, message_id INTEGER)\"\"\"\r\n cursor.execute(creation)\r\nexcept:\r\n pass\r\n\r\n\r\nclass MyClient(discord.Client):\r\n\r\n @staticmethod\r\n async def on_ready():\r\n print(\"Hallo I bim omnline :^)\")\r\n await get_reminder_startup()\r\n\r\n # Nachricht\r\n @staticmethod\r\n async def on_message(message):\r\n\r\n if message.author == client.user:\r\n return\r\n else:\r\n if message.content.startswith('+'):\r\n message.content = message.content[1:]\r\n if str(message.author) in userdict:\r\n timealt = userdict[str(message.author)]\r\n else:\r\n userdict[str(message.author)] = 10\r\n timealt = userdict[str(message.author)]\r\n dauer = time.time() - timealt\r\n\r\n if dauer > 5:\r\n await wiki(message)\r\n await wetter(message)\r\n await helpfunction(message)\r\n await reminder(message)\r\n #if message.channel.id == 608746970340786282:\r\n await lyrics(message)\r\n\r\n\r\nasync def reminder(message):\r\n if \"remindme\" in message.content:\r\n try:\r\n userdict[str(message.author)] = time.time()\r\n user_id = message.author.id\r\n split_message = message.content.split(\" \")\r\n if split_message[2] == \"seconds\" or split_message[2] == \"s\":\r\n reminder_time1 = round(time.time() + float(split_message[1]), 2)\r\n elif split_message[2] == \"minutes\" or split_message[2] == \"m\":\r\n reminder_time1 = round(time.time() + (float(split_message[1]) * 60), 2)\r\n elif split_message[2] == \"hours\" or split_message[2] == \"h\":\r\n reminder_time1 = round(time.time() + (int(split_message[1]) * 3600), 2)\r\n elif split_message[2] == \"days\" or split_message[2] == \"d\":\r\n reminder_time1 = round(time.time() + (int(split_message[1]) * 86400), 2)\r\n elif split_message[2] == \"weeks\" or split_message[2] == \"w\":\r\n reminder_time1 = round(time.time() + (int(split_message[1]) * 604800), 2)\r\n elif split_message[2] == \"months\":\r\n reminder_time1 = round(time.time() + (int(split_message[1]) * 2678400), 2)\r\n del split_message[:3]\r\n reminder_text = \" \".join(split_message)\r\n channel = message.channel.id\r\n sql = \"INSERT INTO reminders (user_id, reminder_text, reminder_time, channel, message_id) VALUES (?, ?, ?, ?, ?)\"\r\n val = (user_id, reminder_text, reminder_time1, channel, message.id)\r\n cursor.execute(sql, val)\r\n connection.commit()\r\n await message.add_reaction('\\N{THUMBS UP SIGN}')\r\n await wait_for_reminder(reminder_text, reminder_time1, message)\r\n except:\r\n await message.channel.send(\"Hm ne irgendwas gefällt mir daran nich. Nochmal? 🤷\")\r\n\r\n\r\nasync def get_reminder_startup():\r\n try:\r\n cursor.execute(\"SELECT * FROM reminders ORDER BY reminder_time ASC LIMIT 1\")\r\n result = cursor.fetchall()\r\n if result:\r\n id = result[0][0]\r\n user_id = result[0][1]\r\n reminder_text = result[0][2]\r\n reminder_time1 = result[0][3]\r\n channel_id = result[0][4]\r\n channel = client.get_channel(channel_id)\r\n message = await channel.fetch_message(id=result[0][5])\r\n await wait_for_reminder_startup(id, user_id, reminder_text, reminder_time1, channel_id, message)\r\n except:\r\n await message.channel.send(\r\n 'Irgendwas klappt nedde. Scheiß Zicklaa zsamme gschwind. Hint: get_reminder_startup()')\r\n\r\n\r\nasync def wait_for_reminder(reminder_text, reminder_time1, message):\r\n try:\r\n if (reminder_time1 - time.time()) < 0:\r\n await message.reply(\r\n \"Ich werde dich wissen lassen:\\n **{}**\".format(reminder_text), mention_author=True)\r\n cursor.execute(\"DELETE FROM reminders WHERE reminder_time=?\", (reminder_time1,))\r\n connection.commit()\r\n else:\r\n await asyncio.sleep(reminder_time1 - time.time())\r\n await message.reply(\r\n \"Ich werde dich wissen lassen:\\n **{}**\".format(reminder_text), mention_author=True)\r\n cursor.execute(\"DELETE FROM reminders WHERE reminder_time=?\", (reminder_time1,))\r\n connection.commit()\r\n except:\r\n await message.channel.send('Irgendwas klappt nedde. Scheiß Zicklaa zsamme gschwind. Hint: wait_for_reminder()')\r\n\r\n\r\nasync def wait_for_reminder_startup(id, user_id, reminder_text, reminder_time1, channel_id, message):\r\n try:\r\n channel = client.get_channel(channel_id)\r\n if (reminder_time1 - time.time()) < 0:\r\n await message.reply(\r\n \"Ich werde dich wissen lassen:\\n **{}**\".format(reminder_text), mention_author=True)\r\n cursor.execute(\"DELETE FROM reminders WHERE id=?\", (id,))\r\n connection.commit()\r\n else:\r\n await asyncio.sleep(reminder_time1 - time.time())\r\n await message.reply(\r\n \"Ich werde dich wissen lassen:\\n **{}**\".format(reminder_text), mention_author=True)\r\n cursor.execute(\"DELETE FROM reminders WHERE id=?\", (id,))\r\n connection.commit()\r\n await get_reminder_startup()\r\n except:\r\n await channel.send('Irgendwas klappt nedde. Scheiß Zicklaa zsamme gschwind. Hint: wait_for_reminder_startup()')\r\n\r\n\r\nasync def helpfunction(message):\r\n if message.content == \"help\":\r\n userdict[str(message.author)] = time.time()\r\n embed = discord.Embed(title='Help', description='Hier wird Ihnen geholfen!', color=0x00ff00)\r\n embed.add_field(name='+help', value=\"Öffnet das Hilfefenster \", inline=False)\r\n embed.add_field(name='+lyrics', value=\"Format: +lyrics (full/link) [USERNAME]\",\r\n inline=False)\r\n embed.add_field(name='+wetter', value=\"Format: +wetter [ORTNAME]\", inline=False)\r\n embed.add_field(name='+wiki', value=\"Format: +wiki [SUCHBEGRIFF]\", inline=False)\r\n embed.add_field(name='+remindme',\r\n value=\"Format: +remindme [ZAHL] [seconds or s/minutes or m/hours or h/days or d/months] [TEXT]\",\r\n inline=False)\r\n embed.set_author(name='Gott', icon_url='https://cdn.psychologytoday.com/sites'\r\n '/default/files/field_blog_entry_images/God_the_Father.jpg')\r\n await message.channel.send(embed=embed)\r\n\r\n\r\nasync def wiki(message):\r\n try:\r\n if message.content.startswith('wiki'):\r\n userdict[str(message.author)] = time.time()\r\n wiki1 = message.content.replace('wiki ', '')\r\n wiki2 = wiki1.replace(' ', '_')\r\n url = 'https://de.wikipedia.org/wiki/' + wiki2.title()\r\n page = urllib.request.urlopen(url)\r\n soup = BeautifulSoup(page, \"html.parser\")\r\n embed = discord.Embed(title=wiki1.title(), url=url, color=0x00ff00)\r\n start = soup('p')\r\n x = 0\r\n text2 = \"\"\r\n for i in start:\r\n t = str(i.getText())\r\n if len(t) > 200:\r\n text = str(i.getText())\r\n text2 = text2 + text\r\n x = x + 1\r\n if x == 2:\r\n break\r\n text2 = (text2[:1020] + '...') if len(text2) > 1024 else text2\r\n text2 = text2.replace('[1]', '').replace('[2]', '').replace('[3]', '').replace('[4]', '') \\\r\n .replace('[5]', '').replace('[6]', '').replace('[7]', '') \\\r\n .replace('[8]', '').replace('[9]', '').replace('[10]', '')\r\n embed.add_field(name=\"Beschreibung\", value=text2, inline=False)\r\n\r\n image_tag = soup.findAll('img')\r\n for bild in image_tag:\r\n bild_url = 'https:' + bild.get('src')\r\n if bild_url == 'https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Disambig-dark.svg/25px' \\\r\n '-Disambig-dark.svg.png' or bild_url == 'https://upload.wikimedia.org/wikipedia/c' \\\r\n 'ommons/thumb/f/f3/Photo-request.svg/40px-P' \\\r\n 'hoto-request.svg.png' or \\\r\n bild_url == 'https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Qsicon_lesenswert.' \\\r\n 'svg/15px-Qsicon_lesenswert.svg.png' or bild_url == 'https://upload.wikimedia.' \\\r\n 'org/wikipedia/commons/thumb' \\\r\n '/a/a1/Qsicon_gesprochen.svg/' \\\r\n '15px-Qsicon_gesprochen.' \\\r\n 'svg.png' or bild_url == \\\r\n 'https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/' \\\r\n 'Wiktfavicon_en.svg/16px-Wiktfavicon_en.svg.png':\r\n pass\r\n else:\r\n bild_url = 'https:' + bild.get('src')\r\n embed.set_thumbnail(url=bild_url)\r\n break\r\n await message.channel.send(embed=embed)\r\n except:\r\n if message.content.startswith('wiki'):\r\n userdict[str(message.author)] = time.time()\r\n wiki1 = message.content.replace('wiki ', '')\r\n wiki2 = wiki1.replace(' ', '_')\r\n wiki22 = wiki2.title()\r\n url = 'https://de.wikipedia.org/wiki/' + wiki22\r\n await message.channel.send('Jibtet nit. Probier doch mal selber: ' + url)\r\n\r\n\r\nasync def lyrics(message):\r\n if message.content.startswith('lyrics'):\r\n userdict[str(message.author)] = time.time()\r\n if message.content == 'lyrics':\r\n await message.channel.send('Format: \"+lyrics (full/link) [USERNAME]\"')\r\n return\r\n if message.content == 'lyrics full' or message.content == 'lyrics link':\r\n await message.channel.send('Ein Username wäre ganz hilfreich, retard.')\r\n return\r\n username = message.content.replace('lyrics full ', '').replace('lyrics link ', '')\r\n wort = message.content.replace('lyrics ', '')\r\n try:\r\n network = pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET)\r\n user = network.get_user(username)\r\n except:\r\n await message.channel.send('User nit gefunden.')\r\n return\r\n if wort.startswith('full'):\r\n try:\r\n lied = user.get_now_playing()\r\n seconds = (lied.get_duration() / 1000) % 60\r\n seconds = int(seconds)\r\n minutes = (lied.get_duration() / (1000 * 60)) % 60\r\n minutes = int(minutes)\r\n if seconds < 10:\r\n seconds = \"0\" + str(seconds)\r\n\r\n artisturl = 'https://www.last.fm/de/music/' + str(lied.get_artist()).replace(' ', '+')\r\n songurl = artisturl + '/_/' + str(lied.get_name()).replace(' ', '+').replace('/', '%2F')\r\n name = str('[' + str(lied.get_name()) + '](' + str(songurl) + ')')\r\n artist = str('[' + str(lied.get_artist()) + '](' + str(artisturl) + ')')\r\n\r\n embed = discord.Embed(title='', color=1917791)\r\n\r\n if user.get_image() is not None:\r\n embed.set_author(name=username, icon_url=user.get_image(),\r\n url='https://www.last.fm/user/' + username)\r\n else:\r\n embed.set_author(name=username, url='https://www.last.fm/user/' + username)\r\n\r\n embed.set_thumbnail(url=str(lied.get_cover_image()))\r\n embed.add_field(name='Titel', value=name)\r\n album = str(lied.get_album())\r\n album = album.replace(str(lied.get_artist()), '').replace(' - ', '')\r\n embed.add_field(name='Artist', value=artist, inline=True)\r\n footer = 'Album: ' + album + ' | ' + 'Duration: ' \\\r\n + str(minutes) + ':' + str(seconds) + ' | ' + 'Plays: ' + str(lied.get_playcount())\r\n embed.set_footer(text=footer)\r\n try:\r\n genius = lyricsgenius.Genius(LYRICS_KEY)\r\n text = genius.search_song(title=str(lied.get_name()), artist=str(lied.get_artist()))\r\n gesamter_text = str(text.lyrics).replace('EmbedShare URLCopyEmbedCopy', '')[0:5500]\r\n while gesamter_text != \"\":\r\n embed.add_field(name='Fortsetzung', value=(gesamter_text[0:1020]), inline=False)\r\n gesamter_text = gesamter_text[1020:]\r\n except:\r\n await message.channel.send(\r\n 'Irgendwas is schiefgelaufen lol. Vielleicht ist der Songtext länger als Discord zulässt?')\r\n\r\n await message.channel.send(embed=embed)\r\n except:\r\n await message.channel.send('Dieser User hört gerade nix.')\r\n elif wort.startswith('link'):\r\n try:\r\n lied = user.get_now_playing()\r\n seconds = (lied.get_duration() / 1000) % 60\r\n seconds = int(seconds)\r\n minutes = (lied.get_duration() / (1000 * 60)) % 60\r\n minutes = int(minutes)\r\n if seconds < 10:\r\n seconds = \"0\" + str(seconds)\r\n\r\n artisturl = 'https://www.last.fm/de/music/' + str(lied.get_artist()).replace(' ', '+')\r\n songurl = artisturl + '/_/' + str(lied.get_name()).replace(' ', '+').replace('/', '%2F')\r\n name = str('[' + str(lied.get_name()) + '](' + str(songurl) + ')')\r\n artist = str('[' + str(lied.get_artist()) + '](' + str(artisturl) + ')')\r\n embed = discord.Embed(title='', color=1917791)\r\n\r\n if user.get_image() is not None:\r\n embed.set_author(name=username, icon_url=user.get_image(),\r\n url='https://www.last.fm/user/' + username)\r\n else:\r\n embed.set_author(name=username, url='https://www.last.fm/user/' + username)\r\n\r\n embed.set_thumbnail(url=str(lied.get_cover_image()))\r\n embed.add_field(name='Titel', value=name)\r\n album = str(lied.get_album())\r\n album = album.replace(str(lied.get_artist()), '').replace(' - ', '')\r\n embed.add_field(name='Artist', value=artist, inline=True)\r\n footer = 'Album: ' + album + ' | ' + 'Duration: ' \\\r\n + str(minutes) + ':' + str(seconds) + ' | ' + 'Plays: ' + str(lied.get_playcount())\r\n embed.set_footer(text=footer)\r\n genius = Genius(LYRICS_KEY)\r\n song = genius.search_song(title=lied.get_title(), artist=lied.get_artist())\r\n embed.add_field(name='Link', value=str('[' + str(lied) + '](' + str(song.url) + ')'),\r\n inline=False)\r\n\r\n await message.channel.send(embed=embed)\r\n except:\r\n await message.channel.send('Dieser User hört gerade nix.')\r\n\r\n\r\nasync def wetter(message):\r\n owm = OWM(OMV_KEY)\r\n if message.content.startswith('wetter'):\r\n try:\r\n userdict[str(message.author)] = time.time()\r\n mgr = owm.weather_manager()\r\n place = message.content.replace('wetter ', '')\r\n observation = mgr.weather_at_place(place)\r\n wetter_neu = observation.weather\r\n embed = discord.Embed(title='Wetter in ' + place.title(), color=1917791)\r\n embed.set_author(name='Gott', icon_url='https://cdn.psychologytoday.com/sites'\r\n '/default/files/field_blog_entry_images/God_the_Father.jpg')\r\n temp = wetter_neu.temperature('celsius')\r\n embed.add_field(name='Temperatur', value=str(round(temp['temp'], 1)) + '°C')\r\n embed.add_field(name='Luftfeuchtigkeit', value=str(wetter_neu.humidity) + '%', inline=True)\r\n embed.add_field(name='Status', value=wetter_neu.detailed_status, inline=False)\r\n await message.channel.send(embed=embed)\r\n except:\r\n await message.channel.send(\r\n 'Wetter schmetter, sag ich schon immer.')\r\n\r\n\r\n''' def test(message):\r\n if message.content == \"stop\":\r\n liste = []\r\n blacklist = ['ich', 'das', 'die', 'ist', 'von', 'in', 'was', 'der', 'du', 'a', 'nicht', 'so', 'ja',\r\n 'zu', 'und'\r\n , 'mit', 'dann', 'es', 'auch', 'hier', 'aber', 'nur', 'da', 'man', 'ein', 'hat', 'mal', 'hab',\r\n 'schon'\r\n , 'wie', 'auf', 'hat', 'wird', 'wenn', 'is', 'mein', 'alles', 'ne', 'dass', 'bin', 'den', 'aus',\r\n 'mich',\r\n 'ok', 'für', 'mir', 'sind', 'eine', 'doch', 'warum', '', '', '', '', '', '', '', '', '',\r\n '', '',\r\n '', '', '']\r\n blackliste = []\r\n dict = {}\r\n nummer = 25000\r\n zahl = 0\r\n messages = await message.channel.history(limit=nummer).flatten()\r\n for m in messages:\r\n if str(m.author) == str(message.author):\r\n zahl = zahl + 1\r\n liste = m.content.lower().split()\r\n for i in liste:\r\n if i in blackliste:\r\n pass\r\n else:\r\n if i in dict:\r\n number = dict.get(i)\r\n dict[str(i)] = number + 1\r\n else:\r\n dict[str(i)] = 1\r\n sorted_dict = sorted(dict.items(), key=operator.itemgetter(1), reverse=True)\r\n embed = discord.Embed(title='Häufigste Wörter', color=0x00ff00)\r\n d = sorted_dict[:8]\r\n for i in d:\r\n embed.add_field(name='Wort', value=i[0])\r\n embed.add_field(name='Anzahl', value=i[1], inline=True)\r\n embed.add_field(name='Häufigkeit', value=(str(round((int(i[1]) / zahl) * 100))) + \"%\", inline=True)\r\n await message.channel.send(embed=embed)'''\r\n\r\n'''async def bruh(message):\r\n if message.content == \"bruh\":\r\n userdict[str(message.author)] = time.time()\r\n await message.delete()\r\n embed = discord.Embed(title='Bruh', description='Bruh', url='https://www.youtube.com/watch?v=2ZIpFytCSVc',\r\n color=0x00ff00)\r\n embed.set_footer(text='Bruh')\r\n embed.add_field(name='Bruh', value=message.author.mention + \" sagt:\")\r\n embed.set_image(url='https://i.imgur.com/qslkBXI.gif')\r\n embed.set_thumbnail(url='https://i.imgur.com/qslkBXI.gif')\r\n embed.set_author(name='Bruh', url='https://i.imgur.com/qslkBXI.gif')\r\n await message.channel.send(embed=embed)'''\r\n\r\nclient = MyClient()\r\nclient.run(CLIENT_RUN)\r\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":20318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"379014026","text":"'''\n# This is an 80 character line #\nCompute the per-particle active pressure\n (with both swim and interparticle contributions)\n'''\n\nimport sys\n\n# Run locally\nsys.path.append('/Users/kolbt/Desktop/compiled/hoomd-blue/build')\nsys.path.append('/Users/kolbt/Desktop/compiled/gsd/build')\n# Run on the cpu\nsys.path.append('/nas/longleaf/home/kolbt/programs/cpu-hoomd/hoomd-blue/build')\n# Run on the gpu\n\nsys.path.append('/nas/longleaf/home/kolbt/programs/hoomd_2.2.1/hoomd-blue/build')\nsys.path.append('/nas/longleaf/home/kolbt/programs/gsd/build')\n\nimport gsd\nfrom gsd import hoomd\nfrom gsd import pygsd\n\nimport freud\nfrom freud import parallel\nfrom freud import box\nfrom freud import density\nfrom freud import cluster\n\nimport numpy as np\nimport math\nimport random\nfrom scipy import stats\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.collections\nfrom matplotlib import colors\nimport matplotlib.gridspec as gridspec\nimport matplotlib.patches as patches\n \ndef distComps(point1, point2x, point2y):\n '''Given points output x, y and r'''\n dx = point2x - point1[0]\n dy = point2y - point1[1]\n r = np.sqrt((dx**2) + (dy**2))\n return dx, dy, r\n \ndef computeFLJ(r, dx, dy, eps):\n sig = 1.\n f = (24. * eps / r) * ( (2*((sig/r)**12)) - ((sig/r)**6) )\n fx = f * (dx) / r\n fy = f * (dy) / r\n return fx, fy\n\ndef computeTauPerTstep(epsilon, mindt=0.000001):\n '''Read in epsilon, output tauBrownian per timestep'''\n# if epsilon != 1.:\n# mindt=0.00001\n kBT = 1.0\n tstepPerTau = float(epsilon / (kBT * mindt))\n return 1. / tstepPerTau\n\ndef roundUp(n, decimals=0):\n '''Round up size of bins to account for floating point inaccuracy'''\n multiplier = 10 ** decimals\n return math.ceil(n * multiplier) / multiplier\n \ndef getNBins(length, minSz=(2**(1./6.))):\n \"Given box size, return number of bins\"\n initGuess = int(length) + 1\n NBins = initGuess\n # This loop only exits on function return\n while True:\n if length / NBins > minSz:\n return NBins\n else:\n NBins -= 1\n \n# Get lattice spacing for particle size\ndef ljForce(r, eps, sigma=1.):\n div = (sigma/r)\n dU = (24. * eps / r) * ((2*(div**12)) - (div)**6)\n return dU\n \ndef avgCollisionForce(pe, power=1.):\n '''Computed from the integral of possible angles'''\n magnitude = np.sqrt(28.)\n return (magnitude * (pe)) / (np.pi)\n \ndef conForRClust(pe, eps):\n out = []\n r = 1.112\n skip = [0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001, 0.0000001, 0.00000001]\n for j in skip:\n while ljForce(r, eps) < avgCollisionForce(pe):\n r -= j\n r += j\n out = r\n return out\n\n# Get infile and open\ninFile = str(sys.argv[1])\nif inFile[0:7] == \"cluster\":\n add = 'cluster_'\nelse:\n add = ''\n \nf = hoomd.open(name=inFile, mode='rb')\n# Inside and outside activity from command line\npeA = float(sys.argv[2])\npeB = float(sys.argv[3])\nparFrac = float(sys.argv[4])\neps = float(sys.argv[5])\ntry:\n phi = float(sys.argv[6])\n intPhi = int(phi)\n phi /= 100.\nexcept:\n phi = 0.6\n intPhi = 60\ntry:\n dtau = float(sys.argv[7])\nexcept:\n dtau = 0.000001\n \nlat = conForRClust(peA, eps)\n \n# Get number of particles for textfile name\nwith hoomd.open(name=inFile, mode='rb') as t:\n snap = t[0]\n typ = snap.particles.typeid\n partNum = len(typ)\n\n# Outfile to write data to\nbase = add + 'hmap_pressure_pa' + str(peA) +\\\n '_pb' + str(peB) +\\\n '_xa' + str(parFrac) +\\\n '_phi' + str(intPhi) +\\\n '_ep' + '{0:.3f}'.format(eps) +\\\n '_N' + str(partNum)\n\nstart = 0 # first frame to process\ndumps = int(f.__len__()) # get number of timesteps dumped\nend = dumps # final frame to process\nstart = end - 1\n\nbox_data = np.zeros((1), dtype=np.ndarray) # box dimension holder\nr_cut = 2**(1./6.) # potential cutoff\ntauPerDT = computeTauPerTstep(epsilon=eps) # brownian time per timestep\n\nwith hoomd.open(name=inFile, mode='rb') as t:\n snap = t[0]\n first_tstep = snap.configuration.step\n box_data = snap.configuration.box\n l_box = box_data[0]\n h_box = l_box / 2.\n typ = snap.particles.typeid\n partNum = len(typ)\n # Compute each mesh\n NBins = getNBins(l_box, r_cut)\n sizeBin = roundUp((l_box / NBins), 6)\n # Set some values for plotting\n parts = [lat for i in range(0, partNum)]\n myCols = plt.cm.jet\n \n # Loop through each timestep\n for j in range(start, end):\n snap = t[j]\n # Easier accessors\n pos = snap.particles.position # position\n pos[:,-1] = 0.0\n xy = np.delete(pos, 2, 1)\n typ = snap.particles.typeid # type\n tst = snap.configuration.step # timestep\n tst -= first_tstep # normalize by first timestep\n tst *= dtau # convert to Brownian time\n \n # Mesh and bin the particles by position\n binParts = [[[] for b in range(NBins)] for a in range(NBins)]\n for k in range(0, partNum):\n # Convert position to be > 0 to place in list mesh\n tmp_posX = pos[k][0] + h_box\n tmp_posY = pos[k][1] + h_box\n x_ind = int(tmp_posX / sizeBin)\n y_ind = int(tmp_posY / sizeBin)\n # Append all particles to appropriate bin\n binParts[x_ind][y_ind].append(k)\n \n # Loop through particles and compute pressure\n pressure = [0. for i in range(0, partNum)]\n for k in range(0, partNum):\n # Get mesh indices\n tmp_posX = pos[k][0] + h_box\n tmp_posY = pos[k][1] + h_box\n x_ind = int(tmp_posX / sizeBin)\n y_ind = int(tmp_posY / sizeBin)\n # Get index of surrounding bins\n l_bin = x_ind - 1 # index of left bins\n r_bin = x_ind + 1 # index of right bins\n b_bin = y_ind - 1 # index of bottom bins\n t_bin = y_ind + 1 # index of top bins\n if r_bin == NBins:\n r_bin -= NBins # adjust if wrapped\n if t_bin == NBins:\n t_bin -= NBins # adjust if wrapped\n h_list = [l_bin, x_ind, r_bin] # list of horizontal bin indices\n v_list = [b_bin, y_ind, t_bin] # list of vertical bin indices\n\n # Loop through all bins\n for h in range(0, len(h_list)):\n for v in range(0, len(v_list)):\n # Take care of periodic wrapping for position\n wrapX = 0.0\n wrapY = 0.0\n if h == 0 and h_list[h] == -1:\n wrapX -= l_box\n if h == 2 and h_list[h] == 0:\n wrapX += l_box\n if v == 0 and v_list[v] == -1:\n wrapY -= l_box\n if v == 2 and v_list[v] == 0:\n wrapY += l_box\n # Compute distance between particles\n for b in range(0, len(binParts[h_list[h]][v_list[v]])):\n ref = binParts[h_list[h]][v_list[v]][b]\n dx, dy, r = distComps(pos[k],\n pos[ref][0] + wrapX,\n pos[ref][1] + wrapY)\n r = round(r, 4) # round value to 4 decimal places\n\n # If LJ potential is on, compute pressure\n if 0.1 < r <= r_cut:\n # Compute the x and y components of force\n fx, fy = computeFLJ(r, dx, dy, eps)\n # Compute the x force times x distance\n sigx = fx * (dx)\n # Likewise for y\n sigy = fy * (dy)\n # Test the code\n if sigx < 0 or sigy < 0:\n print(\"Negative value for force times r!!!\")\n # Add the pressure from this neighbor\n pressure[k] += ((sigx + sigy) / 2.)\n \n outDPI = 500.\n fig, ax = plt.subplots()\n xy = np.delete(pos, 2, 1)\n coll = matplotlib.collections.EllipseCollection(parts, parts,\n np.zeros_like(parts),\n offsets=xy, units='xy',\n cmap=myCols,\n transOffset=ax.transData)\n coll.set_array(np.ravel(pressure))\n# minCol = min(pressure)\n# maxCol = max(pressure)\n# coll.set_clim([minCol, 1.0])\n ax.add_collection(coll)\n cbar = plt.colorbar(coll, format='%.0f')\n cbar.set_label(r'Interparticle Pressure $(\\Pi^{P})$', labelpad=20, rotation=270)\n\n # Limits and ticks\n viewBuff = 0.0\n ax.set_xlim(-h_box - viewBuff, h_box + viewBuff)\n ax.set_ylim(-h_box - viewBuff, h_box + viewBuff)\n ax.tick_params(axis='both', which='both',\n bottom=False, top=False, left=False, right=False,\n labelbottom=False, labeltop=False, labelleft=False, labelright=False)\n\n pad = str(j).zfill(4)\n ax.set_aspect('equal')\n plt.tight_layout()\n plt.savefig(base + '_' + pad + '.png', dpi=outDPI)\n plt.close()\n","sub_path":"post_proc/swim_pressure_heatmap.py","file_name":"swim_pressure_heatmap.py","file_ext":"py","file_size_in_byte":9634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"358480724","text":"import os, json\nfrom copy import deepcopy\nfrom matplotlib.pylab import *\n\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom scripts.model.nl2sql.models.sel_predict import *\nfrom scripts.model.nl2sql.models.cond_predict import *\nfrom scripts.model.nl2sql.utils.utils_data import *\nfrom scripts.model.nl2sql.utils.utils import *\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\nclass NL2SQL(nn.Module):\n def __init__(self, iS, hS, lS, dr, n_cond_ops, n_agg_ops, n_order_ops, old=False):\n super(NL2SQL, self).__init__()\n self.iS = iS\n self.hS = hS\n self.ls = lS\n self.dr = dr\n\n self.max_wn = 4\n self.n_cond_ops = n_cond_ops\n self.n_agg_ops = n_agg_ops\n self.n_order_ops = n_order_ops\n # where col prediction\n self.snp = SNP(iS, hS, lS, dr)\n # select column prediction\n self.scp = SCP(iS, hS, lS, dr)\n # select agg prediction\n self.sap = SAP(iS, hS, lS, dr, n_agg_ops, old=old)\n # where num prediction\n self.wnp = WNP(iS, hS, lS, dr)\n\n self.wcp = WCP(iS, hS, lS, dr)\n self.wop = WOP(iS, hS, lS, dr, n_cond_ops)\n self.wvp = WVP_se(iS, hS, lS, dr, n_cond_ops, old=old) # start-end-search-discriminative model\n\n def forward(self, wemb_n, l_n, wemb_hpu, l_hpu, l_hs,\n g_sn=None, g_sc=None, g_sa=None, g_wn=None, g_wc=None, g_wo=None, g_wvi=None,\n show_p_sc=False, show_p_sa=False,\n show_p_wn=False, show_p_wc=False, show_p_wo=False, show_p_wv=False):\n\n # sn\n s_sn = self.snp(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, show_p_wn=show_p_wn)\n\n if g_wn:\n pr_sn = g_sn\n else:\n pr_sn = pred_sn(s_sn)\n\n # sc\n s_sc = self.scp(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, show_p_sc=show_p_sc)\n\n if g_sc:\n pr_sc = g_sc\n else:\n pr_sc = pred_sc(s_sc)\n\n # sa\n s_sa = self.sap(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, pr_sn, pr_sc, show_p_sa=show_p_sa)\n if g_sa:\n # it's not necessary though.\n pr_sa = g_sa\n else:\n pr_sa = pred_sa(s_sa)\n\n\n # wn\n s_wn = self.wnp(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, show_p_wn=show_p_wn)\n\n if g_wn:\n pr_wn = g_wn\n else:\n pr_wn = pred_wn(s_wn)\n\n # wc\n s_wc = self.wcp(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, show_p_wc=show_p_wc, penalty=True)\n\n if g_wc:\n pr_wc = g_wc\n else:\n pr_wc = pred_wc(pr_wn, s_wc)\n\n # wo\n s_wo = self.wop(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, wn=pr_wn, wc=pr_wc, show_p_wo=show_p_wo)\n\n if g_wo:\n pr_wo = g_wo\n else:\n pr_wo = pred_wo(pr_wn, s_wo)\n\n # wv\n s_wv = self.wvp(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, wn=pr_wn, wc=pr_wc, wo=pr_wo, show_p_wv=show_p_wv)\n\n return s_sn, s_sc, s_sa, s_wn, s_wc, s_wo, s_wv\n\n def beam_forward(self, wemb_n, l_n, wemb_hpu, l_hpu, l_hs, engine, tb,\n nlu_t, nlu_wp_t, wp_to_wh_index, nlu,\n beam_size=4,\n show_p_sc=False, show_p_sa=False,\n show_p_wn=False, show_p_wc=False, show_p_wo=False, show_p_wv=False):\n \"\"\"\n Execution-guided beam decoding.\n \"\"\"\n # sc\n s_sc = self.scp(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, show_p_sc=show_p_sc)\n prob_sc = F.softmax(s_sc, dim=-1)\n bS, mcL = s_sc.shape\n\n # minimum_hs_length = min(l_hs)\n # beam_size = minimum_hs_length if beam_size > minimum_hs_length else beam_size\n\n # sa\n # Construct all possible sc_sa_score\n prob_sc_sa = torch.zeros([bS, beam_size, self.n_agg_ops]).to(device)\n prob_sca = torch.zeros_like(prob_sc_sa).to(device)\n\n # get the top-k indices. pr_sc_beam = [B, beam_size]\n pr_sc_beam = pred_sc_beam(s_sc, beam_size)\n\n # calculate and predict s_sa.\n for i_beam in range(beam_size):\n pr_sc = list( array(pr_sc_beam)[:,i_beam] )\n s_sa = self.sap(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, pr_sc, show_p_sa=show_p_sa)\n prob_sa = F.softmax(s_sa, dim=-1)\n prob_sc_sa[:, i_beam, :] = prob_sa\n\n prob_sc_selected = prob_sc[range(bS), pr_sc] # [B]\n prob_sca[:, i_beam, :] = (prob_sa.t() * prob_sc_selected).t()\n # [mcL, B] * [B] -> [mcL, B] (element-wise multiplication)\n # [mcL, B] -> [B, mcL]\n\n # Calculate the dimension of tensor\n # tot_dim = len(prob_sca.shape)\n\n # First flatten to 1-d\n idxs = topk_multi_dim(torch.tensor(prob_sca), n_topk=beam_size, batch_exist=True)\n # Now as sc_idx is already sorted, re-map them properly.\n\n idxs = remap_sc_idx(idxs, pr_sc_beam) # [sc_beam_idx, sa_idx] -> [sc_idx, sa_idx]\n idxs_arr = array(idxs)\n # [B, beam_size, remainig dim]\n # idxs[b][0] gives first probable [sc_idx, sa_idx] pairs.\n # idxs[b][1] gives of second.\n\n # Calculate prob_sca, a joint probability\n beam_idx_sca = [0] * bS\n beam_meet_the_final = [False] * bS\n while True:\n pr_sc = idxs_arr[range(bS), beam_idx_sca, 0]\n pr_sa = idxs_arr[range(bS), beam_idx_sca, 1]\n\n # map index properly\n\n check = check_sc_sa_pairs(tb, pr_sc, pr_sa)\n\n if sum(check) == bS:\n break\n else:\n for b, check1 in enumerate(check):\n if not check1: # wrong pair\n beam_idx_sca[b] += 1\n if beam_idx_sca[b] >= beam_size:\n beam_meet_the_final[b] = True\n beam_idx_sca[b] -= 1\n else:\n beam_meet_the_final[b] = True\n\n if sum(beam_meet_the_final) == bS:\n break\n\n\n # Now pr_sc, pr_sa are properly predicted.\n pr_sc_best = list(pr_sc)\n pr_sa_best = list(pr_sa)\n\n # Now, Where-clause beam search.\n s_wn = self.wnp(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, show_p_wn=show_p_wn)\n prob_wn = F.softmax(s_wn, dim=-1).detach().to('cpu').numpy()\n\n # Found \"executable\" most likely 4(=max_num_of_conditions) where-clauses.\n # wc\n s_wc = self.wcp(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, show_p_wc=show_p_wc, penalty=True)\n prob_wc = F.sigmoid(s_wc).detach().to('cpu').numpy()\n # pr_wc_sorted_by_prob = pred_wc_sorted_by_prob(s_wc)\n\n # get max_wn # of most probable columns & their prob.\n pr_wn_max = [self.max_wn]*bS\n pr_wc_max = pred_wc(pr_wn_max, s_wc) # if some column do not have executable where-claouse, omit that column\n prob_wc_max = zeros([bS, self.max_wn])\n for b, pr_wc_max1 in enumerate(pr_wc_max):\n prob_wc_max[b,:] = prob_wc[b,pr_wc_max1]\n\n # get most probable max_wn where-clouses\n # wo\n s_wo_max = self.wop(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, wn=pr_wn_max, wc=pr_wc_max, show_p_wo=show_p_wo)\n prob_wo_max = F.softmax(s_wo_max, dim=-1).detach().to('cpu').numpy()\n # [B, max_wn, n_cond_op]\n\n pr_wvi_beam_op_list = []\n prob_wvi_beam_op_list = []\n for i_op in range(self.n_cond_ops-1):\n pr_wo_temp = [ [i_op]*self.max_wn ]*bS\n # wv\n s_wv = self.wvp(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, wn=pr_wn_max, wc=pr_wc_max, wo=pr_wo_temp, show_p_wv=show_p_wv)\n prob_wv = F.softmax(s_wv, dim=-2).detach().to('cpu').numpy()\n\n # prob_wv\n pr_wvi_beam, prob_wvi_beam = pred_wvi_se_beam(self.max_wn, s_wv, beam_size)\n pr_wvi_beam_op_list.append(pr_wvi_beam)\n prob_wvi_beam_op_list.append(prob_wvi_beam)\n # pr_wvi_beam = [B, max_wn, k_logit**2 [st, ed] paris]\n\n # pred_wv_beam\n\n # Calculate joint probability of where-clause\n # prob_w = [batch, wc, wo, wv] = [B, max_wn, n_cond_op, n_pairs]\n n_wv_beam_pairs = prob_wvi_beam.shape[2]\n prob_w = zeros([bS, self.max_wn, self.n_cond_ops-1, n_wv_beam_pairs])\n for b in range(bS):\n for i_wn in range(self.max_wn):\n for i_op in range(self.n_cond_ops-1): # do not use final one\n for i_wv_beam in range(n_wv_beam_pairs):\n # i_wc = pr_wc_max[b][i_wn] # already done\n p_wc = prob_wc_max[b, i_wn]\n p_wo = prob_wo_max[b, i_wn, i_op]\n p_wv = prob_wvi_beam_op_list[i_op][b, i_wn, i_wv_beam]\n\n prob_w[b, i_wn, i_op, i_wv_beam] = p_wc * p_wo * p_wv\n\n # Perform execution guided decoding\n conds_max = []\n prob_conds_max = []\n # while len(conds_max) < self.max_wn:\n idxs = topk_multi_dim(torch.tensor(prob_w), n_topk=beam_size, batch_exist=True)\n # idxs = [B, i_wc_beam, i_op, i_wv_pairs]\n\n # Construct conds1\n for b, idxs1 in enumerate(idxs):\n conds_max1 = []\n prob_conds_max1 = []\n for i_wn, idxs11 in enumerate(idxs1):\n i_wc = pr_wc_max[b][idxs11[0]]\n i_op = idxs11[1]\n wvi = pr_wvi_beam_op_list[i_op][b][idxs11[0]][idxs11[2]]\n\n # get wv_str\n temp_pr_wv_str, _ = convert_pr_wvi_to_string([[wvi]], [nlu_t[b]], [nlu_wp_t[b]], [wp_to_wh_index[b]], [nlu[b]])\n merged_wv11 = merge_wv_t1_eng(temp_pr_wv_str[0][0], nlu[b])\n conds11 = [i_wc, i_op, merged_wv11]\n\n prob_conds11 = prob_w[b, idxs11[0], idxs11[1], idxs11[2] ]\n\n # test execution\n # print(nlu[b])\n # print(tb[b]['id'], tb[b]['types'], pr_sc[b], pr_sa[b], [conds11])\n pr_ans = engine.execute(tb[b]['id'], pr_sc[b], pr_sa[b], [conds11])\n if bool(pr_ans):\n # pr_ans is not empty!\n conds_max1.append(conds11)\n prob_conds_max1.append(prob_conds11)\n conds_max.append(conds_max1)\n prob_conds_max.append(prob_conds_max1)\n\n # May need to do more exhuastive search?\n # i.e. up to.. getting all executable cases.\n\n # Calculate total probability to decide the number of where-clauses\n pr_sql_i = []\n prob_wn_w = []\n pr_wn_based_on_prob = []\n\n for b, prob_wn1 in enumerate(prob_wn):\n max_executable_wn1 = len(conds_max[b])\n prob_wn_w1 = []\n prob_wn_w1.append(prob_wn1[0]) # wn=0 case.\n for i_wn in range(max_executable_wn1):\n prob_wn_w11 = prob_wn1[i_wn+1] * prob_conds_max[b][i_wn]\n prob_wn_w1.append(prob_wn_w11)\n pr_wn_based_on_prob.append(argmax(prob_wn_w1))\n prob_wn_w.append(prob_wn_w1)\n\n pr_sql_i1 = {'agg': pr_sa_best[b], 'sel': pr_sc_best[b], 'conds': conds_max[b][:pr_wn_based_on_prob[b]]}\n pr_sql_i.append(pr_sql_i1)\n # s_wv = [B, max_wn, max_nlu_tokens, 2]\n return prob_sca, prob_w, prob_wn_w, pr_sc_best, pr_sa_best, pr_wn_based_on_prob, pr_sql_i\n\n\ndef Loss_sn(s_sn, g_sn):\n loss = F.cross_entropy(s_sn, torch.tensor(g_sn).to(device))\n return loss\n\n\ndef Loss_sc(s_sc, g_sc):\n # Construct index matrix\n bS, max_h_len = s_sc.shape\n im = torch.zeros([bS, max_h_len]).to(device)\n for b, g_sc1 in enumerate(g_sc):\n for g_sc11 in g_sc1:\n im[b, g_sc11] = 1.0\n # Construct prob.\n p = F.sigmoid(s_sc)\n loss = F.binary_cross_entropy(p, im)\n\n return loss\n\n\ndef Loss_sa(s_sa, g_sn, g_sa):\n loss = 0\n for b, g_wn1 in enumerate(g_sn):\n if g_wn1 == 0:\n continue\n g_wo1 = g_sa[b]\n s_wo1 = s_sa[b]\n loss += F.cross_entropy(s_wo1[:g_wn1], torch.tensor(g_wo1).to(device))\n\n return loss\n\n\ndef Loss_wn(s_wn, g_wn):\n loss = F.cross_entropy(s_wn, torch.tensor(g_wn).to(device))\n\n return loss\n\n\ndef Loss_wc(s_wc, g_wc):\n\n # Construct index matrix\n bS, max_h_len = s_wc.shape\n im = torch.zeros([bS, max_h_len]).to(device)\n for b, g_wc1 in enumerate(g_wc):\n for g_wc11 in g_wc1:\n im[b, g_wc11] = 1.0\n # Construct prob.\n p = F.sigmoid(s_wc)\n loss = F.binary_cross_entropy(p, im)\n\n return loss\n\n\ndef Loss_wo(s_wo, g_wn, g_wo):\n\n # Construct index matrix\n loss = 0\n for b, g_wn1 in enumerate(g_wn):\n if g_wn1 == 0:\n continue\n g_wo1 = g_wo[b]\n s_wo1 = s_wo[b]\n loss += F.cross_entropy(s_wo1[:g_wn1], torch.tensor(g_wo1).to(device))\n\n return loss\n\n\ndef Loss_wv_se(s_wv, g_wn, g_wo, g_wvi):\n \"\"\"\n s_wv: [bS, 4, mL, 2], 4 stands for maximum # of condition, 2 tands for start & end logits.\n g_wvi: [ [1, 3, 2], [4,3] ] (when B=2, wn(b=1) = 3, wn(b=2) = 2).\n \"\"\"\n loss = 0\n # g_wvi = torch.tensor(g_wvi).to(device)\n for b, g_wvi1 in enumerate(g_wvi):\n # for i_wn, g_wvi11 in enumerate(g_wvi1):\n\n g_wn1 = g_wn[b]\n g_wo1 = g_wo[b]\n\n flag = True\n\n if g_wn1 == 0:\n flag = False\n\n # todo: work for comparision\n for i in g_wo1:\n if i not in [2, 3, 4, 5, 6, 7]:\n flag = False\n\n if flag is not True:\n continue\n\n g_wvi1 = torch.tensor(g_wvi1).to(device)\n g_st1 = g_wvi1[:, 0]\n g_ed1 = g_wvi1[:, 1]\n # loss from the start position\n loss += F.cross_entropy(s_wv[b, :g_wn1, :, 0], g_st1)\n\n # print(\"st_login: \", s_wv[b,:g_wn1,:,0], g_st1, loss)\n # loss from the end position\n loss += F.cross_entropy(s_wv[b, :g_wn1, :, 1], g_ed1)\n # print(\"ed_login: \", s_wv[b,:g_wn1,:,1], g_ed1, loss)\n\n return loss\n\n\ndef Loss_sw_se(s_sn, s_sc, s_sa, s_wn, s_wc, s_wo, s_wv, g_sn, g_sc, g_sa, g_wn, g_wc, g_wo, g_wvi):\n \"\"\"\n\n :param s_wv: score [ B, n_conds, T, score]\n :param g_wn: [ B ]\n :param g_wvi: [B, conds, pnt], e.g. [[[0, 6, 7, 8, 15], [0, 1, 2, 3, 4, 15]], [[0, 1, 2, 3, 16], [0, 7, 8, 9, 16]]]\n :return:\n \"\"\"\n loss = 0\n loss += Loss_sn(s_sn, g_sn)\n loss += Loss_sc(s_sc, g_sc)\n loss += Loss_sa(s_sa, g_sn, g_sa)\n loss += Loss_wn(s_wn, g_wn)\n loss += Loss_wc(s_wc, g_wc)\n loss += Loss_wo(s_wo, g_wn, g_wo)\n loss += Loss_wv_se(s_wv, g_wn, g_wo, g_wvi)\n\n return loss\n","sub_path":"scripts/model/nl2sql/nl2sql.py","file_name":"nl2sql.py","file_ext":"py","file_size_in_byte":14433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"539311397","text":"#!/usr/bin/env python\n\n\"\"\"\nlockdown.py updates release.yaml files\n\nThis script does:\n* Parses those external image and adds sha value to them in\n the release.yaml file\n\"\"\"\n\nimport argparse\nimport os\nimport re\nimport string\nimport sys\nimport docker\nfrom typing import List\n\ndef scan_release(omit: List[str], path: str) -> List[str]:\n \"\"\"Extracts built images from the release.yaml at path\n Args:\n omit: The list of images that are omitted from the static image list\n path: The path to the file (release.yaml) that will contain the built images\n Returns:\n list of the images parsed from the file\n \"\"\"\n print(\"scan_release\")\n images = []\n with open(path) as f:\n print(\"path: \" + path)\n for line in f:\n match = re.search(\"image:\" + \".*\" + \"latest\", line)\n if match:\n exclude = False\n for image in omit:\n if image in line:\n exclude = True\n if not(exclude):\n images.append(match.group(0).replace(\"image:\", \"\").strip())\n return images\n\ndef lockdown_image(images: List[str]) -> List[str]:\n \"\"\"Lockdown images with the sha value\n Args:\n images: The list of images that are lockdowned\n Returns:\n list of the lockdowned images\n \"\"\"\n print(\"lockdown_image\")\n taggedimages = []\n client = docker.DockerClient(base_url='unix://var/run/docker.sock')\n for image in images:\n print(\"image:\" + image)\n imageobj = client.images.pull(image)\n taggedimages.append(imageobj.attrs[\"RepoDigests\"][0])\n return taggedimages\n\ndef replace_images(org: List[str], new: List[str], path: str):\n \"\"\"Replace original images with new images in the release.yaml at path\n Args:\n org: The list of original images that are replaced by the new images\n new: The list of new images\n path: The path to the file (release.yaml) that will contain the built images\n \"\"\"\n print(\"replace_image\")\n with open(path) as f:\n with open(path+\".temp\", \"x\") as ff:\n for line in f:\n newline = line\n i = 0\n for o in org:\n match = re.search(o , line)\n if match:\n newline = line.replace(o, new[i])\n i = i + 1\n ff.write(newline)\n os.replace(path+\".temp\", path)\n\nif __name__ == \"__main__\":\n arg_parser = argparse.ArgumentParser(\n description=\"Lockdown external images with sha in a release.yaml\")\n arg_parser.add_argument(\"--path\", type=str, required=True,\n help=\"Path to the release.yaml\")\n arg_parser.add_argument(\"--omit\", type=str, required=True,\n help=\"String prefix which is omitted from the external images\")\n args = arg_parser.parse_args()\n\n images = scan_release(args.omit.split(\",\") , args.path)\n taggedimages = lockdown_image(images)\n replace_images(images, taggedimages, args.path)\n\n print(\"Done.\\n\")\n\n","sub_path":"tekton/scripts/lockdown.py","file_name":"lockdown.py","file_ext":"py","file_size_in_byte":3071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"252633269","text":"\"\"\"https://github.com/django-helpdesk/django-helpdesk/issues/348\nMust have username/passwork credentials for sender\nUse a 'Reply-To' header to specify the party who initiated the inquiry\"\"\"\n\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.conf import settings\n\nfrom django.shortcuts import render\n\nfrom django.core.mail import BadHeaderError, send_mail\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import redirect, render\n\nfrom .forms import ContactForm\n\ndef email(request):\n if request.method == 'GET':\n form = ContactForm()\n else:\n form = ContactForm(request.POST)\n if form.is_valid():\n subject = 'Website Inquiry: ' # subject prefix\n subject = subject + form.cleaned_data['subject'] # append user input\n #from_email = form.cleaned_data['from_email']\n headers = {'Reply-To': form.cleaned_data['from_email']}\n message = 'Website Inquiry:'\n message = '\\n'.join([message, '\\n', form.cleaned_data['message']])\n #message = message.join(['\\n', '\\n', form.cleaned_data['message']])\n #message = message + form.cleaned_data['message']\n try:\n #send_mail(subject, message, from_email, ['admin@example.com'])\n msg = EmailMultiAlternatives(subject, message, '00mstacy@gmail.com', ['00mstacy@gmail.com',], headers=headers)\n msg.send(fail_silently=False)\n except BadHeaderError:\n return HttpResponse('Invalid header found.')\n return redirect('success')\n return render(request, \"email.html\", {'form': form})\n\ndef success(request):\n return HttpResponse('Success! Thank you for your message.')\n","sub_path":"send_email/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"597026544","text":"\n\nfrom xai.brain.wordbase.nouns._science import _SCIENCE\n\n#calss header\nclass _SCIENCES(_SCIENCE, ):\n\tdef __init__(self,): \n\t\t_SCIENCE.__init__(self)\n\t\tself.name = \"SCIENCES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"science\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_sciences.py","file_name":"_sciences.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"570647376","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .models import *\nimport os\nimport urllib.request\nfrom django.conf import settings\nfrom django.views.decorators.csrf import csrf_exempt\nimport ast\nfrom django.http import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom PIL import Image\nfrom math import sqrt\nfrom collections import Counter, defaultdict\nfrom .google_ocr import *\nimport time\nimport sys\nimport subprocess\nfrom random import randint\nimport json\nimport csv\nimport boto3\nfrom random import randint\nfrom time import sleep\n\ndef syncImages():\n streetviewImages = StreetviewImage.objects.all()\n for streetviewImage in streetviewImages:\n if streetviewImage.image_is_set is False:\n streetviewImage.check_if_image_is_set()\n else:\n print(str(streetviewImage.pk) + \" was previously set\")\n\ndef saveImages_async_deprecated():\n # parameters\n xdim = 640\n ydim = 640\n count_continuous_error = 0\n\n # get mapPoints\n mapPoints = MapPoint.objects.all()\n for mapPoint in mapPoints:\n\n # check if we should create the image\n # if we don't have exactly two streetviewImage objects, then we need to (re)create the images\n streetviewImages = mapPoint.streetviewimage_set.all()\n if len(streetviewImages) != 2:\n streetviewImages.delete()\n mapPoint.createStreetviewImages()\n recreate_image = True\n # if we have previously flagged streetviewImage objects as set, then we don't need to recreate\n elif streetviewImages[0].image_is_set and streetviewImages[1].image_is_set:\n recreate_image = False\n #print(\"skipping \" + str(streetviewImages[0].pk) + \" and \" + str(streetviewImages[1].pk))\n # check if we need to recreate explicitly\n elif streetviewImages[0].check_if_image_is_set() and streetviewImages[1].check_if_image_is_set():\n streetviewImages[0].image_is_set = True\n streetviewImages[0].save()\n streetviewImages[1].image_is_set = True\n streetviewImages[1].save()\n recreate_image = False\n print(\"skipping \" + str(streetviewImages[0].pk) + \" and \" + str(streetviewImages[1].pk))\n # we need to recreate image\n else:\n recreate_image = True\n\n try:\n if recreate_image:\n for streetviewImage in mapPoint.streetviewimage_set.all():\n sleep(randint(0,6))\n if settings.USE_S3:\n image_name = 'temp6.jpg'\n fi = saveConcatImage(xdim,ydim,mapPoint.latitude,mapPoint.longitude, \\\n streetviewImage.fov,streetviewImage.heading, \\\n streetviewImage.pitch, image_name)\n # upload image to s3\n s3 = boto3.client('s3', \\\n aws_access_key_id=settings.AWS_ACCESS_KEY,\n aws_secret_access_key=settings.AWS_SECRET, \\\n )\n s3.upload_file(fi, settings.AWS_BUCKET_NAME, streetviewImage.image_name())\n streetviewImage.image_is_set = True\n streetviewImage.save()\n print(streetviewImage.image_name() + ' uploaded to s3')\n else:\n image_name = streetviewImage.image_name()\n fi = saveConcatImage(xdim,ydim,mapPoint.latitude,mapPoint.longitude, \\\n streetviewImage.fov,streetviewImage.heading, \\\n streetviewImage.pitch, image_name)\n streetviewImage.image_is_set = True\n streetviewImage.save()\n print(streetviewImage.image_name() + ' saved')\n count_continuous_error = 0\n except BaseException as e:\n print(str(e))\n count_continuous_error += 1\n print(\"continuous error = \" + str(count_continuous_error))\n if count_continuous_error > 3:\n break\n else:\n continue\n\n\n\n\n# saves concatenated image from google streetview to local disk\ndef saveImages_async_deprecated():\n # get mapPoints\n mapPoints = MapPoint.objects.all()\n xdim = 640\n ydim = 640\n pitch=0\n for mapPoint in mapPoints:\n # check if image associated here to prevent worker collisions\n if mapPoint.streetviewimage_set.all().count() != 0:\n continue\n\n # fov right is wider because we are nearer to the right side of the road.\n for rl in [{'heading':mapPoint.photographerHeading+90,'fov':35}, \\\n {'heading':mapPoint.photographerHeading-90,'fov':22.5}]:\n # save object\n streetviewImage = StreetviewImage(mapPoint=mapPoint, \\\n heading=rl['heading'], \\\n fov=rl['fov'], \\\n pitch=pitch)\n streetviewImage.save()\n\n # make image, save local\n\n if settings.USE_S3:\n image_name = 'temp6.jpg'\n fi = saveConcatImage(xdim,ydim,mapPoint.latitude,mapPoint.longitude,rl['fov'],rl['heading'],pitch,image_name)\n # upload image to s3\n s3 = boto3.client('s3', \\\n aws_access_key_id=settings.AWS_ACCESS_KEY,\n aws_secret_access_key=settings.AWS_SECRET, \\\n )\n s3.upload_file(fi, settings.AWS_BUCKET_NAME, streetviewImage.image_name())\n print(streetviewImage.image_name() + ' uploaded to s3')\n else:\n image_name = streetviewImage.image_name()\n fi = saveConcatImage(xdim,ydim,mapPoint.latitude,mapPoint.longitude,rl['fov'],rl['heading'],pitch,image_name)\n print(streetviewImage.image_name() + ' saved')\n\ndef saveConcatImage(xdim,ydim,latitude,longitude,fov,heading,pitch,image_name):\n #saveImage2(xdim,ydim,latitude,longitude,fov,heading-(2*fov-0.5),pitch,'temp1.jpg')\n saveImage2(xdim,ydim,latitude,longitude,fov,heading-(fov-0.5),pitch,'temp2.jpg')\n saveImage2(xdim,ydim,latitude,longitude,fov,heading ,pitch,'temp3.jpg')\n saveImage2(xdim,ydim,latitude,longitude,fov,heading+(fov-0.5),pitch,'temp4.jpg')\n #saveImage2(xdim,ydim,latitude,longitude,fov,heading+(2*fov-0.5),pitch,'temp5.jpg')\n\n #I1 = Image.open(os.path.join(settings.MEDIA_ROOT,'temp1.jpg'))\n I2 = Image.open(os.path.join(settings.MEDIA_ROOT,'temp2.jpg'))\n I3 = Image.open(os.path.join(settings.MEDIA_ROOT,'temp3.jpg'))\n I4 = Image.open(os.path.join(settings.MEDIA_ROOT,'temp4.jpg'))\n #I5 = Image.open(os.path.join(settings.MEDIA_ROOT,'temp5.jpg'))\n\n # crop\n #I1 = I1.crop((0, 0, I1.size[0], I1.size[1]-20))\n I2 = I2.crop((0, 0, I2.size[0], I2.size[1]-20))\n I3 = I3.crop((0, 0, I3.size[0], I3.size[1]-20))\n I4 = I4.crop((0, 0, I4.size[0], I4.size[1]-20))\n #I5 = I5.crop((0, 0, I5.size[0], I5.size[1]-20))\n\n\n I_concatenate = concatenateImage(I2,I3,'left')\n #I_concatenate = concatenateImage(I1,I_concatenate,'left')\n I_concatenate = concatenateImage(I_concatenate,I4,'right')\n #I_concatenate = concatenateImage(I_concatenate,I5,'right')\n\n # crop x-dimension ( 3600x620 to 2500x620 ) so that textDetector doesn't run out of memory\n #final_dimx = 2500\n #width, height = I_concatenate.size\n #I_concatenate = I_concatenate.crop(( round(width/2- final_dimx/2) , 0, round(width/2+ final_dimx/2), height))\n\n fi_path = os.path.join(settings.MEDIA_ROOT,image_name)\n I_concatenate.save(fi_path)\n #\n return fi_path\n\ndef concatenateImage(I_left, I_right, shiftRightOrLeft):\n # get column of right-most pixels for I_left and left-most pixels for I_right\n column_left = get_column(I_left,'last')\n column_right = get_column(I_right,'first')\n # find shift that minimizes distance\n dimy = len(column_left)\n shift_range = int(dimy/6) # decrease to speed up\n min_average_distance = float(\"inf\")\n shift = 0\n for i in range(-shift_range,shift_range):\n sum_distance = 0\n count = 0\n for j in range(0,dimy):\n if j+i<0 or j+i>=dimy:\n continue\n else:\n v1 = column_left[j]\n v2 = column_right[j+i]\n distance = sqrt( (v1[0]-v2[0])**2 + (v1[1]-v2[1])**2 + (v1[2]-v2[2])**2 )\n sum_distance += distance\n count = count + 1\n average_distance = sum_distance/count\n if average_distance < min_average_distance:\n min_average_distance=average_distance\n shift=i\n # shift right image to match left image\n if shiftRightOrLeft == 'right':\n I_right_shift = Image.new('RGB', (I_right.size[0], I_right.size[1]))\n I_right_shift.paste(I_right, (0,-shift))\n # concatenate right and left image\n dimy = max(I_left.size[1],I_right_shift.size[1])\n dimx = I_left.size[0]+I_right_shift.size[0]\n I_concatenate = Image.new('RGB', (dimx,dimy))\n I_concatenate.paste(I_left, (0,0))\n I_concatenate.paste(I_right_shift, (I_left.size[0],0))\n elif shiftRightOrLeft == 'left':\n I_left_shift = Image.new('RGB', (I_left.size[0], I_left.size[1]))\n I_left_shift.paste(I_left, (0,shift))\n # concatenate right and left image\n dimy = max(I_right.size[1],I_left_shift.size[1])\n dimx = I_right.size[0]+I_left_shift.size[0]\n I_concatenate = Image.new('RGB', (dimx,dimy))\n I_concatenate.paste(I_left_shift, (0,0))\n I_concatenate.paste(I_right, (I_left_shift.size[0],0))\n return I_concatenate\n\ndef get_column(I,firstOrLast):\n pix = I.load()\n dimx = I.size[0]\n dimy = int(I.size[1])\n column = [None]*dimy\n for i in range(0,dimy):\n if firstOrLast == 'first':\n column[i] = pix[0,i]\n elif firstOrLast == 'last':\n column[i] = pix[dimx-1,i]\n return column\n\nclass AppURLopener(urllib.request.FancyURLopener):\n version = \"Mozilla/5.0\"\n\ndef saveImage2(xdim,ydim,latitude,longitude,fov,heading,pitch,filename):\n url = \"http://maps.googleapis.com/maps/api/streetview?size=%dx%d&location=%f,%f&fov=%d&heading=%f&pitch=%f\"%(xdim,ydim,latitude,longitude,fov,heading,pitch) \\\n + '&key='+ settings.GOOGLE_MAPS_API_KEY\n\n fi_path = os.path.join(settings.MEDIA_ROOT,filename)\n\n urllib._urlopener = AppURLopener()\n print(url)\n #urllib.URLopener.version = 'Mozilla/5.0' # (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 SE 2.X MetaSr 1.0\n data = urllib.request.urlretrieve(url, fi_path)\n","sub_path":"streetviewInterface/mySite/ImagePicker/views_saveImage.py","file_name":"views_saveImage.py","file_ext":"py","file_size_in_byte":11100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"582657291","text":"# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html\n# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE\nfrom typing import Tuple\n\n__version__ = \"2.11.1\"\n\n\ndef get_numversion_from_version(v: str) -> Tuple:\n \"\"\"Kept for compatibility reason\n\n See https://github.com/PyCQA/pylint/issues/4399\n https://github.com/PyCQA/pylint/issues/4420,\n \"\"\"\n v = v.replace(\"pylint-\", \"\")\n version = []\n for n in v.split(\".\")[0:3]:\n try:\n version.append(int(n))\n except ValueError:\n num = \"\"\n for c in n:\n if c.isdigit():\n num += c\n else:\n break\n try:\n version.append(int(num))\n except ValueError:\n version.append(0)\n while len(version) != 3:\n version.append(0)\n return tuple(version)\n\n\nnumversion = get_numversion_from_version(__version__)\n","sub_path":".venv/lib/python3.8/site-packages/pylint/__pkginfo__.py","file_name":"__pkginfo__.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"162213196","text":"import numpy as np\n\nimport scipy.sparse as sparse\nimport scipy.sparse.linalg as sp_linalg\n\n\ndef discretesample(p, n):\n \"\"\"independently draws n samples (with replacement) from the\n distribution specified by p, where p is a probability array\n whose elements sum to 1.\"\"\"\n return np.random.choice(len(p), n, p=p)\n\n\ndef similarity(x1, x2):\n norm_x1 = np.linalg.norm(x1)\n norm_x2 = np.linalg.norm(x2)\n return np.dot(x1, x2) / (norm_x1 * norm_x2)\n\n\ndef calc_centroid(X):\n return np.mean(X, 0)\n\n\ndef count_diff(a, prev_a):\n diff = np.abs(a - prev_a)\n diff[diff > 1] = 1\n\n return np.sum(diff)\n\n\ndef k_means_sphere(X, k, max_iter=100):\n # kmeans++ init\n n = X.shape[0]\n\n def kmeanspp(_X, _k):\n n_inst = _X.shape[0]\n dim = _X.shape[1]\n\n # select initial centroids\n C = np.zeros((_k, dim)) # k++ means\n rands = np.random.randint(0, n_inst)\n C[0, :] = _X[rands]\n\n probs = np.zeros(n_inst)\n\n for centroidN in range(1, _k):\n # compute probabilities for new ctroid\n for recN in range(0, n_inst):\n rec = _X[recN, :]\n\n # compute distance to nearest centroid\n nearest_dist = np.inf\n for exist_centroidN in range(0, centroidN):\n centroid = C[exist_centroidN, :]\n clust_rec_sim = similarity(rec, centroid)\n clust_rec_dist = 0.5 * (1 - clust_rec_sim)\n\n if clust_rec_dist < nearest_dist:\n nearest_dist = clust_rec_dist\n # the probability is proportional to d^2\n probs[recN] = nearest_dist * nearest_dist\n norm_factor = 1.0 / np.sum(probs)\n probs = probs * norm_factor\n\n chosenN = discretesample(probs, 1)[0]\n C[centroidN, :] = _X[chosenN, :]\n print('Chosen centroid {}, probability: {}, max probability: {} '.format(chosenN, probs[centroidN],\n probs.max()))\n return C\n\n C = kmeanspp(X, k)\n prev_assignment = np.zeros(n)\n assignment = np.zeros(n)\n\n change = True\n iterN = 0\n\n while change and iterN < max_iter:\n iterN += 1\n lost_centroid = True\n\n while lost_centroid:\n lost_centroid = False\n\n # assign vectors\n for recN in range(0, n):\n xi = X[recN, :]\n best_idx = -1\n best_sim = np.NINF\n\n for clustN in range(0, k):\n sim = similarity(xi, C[clustN, :])\n if sim > best_sim:\n best_idx = clustN\n best_sim = sim\n\n assignment[recN] = best_idx\n\n # recompute centroids\n for clustN in range(0, k):\n assigned_idxs = assignment == clustN\n\n if assigned_idxs.astype(dtype=int).sum() > 0:\n Yn = X[assigned_idxs, :]\n C[clustN, :] = calc_centroid(Yn)\n else:\n C = kmeanspp(X, k)\n lost_centroid = True\n print(\"Lost a centroid, reinitialized at {}\".format(iterN))\n break\n\n diff = count_diff(assignment, prev_assignment)\n change = diff > 0\n tmp = prev_assignment\n prev_assignment = assignment\n assignment = tmp\n\n return assignment\n\n\ndef k_means_sphere_vectorized(X, k, max_iter=100, debug_assert=False):\n print('running k-means')\n\n # dimensions and other variables\n n = X.shape[0]\n d = X.shape[1]\n\n range_n = range(n)\n range_k = range(k)\n\n # kmeans++ init\n def kmeanspp(_X, _X_norm, _k):\n n_inst = _X_norm.shape[0]\n dim = _X_norm.shape[1]\n\n # select initial centroids\n C = np.empty((_k, dim)) # k++ means\n C_norm_t = np.empty((dim, _k))\n\n rands = np.random.randint(0, n_inst)\n C[0, :] = _X[rands, :]\n C_norm_t[:, 0] = _X_norm[rands, :]\n\n select_prob_vec = np.empty(n_inst)\n mn_clust_dist_vec = np.empty(n_inst)\n\n for centroidN in range(1, _k):\n # compute probabilities for the new centroid\n C_curr_norm_t = C_norm_t[:, :centroidN]\n\n # compute the distance as 0.5*(1 - sim)\n ftrv_clust_dist_mat = np.dot(_X_norm, C_curr_norm_t)\n np.subtract(1, ftrv_clust_dist_mat, out=ftrv_clust_dist_mat)\n np.multiply(0.5, ftrv_clust_dist_mat, out=ftrv_clust_dist_mat)\n\n # for each of the examples compute the distance to the nearest centroid\n np.min(ftrv_clust_dist_mat, axis=1, out=mn_clust_dist_vec)\n\n # the probability of selecting the instance should be\n # proportional to d^2\n np.multiply(mn_clust_dist_vec, mn_clust_dist_vec, select_prob_vec)\n\n prob_sum = np.sum(select_prob_vec)\n if prob_sum < 1e-12:\n np.multiply(np.ones(n_inst), 1 / n_inst, out=select_prob_vec)\n prob_sum = n_inst\n\n norm_factor = 1.0 / prob_sum\n np.multiply(select_prob_vec, norm_factor, out=select_prob_vec)\n\n # sample the new centroid according to the computed distribution\n chosenN = discretesample(select_prob_vec, 1)[0]\n C[centroidN, :] = _X[chosenN, :]\n C_norm_t[:, centroidN] = _X_norm[chosenN, :]\n\n return C\n\n # normalize the rows of X so it will be faster to compute the cosine\n # similarity\n one_by_row_norm_X_vec = np.linalg.norm(X, axis=1)\n np.reciprocal(one_by_row_norm_X_vec, out=one_by_row_norm_X_vec)\n Dx = sparse.csr_matrix((one_by_row_norm_X_vec, (range_n, range_n)), shape=(n, n))\n X_norm = Dx.dot(X)\n del one_by_row_norm_X_vec\n del Dx\n\n if debug_assert:\n # check that the rows of X are of unit length\n row_norm_vec = np.linalg.norm(X_norm, axis=1)\n assert np.linalg.norm(np.ones(n) - row_norm_vec) < 1e-7\n assert isinstance(X_norm, np.ndarray)\n\n C = kmeanspp(X, X_norm, k)\n prev_assignment = -np.ones(n, dtype=int)\n assignment_vec = np.empty(n, dtype=int)\n assign_diff_vec = np.empty(n, dtype=int)\n\n clust_sim_ftrvv = np.empty((n, k))\n clust_sum_vec = np.empty(d)\n\n change = True\n iterN = 0\n\n while change and iterN < max_iter:\n iterN += 1\n lost_centroid = True\n\n if iterN % 10 == 0:\n print('iterN: ' + str(iterN))\n\n # normalize the centroids to make the computation of the cosine\n # similarity faster\n inv_row_norm_C_vec = np.linalg.norm(C, axis=1)\n np.reciprocal(inv_row_norm_C_vec, out=inv_row_norm_C_vec)\n D_one_by_norm = sparse.csr_matrix((inv_row_norm_C_vec, (range_k, range_k)), shape=(k, k))\n C_norm_t = D_one_by_norm.dot(C).T\n\n del inv_row_norm_C_vec\n del D_one_by_norm\n\n if debug_assert:\n # check that the columns of C are of unit length\n col_norm_vec = np.linalg.norm(C_norm_t, axis=0)\n assert np.linalg.norm(np.ones(k) - col_norm_vec) < 1e-7\n assert isinstance(C_norm_t, np.ndarray)\n\n while lost_centroid:\n lost_centroid = False\n\n # assign vectors\n np.dot(X_norm, C_norm_t, out=clust_sim_ftrvv)\n # the assignment is the index of the maximal value\n # in each row\n np.argmax(clust_sim_ftrvv, axis=1, out=assignment_vec)\n\n # recompute centroids\n for clustN in range(0, k):\n assigned_idxs = assignment_vec == clustN\n\n clust_size = np.sum(assigned_idxs)\n\n if clust_size > 0:\n np.dot(assigned_idxs, X, out=clust_sum_vec)\n np.multiply(1 / clust_size, clust_sum_vec, out=C[clustN, :])\n # centroid_ftrvv = (1 / clust_size) * clust_sum_vec\n # C[clustN, :] = centroid_vec\n else:\n C = kmeanspp(X_norm, k)\n lost_centroid = True\n print(\"Lost a centroid, reinitialized at {}\".format(iterN))\n break\n\n # check if the assignments changed\n np.subtract(assignment_vec, prev_assignment, out=assign_diff_vec)\n np.abs(assign_diff_vec, out=assign_diff_vec)\n change = np.sum(assign_diff_vec) > 0\n\n # swap the assignment and prev_assignment vectors\n tmp = prev_assignment\n prev_assignment = assignment_vec\n assignment_vec = tmp\n\n return assignment_vec\n","sub_path":"src/modules/partitioning/k_means_sphere.py","file_name":"k_means_sphere.py","file_ext":"py","file_size_in_byte":8627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"47349299","text":"from torchvision.ops import nms as nms_torch\nfrom ..core import bbox_overlaps\nimport torch\n\ndef batched_iou_nms(bboxes, scores, locs, labels, iou_threshold, score_thr=None):\n \"\"\"IoU guided NMS, bboxes are sorted by iou, score of the current bbox is taking the max of \n scores of all the bboxes suppressed by the bbox.\n \n Args:\n bboxes (Tensor): shape (n, 4)\n scores (Tensor): shape (n,), classification score\n locs (Tensor): shape(n,) iou score\n labels (Tensor): label of bboxes, help to do batched nms\n iou_threshold (float): iou threshold\n score_thr (float): filter scores belowing this number\"\"\"\n filt_mask = scores >= score_thr\n if filt_mask.sum().item() == 0:\n return \\\n bboxes.new_empty(0, 4), \\\n scores.new_empty(0), \\\n locs.new_empty(0), \\\n labels.new_empty(0)\n bboxes = bboxes[filt_mask]\n scores = scores[filt_mask]\n locs = locs[filt_mask]\n labels = labels[filt_mask]\n nms_bboxes = bboxes + (labels * (bboxes.max() + 1)).view(-1, 1)\n \n keep = nms_torch(nms_bboxes, locs, iou_threshold)\n keep_bboxes = nms_bboxes[keep]\n overlaps = bbox_overlaps(keep_bboxes, nms_bboxes)\n # find the suppressed bboxes for each kept bbox\n suppressed = overlaps > iou_threshold\n # accumulate suppression count\n suppressed = suppressed.long().cummax(0)[0].cumsum(0)\n # the real suppressed bboxes should be the ones that are suppressed exactly once\n suppressed = (suppressed == 1)\n span_scores = scores.view(1, overlaps.size(1)).repeat(overlaps.size(0), 1)\n span_scores[~suppressed] = scores.min() - 1\n # taking the max of the suppressed group\n keep_scores = span_scores.max(1)[0]\n # sort by scores, following tradition\n keep_scores, srt_idx = keep_scores.sort(descending=True)\n keep = keep[srt_idx]\n return bboxes[keep], keep_scores, locs[keep], labels[keep]\n\n","sub_path":"mmdet/iounet/nms.py","file_name":"nms.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"269498474","text":"from turtle import *\r\nfrom random import *\r\nfrom math import *\r\n\r\nscreen= getscreen() #Untuk menampilkan layar\r\nscreen.colormode(255) #untuk mensetting colormode menjadi RGB\r\nspeed(10.5) #untuk mengatur kecepatan \r\ntitle(\" Colorful Chessboard and Flowers\") #untuk title screen\r\nscreensize(canvwidth=7000, canvheight=7000, bg=None) #untuk mengatur ukuran canvas\r\nhideturtle() #untuk menyembunyikan turtle\r\nrows = int(screen.numinput(\"Colorful Chessboard and Flowers\",\"Enter the number of rows\",None,minval=2, maxval=25)) #numinput di gunakan untuk input menggunakan dialog box\r\npixel = int(screen.numinput(\"Colorful Chessboard and Flowers\",\"Enter the number of square size\",None,minval=2, maxval=None)) \r\npetals = int(screen.numinput(\"Colorful Chessboard and Flowers\",\"Enter the number petals\",None,minval=1, maxval=360))\r\nshowturtle() #untuk menunjukkan turtle\r\npenup()\r\ngoto (0,250)\r\npendown()\r\nsetheading(360/petals) #untuk mengarahkan turtle sesuai dengan sudut yang diberikan, sudut itu dihitung dari x-axis positif\r\npensize(3) #untuk mengatur ketebalan garis cetakan turtle\r\nfor i in range(1,petals+1) :\r\n r = (randint(0,255))\r\n g = (randint(0,255))\r\n b = (randint(0,255))\r\n color((r,g,b),(r,g,b))\r\n pendown()\r\n circle(100,60) #untuk membuat tali busur\r\n right(-120)\r\n circle(100,60)\r\n setheading(360/petals+(360/petals)*i)\r\npenup()\r\nif rows % 2 == 0 : #untuk mengecek barisnya genap atau ganjil\r\n x = -((rows)/2)*pixel \r\n y = 120-pixel\r\n goto (x,y) #untuk menempatkan turtle\r\nelse :\r\n x = -((rows+1)/2)*pixel + (pixel//2)\r\n y = 120-pixel\r\n goto (x,y)\r\nsetheading(90)\r\npensize(0)\r\nfor numb in range(rows) : # loop untuk kolom\r\n for k in range(1,rows+1) : # lopp untuk baris\r\n r = (randint(0,255)) #untuk memberi nilai random pada variable\r\n g = (randint(0,255))\r\n b = (randint(0,255))\r\n color((r,g,b),(r,g,b)) #untuk mengaplikasikan nilai nilai rgb menjadi suatu warna isian dan garis\r\n pendown() #untuk membuat turtle mencetak garis\r\n begin_fill() # untuk memberi tanda awal permulaan pewarnaan\r\n for j in range(4) : #loop untuk membuat persegi\r\n forward(pixel) #untuk membuat turtle bergerak maju\r\n right(90) #untuk membuat turtle belok sebesar 90 derajat\r\n end_fill() #untuk memberi tanda akhir pewarnaan\r\n penup()\r\n goto(x+(pixel*k),y)\r\n y = y - pixel\r\n goto(x,y)\r\ntext = \"Colorful Chessboard of \" + str(rows**2) + \" Squares and Flower of \" + str(petals) + \" Petals\"\r\ngoto(0,(-pixel*rows)+50)\r\ncolor(\"blue\")\r\nwrite(text,align='center',font=('Arial',16,'normal')) #untuk menulis text di canvas\r\nhideturtle()\r\nexitonclick() #untuk memerintahkan agar exit pada saat canvas di klik\r\n\r\n \r\n\r\n\r\n \r\n","sub_path":"Archive-Code/B_PDD_1806235832_DiptaLaksmanaBaswaraD_Tugas01.py","file_name":"B_PDD_1806235832_DiptaLaksmanaBaswaraD_Tugas01.py","file_ext":"py","file_size_in_byte":2896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"390374631","text":"import speech_recognition as sr \nimport colorama\nfrom colorama import Fore as f\n \nAUDIO_FILE = (input(\"Enter the Files Name: \")+\".wav\") \n \n# use the audio file as the audio source \n \nr = sr.Recognizer() \n \nwith sr.AudioFile(AUDIO_FILE) as source: \n\n audio = r.record(source) #Reads the audio file\n \ntry: \n\tprint(f.LIGHTGREEN_EX + \"Success\")\n\tprint(f.LIGHTYELLOW_EX + \"The audio file contains: \" + f.LIGHTBLUE_EX + r.recognize_google(audio)) \n \nexcept sr.UnknownValueError: \n print(f.LIGHTRED_EX + \"Google Speech Recognition could not understand the audio\") \n \nexcept sr.RequestError as e: \n print(f.LIGHTRED_EX + \"Could not request results from Google Speech Recognition service; {0}\".format(e)) \n","sub_path":"Update.py","file_name":"Update.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"499113619","text":"import torchvision.transforms as transforms\nfrom PIL import Image\nfrom torch.utils.data import Dataset, DataLoader\nimport random\nimport json\nimport os\nfrom os.path import join\nimport torch\nimport numpy as np\n\n\nclass PatchAllface(Dataset):\n def __init__(self, txtpath, transform):\n self.data_json = json.load(open(txtpath))\n self.transform = transform\n\n def __getitem__(self, idx):\n video_paths = self.data_json[idx]\n fake_video_path, real_video_path = video_paths\n\n fake_image_names = os.listdir(fake_video_path)\n fake_image_nums = np.linspace(0, len(fake_image_names) - 1, 10, dtype=int).tolist()\n fake_image_names = [fake_image_names[num] for num in fake_image_nums]\n fake_image_paths = [join(fake_video_path, image_name) for image_name in fake_image_names]\n fake_images = [Image.open(imagepath).convert('RGB') for imagepath in fake_image_paths]\n\n real_image_names = os.listdir(real_video_path)\n real_image_nums = np.linspace(0, len(real_image_names) - 1, 10, dtype=int).tolist()\n real_image_names = [real_image_names[num] for num in real_image_nums]\n real_image_paths = [join(real_video_path, image_name) for image_name in real_image_names]\n real_images = [Image.open(imagepath).convert('RGB') for imagepath in real_image_paths]\n\n fake_images = [self.transform(image) for image in fake_images]\n real_images = [self.transform(image) for image in real_images]\n\n fake_images = torch.stack(fake_images, dim=0)\n real_images = torch.stack(real_images, dim=0)\n\n if random.randint(0, 1) == 0:\n images = torch.stack((real_images, fake_images), dim=0)\n label = torch.tensor([0, 1])\n else:\n images = torch.stack((fake_images, real_images), dim=0)\n label = torch.tensor([1, 0])\n return images, label\n\n def __len__(self):\n return len(self.data_json)\n\n\ntransform_train = transforms.Compose([\n transforms.Resize((299, 299)),\n transforms.RandomVerticalFlip(),\n transforms.RandomHorizontalFlip(),\n transforms.RandomRotation(15),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n])\n\ntransform_test = transforms.Compose([\n transforms.Resize((299, 299)),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n])\n\n\ndef get_dataloader(BATCH_SIZE):\n datatrain = \"/root/data/wzy/datalocker/corres_large_factor_train.json\"\n dataval = \"/root/data/wzy/datalocker/corres_large_factor_validate.json\"\n data_image = PatchAllface(txtpath=datatrain, transform=transform_train)\n data_loader_image = DataLoader(dataset=data_image, shuffle=True, batch_size=BATCH_SIZE, num_workers=4)\n test_data = PatchAllface(txtpath=dataval, transform=transform_test)\n test_data_loader = DataLoader(dataset=test_data, shuffle=False, batch_size=BATCH_SIZE, num_workers=4)\n\n return data_loader_image, test_data_loader\n\n\nif __name__ == '__main__':\n train_dataloader, test_dataloader = get_dataloader(16)\n for video_images, video_label in train_dataloader:\n video_images = video_images.view(16 * 2, 8, 3, 299, 299)\n video_label = video_label.view(16 * 2)\n video_images = video_images.permute(0, 2, 1, 3, 4)\n print(video_images.size())\n exit()\n","sub_path":"dataloader/dataloader_face_corredpond_299.py","file_name":"dataloader_face_corredpond_299.py","file_ext":"py","file_size_in_byte":3346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"16588292","text":"#! /usr/bin/env python\n# -*- mode: python; coding: utf-8 ; python-indent: 2 -*-\n\nimport downstream as ds\nnewdir = \"/data/videos/hp2012/\"\n\nimport sys, os\nsys.path.append('..')\nimport vsutils as vsu\n\narg = sys.argv[1]\nif not os.path.isfile(arg):\n sys.exit(0)\nf = file(arg)\nauthor=''\nname=''\nfor l in f.readlines():\n if l[0]=='*': \n author=l.split()[1].strip()\n if l[0:4]==\"http\": \n url = l.split()[0]\n ds.transcode_youtube(url.strip(), newdir)\n","sub_path":"va_chercher_fichier_liens.py","file_name":"va_chercher_fichier_liens.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"621714762","text":"from skimage import data, filters,io, feature, morphology\nimport matplotlib.pyplot as plt\nimport findtraces\nimport drawtraces\n\ndef main(imgpath, sigma, speed):\n img = io.imread(imgpath, as_grey=True)\n img = feature.canny(img, sigma=sigma)\n print(\"关闭图像窗口后将会开始绘制\")\n plt.imshow(img, cmap=\"gray\")\n plt.show()\n traces = findtraces.do(img==False)\n drawtraces.do(traces, img.shape[0], img.shape[1])\n\nif __name__ == '__main__':\n import sys\n if(len(sys.argv) < 2):\n print(\"缺少参数(fundraw.py [] [])\")\n else:\n imgpath = sys.argv[1]\n sigma = float(sys.argv[2]) if len(sys.argv)>=3 else 2\n speed = int(sys.argv[3]) if len(sys.argv)>=4 else 10\n main(imgpath=imgpath, sigma=sigma, speed=speed)\n","sub_path":"Python/素描图片/fundraw.py","file_name":"fundraw.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"245937495","text":"#sequenceingsPrimers\n\nfrom Bio.Blast import NCBIWWW\nfrom Bio.Blast import NCBIXML\nfile_string = \"\" \nx = 1\nn=1\n\nfasta_files = [\"result\"]\nfor i in fasta_files:\n File = open(\"output\"+str(x)+\".txt\",\"w\")\n fasta_string = open(i+\".fasta\").read() #or make the names fasta1.fasta and just do open(i).read\n result_handle = NCBIWWW.qblast(\"blastn\", \"nr\", fasta_string, hitlist_size=10)\n\n #blast_records = NCBIXML.parse(result_handle) \n blast_record = NCBIXML.read(result_handle)# if you only have one seq in file\n E_VALUE_THRESH = 0.001\n for blast_record in blast_record:\n for alignment in blast_record.alignments:\n for hsp in alignment.hsps:\n if hsp.expect < E_VALUE_THRESH:\n file_string += \"alignment:\",alignment.title+\"\\n\"\n file_string += \"e-value:\",hsp.expect+\"\\n\"\n x += 1\n File.write(file_string)\n","sub_path":"SeqAuto.py","file_name":"SeqAuto.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"562888020","text":"import sys\nsys.stdin = open('2007. 패턴 마디의 길이.txt')\n\nt = int(input())\nfor tc in range(1, t+1):\n array = list(input())\n # print(array)\n\n minLen = 10\n for i in range(10, 0, -1):\n if array[0:i] == array[i:i*2]:\n if i < minLen: minLen = i\n \n print('#{} {}'.format(tc, minLen))","sub_path":"SWExpert/D2/2007. 패턴 마디의 길이.py","file_name":"2007. 패턴 마디의 길이.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"243298483","text":"import threading\n\nimport discord\n\nimport brian.AI as train\nimport brian.getreply as rp\nfrom brian.update_dataset import main, create_text_review\n\ntrain_bot = train.AI()\nclient = discord.Client()\ncachemsg = []\ndataset_raw = []\nreply = rp.getrply()\nidreply = []\n\n\ndef train_reload():\n train_bot.train()\n reply.__init__()\n print('reload models')\n\ndef save_text_raw(fpath: dir, data):\n file = open(fpath, \"a+\", encoding=\"utf-8\")\n for item in data:\n file.write(\"{}<=:=>{}|=:=|{}\\n\".format(item[0], item[1], item[2]))\n file.close()\n\n\n@client.event\nasync def on_ready():\n print('Đang khởi chạy')\n print(client.user.name)\n print(client.user.id)\n print('------')\n\n\n@client.event\nasync def on_message(ctx):\n idnow = 0\n if ctx.reference:\n idnow = ctx.reference.message_id\n cachemsg.append((ctx.id, ctx.content))\n if (ctx.author == client.user):\n idreply.append(ctx.id)\n return\n idref = ctx.reference\n if idref != None:\n idref = idref.message_id\n for item in cachemsg:\n if item[0] == idref:\n msg, tag = reply.chatbot_response(msg=item[1])\n dataset_raw.append((item[1], ctx.content, tag))\n print(cachemsg)\n print(dataset_raw)\n if len(idreply) >= 100:\n for item in idreply[0:50]:\n idreply.remove(item)\n if len(cachemsg) >= 100:\n for item in cachemsg[0:50]:\n cachemsg.remove(item)\n if (ctx.channel.id == 863726369951580210) or (ctx.channel.id == 861883913009889290) or (idnow in idreply) or (\n 'bot' in ctx.content.lower().replace(',', '').replace('.', '').split(\" \")):\n msg, tag = reply.chatbot_response(msg=ctx.content)\n await ctx.reply(msg, mention_author=True)\n if len(dataset_raw) >= 100:\n save_text_raw('brian/data/raw.txt', dataset_raw)\n dataset_raw.clear()\n main('brian/data/raw.txt', 'brian/data/intents.json')\n # train and reload\n th1 = threading.Thread(target=train_reload)\n th1.start()\n if ctx.channel.id == 861544200045592597:\n if ctx.content == 'học':\n save_text_raw('brian/data/raw.txt', dataset_raw)\n dataset_raw.clear()\n main('brian/data/raw.txt', 'brian/data/intents.json')\n # train and reload\n th1 = threading.Thread(target=train_reload)\n th1.start()\n if ctx.content == 'xemdataset':\n create_text_review()\n await ctx.channel.send(file=discord.File('brian/data/textout.txt'))\n\n\nclient.run(\"TOKEN\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"4707626","text":"# Copyright 2018 Google LLC\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\nfrom __future__ import print_function\nfrom baseline_agent import BaselineAgent\nfrom adv_human import AdvancedHumanAgent\nfrom adv_human_mistake import AdvancedHumanMistakeAgent\n# from adv_human_mistake2 import AdvancedHumanMistake2Agent\nfrom training_observer import TrainingObserver\n# from mdk2 import MDK2\nimport sys\nimport argparse\nfrom random import seed\nimport numpy as np\nimport json\n\n\nfrom hanabi_learning_environment import pyhanabi\n\n\nclass ModObservation(pyhanabi.HanabiObservation):\n def __init__(self):\n self.obs = None\n self.obs_cards = None\n moves = []\n for card_index in range(5):\n moves.append(pyhanabi.HanabiMove.get_play_move(card_index))\n moves.append(pyhanabi.HanabiMove.get_discard_move(card_index))\n moves.append(pyhanabi.HanabiMove.get_reveal_color_move(1, card_index))\n moves.append(pyhanabi.HanabiMove.get_reveal_rank_move(1, card_index))\n self.moves = moves\n self._observation = None\n self.flag = 1\n\n def observation(self):\n \"\"\"Returns the C++ HanabiObservation object.\"\"\"\n return self._observation\n\n def cur_player_offset(self):\n \"\"\"Returns the player index of the acting player, relative to observer.\"\"\"\n return self.flag\n\n def num_players(self):\n \"\"\"Returns the number of players in the game.\"\"\"\n return self.obs.num_players()\n\n def observed_hands(self):\n \"\"\"Returns a list of all hands, with cards ordered oldest to newest.\n\n The observing player's cards are always invalid.\n \"\"\"\n return self.obs_cards\n\n def card_knowledge(self):\n \"\"\"Returns a per-player list of hinted card knowledge.\n\n Each player's entry is a per-card list of HanabiCardKnowledge objects.\n Each HanabiCardKnowledge for a card gives the knowledge about the cards\n accumulated over all past reveal actions.\n \"\"\"\n return self.obs.card_knowledge()\n\n def discard_pile(self):\n \"\"\"Returns a list of all discarded cards, in order they were discarded.\"\"\"\n return self.obs.discard_pile()\n\n def fireworks(self):\n \"\"\"Returns a list of fireworks levels by value, ordered by color.\"\"\"\n return self.obs.fireworks()\n\n def deck_size(self):\n \"\"\"Returns number of cards left in the deck.\"\"\"\n return self.obs.deck_size()\n\n def last_moves(self):\n \"\"\"Returns moves made since observing player last acted.\n\n Each entry in list is a HanabiHistoryItem, ordered from most recent\n move to oldest. Oldest move is the last action made by observing\n player. Skips initial chance moves to deal hands.\n \"\"\"\n return self.obs.last_moves()\n\n def information_tokens(self):\n \"\"\"Returns the number of information tokens remaining.\"\"\"\n return self.obs.information_tokens()\n\n def life_tokens(self):\n \"\"\"Returns the number of information tokens remaining.\"\"\"\n return self.obs.life_tokens()\n\n def legal_moves(self):\n \"\"\"Returns list of legal moves for observing player.\n\n List is empty if cur_player() != 0 (observer is not currently acting).\n \"\"\"\n return self.moves\n\n\n def card_playable_on_fireworks(self, color, rank):\n return self.obs.card_playable_on_fireworks(color, rank)\n\ndef run_game(game_parameters, agents, trainmodel=None, verbose=1, train=False):\n \"\"\"Play a game, selecting random actions.\"\"\"\n\n def print_state(state):\n \"\"\"Print some basic information about the state.\"\"\"\n print(\"\")\n print(\"Current player: {}\".format(state.cur_player()))\n print(state)\n\n # Example of more queries to provide more about this state. For\n # example, bots could use these methods to to get information\n # about the state in order to act accordingly.\n print(\"### Information about the state retrieved separately ###\")\n print(\"### Information tokens: {}\".format(state.information_tokens()))\n print(\"### Life tokens: {}\".format(state.life_tokens()))\n print(\"### Fireworks: {}\".format(state.fireworks()))\n print(\"### Deck size: {}\".format(state.deck_size()))\n print(\"### Discard pile: {}\".format(str(state.discard_pile())))\n print(\"### Player hands: {}\".format(str(state.player_hands())))\n print(\"\")\n\n def print_observation(observation):\n \"\"\"Print some basic information about an agent observation.\"\"\"\n print(\"--- Observation ---\")\n print(observation)\n\n print(\"### Information about the observation retrieved separately ###\")\n print(\"### Current player, relative to self: {}\".format(\n observation.cur_player_offset()))\n print(\"### Observed hands: {}\".format(observation.observed_hands()))\n print(\"### Card knowledge: {}\".format(observation.card_knowledge()))\n print(\"### Discard pile: {}\".format(observation.discard_pile()))\n print(\"### Fireworks: {}\".format(observation.fireworks()))\n print(\"### Deck size: {}\".format(observation.deck_size()))\n move_string = \"### Last moves:\"\n for move_tuple in observation.last_moves():\n move_string += \" {}\".format(move_tuple)\n print(move_string)\n print(\"### Information tokens: {}\".format(observation.information_tokens()))\n print(\"### Life tokens: {}\".format(observation.life_tokens()))\n print(\"### Legal moves: {}\".format(observation.legal_moves()))\n print(\"--- EndObservation ---\")\n\n def print_encoded_observations(encoder, state, num_players):\n print(\"--- EncodedObservations ---\")\n print(\"Observation encoding shape: {}\".format(encoder.shape()))\n print(\"Current actual player: {}\".format(state.cur_player()))\n for i in range(num_players):\n print(\"Encoded observation for player {}: {}\".format(\n i, encoder.encode(state.observation(i))))\n print(\"--- EndEncodedObservations ---\")\n\n game = pyhanabi.HanabiGame(game_parameters)\n\n encoder = pyhanabi.ObservationEncoder(game)\n mod_obs = [ModObservation() for _ in range(len(agents) + train)]\n\n if verbose > 3:\n print(game.parameter_string(), end=\"\")\n obs_encoder = pyhanabi.ObservationEncoder(\n game, enc_type=pyhanabi.ObservationEncoderType.CANONICAL)\n\n state = game.new_initial_state()\n last_mistake, move, mistake = None, None, None\n while not state.is_terminal():\n if state.cur_player() == pyhanabi.CHANCE_PLAYER_ID:\n state.deal_random_card()\n continue\n\n observation = state.observation(state.cur_player())\n\n for idx, agt in enumerate(agents):\n if idx == state.cur_player():\n last_mistake = mistake\n move, mistake = agt.act2(observation)\n # print('Move:', move, mistake)\n else:\n mod_obs[idx].obs = observation\n mod_obs[idx].obs_cards = None\n mod_obs[idx].flag = 1\n agt.act(mod_obs[idx])\n if train:\n mod_obs[-1].obs = observation\n mod_obs[-1].obs_cards = None\n mod_obs[-1].flag = 1\n trainmodel.act3(mod_obs[-1], last_mistake)\n\n state.apply_move(move)\n\n if verbose > 3:\n print_state(state)\n print_observation(observation)\n if verbose > 4:\n print_encoded_observations(obs_encoder, state, game.num_players())\n print(\"\")\n print(\"Number of legal moves: {}\".format(len(observation.legal_moves())))\n if verbose > 2:\n print(\"Agent has chosen: {}\".format(move))\n if verbose > 2:\n print(\"\")\n print(\"Game done. Terminal state:\")\n print(\"\")\n print(state)\n print(\"\")\n if verbose > 1:\n print(\"score: {}\".format(state.score()))\n return state.score()\n\n\nreinforcement_agents = []\n\np = argparse.ArgumentParser(prog='PROG')\np.add_argument('foo')\nfor i in [('-p', 'players', 2, int), ('-c', 'colors', 5, int), ('-r', 'rank', 5, int), ('-hs', 'hand_size', 5, int),\n ('-i', 'max_information_tokens', 8, int), ('-l', 'max_life_tokens', 3, int), ('-s', 'seed', -1, int),\n ('-v', 'verbose', 0, int), ('-n', 'num_rounds', 1, int), ('-tr', 'training_rounds', 0, int),\n ('-al', 'alpha', 0.05, float), ('-a2', 'alpha2', 0, float), ('-a3', 'alpha3', 0, float), ('-t', 'train', 1, int)]:\n p.add_argument(i[0], dest=i[1], default=i[2], type=i[3])\np.add_argument('-a', dest='agents', default=['baseline', 'baseline'], nargs='*')\nargs = vars(p.parse_args(sys.argv))\nagent_dict = {'baseline': BaselineAgent, 'advhm': AdvancedHumanMistakeAgent, 'advh': AdvancedHumanAgent,\n 'mdk': TrainingObserver}\n\nseed(1)\nscore_list = []\ntraining_to_go = args['training_rounds']\nagents=[]\nlabels = []\nargs['print'] = 0\nfor agent in args['agents']:\n agents.append(agent_dict[agent](args))\ntrainagt = TrainingObserver(args)\n\nfor _ in range(args['num_rounds']):\n if _%50 == 0 and args['verbose'] >= 0:\n print('#################'+str(_))\n if _ == args['num_rounds'] - 1:\n args['print'] = 1\n for agent in agents:\n agent.reset(args)\n trainagt.reset(args)\n score_list.append(run_game(args, agents, trainmodel=trainagt, verbose=args['verbose'], train=True))\n\nif args['verbose'] >= 0:\n print(sum(score_list)/args['num_rounds'])\n agents = agents[:-1] + [trainagt]\n score_list=[]\n print('##################################')\n\n if args['train'] == 1:\n '''trainagt.k_means()\n print('Clusters: ')\n print(trainagt.clusters)\n np.savetxt('./clusters.txt', trainagt.clusters)'''\n data = np.concatenate([trainagt.data, np.array(trainagt.labels).reshape((-1,1))], axis=1)\n np.savetxt('./train_data.txt', data)\n\n trainagt = TrainingObserver(args)\n for _ in range(args['num_rounds']):\n if _%50 == 0 and args['verbose'] >= 0:\n print('#################'+str(_))\n if _ == args['num_rounds'] - 1:\n args['print'] = 1\n for agent in agents:\n agent.reset(args)\n trainagt.reset(args)\n score_list.append(run_game(args, agents, trainmodel=trainagt, verbose=args['verbose'], train=True))\n data = np.concatenate([trainagt.data, np.array(trainagt.labels).reshape((-1, 1))], axis=1)\n np.savetxt('./val_data.txt', data)\n\n","sub_path":"gen_model_data.py","file_name":"gen_model_data.py","file_ext":"py","file_size_in_byte":11029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"88607844","text":"\n\"\"\"\n\nWrite a program that takes a list and returns a new list that contains all the elements of the first list minus all the duplicates.\n\n\"\"\"\n\nimport numpy\n\n# The first function used for and if to iterate the elements in that list\ndef dupe1(a):\n y=[]\n for i in a:\n if i not in y:\n y.append(i)\n y.sort()\n return y\n\n# The second one used list(set(a)) to remove duplicates directly.\ndef dupe2(a):\n return list(set(a))\n\na=[1,2,3,5,6,7,5,4,2,1]\nprint(dupe1(a))\nprint(dupe2(a))\n","sub_path":"First Programs/List of set.py","file_name":"List of set.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"574698206","text":"import traceback\nimport sys\nfrom discord.ext import commands\nimport discord\nimport asyncio\n\n\nclass errors_Cog(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.Cog.listener()\n async def on_command_error(self, ctx, error):\n if isinstance(error, commands.MissingRequiredArgument):\n embed = discord.Embed(colour=discord.Colour(0xa9219b))\n\n #embed.set_image(url=\"https://cdn.discordapp.com/embed/avatars/0.png\")\n embed.set_thumbnail(url=\"https://n0tj.com/g_center.png\")\n embed.set_author(name=\"Join the gearBot discord\", url=\"https://discord.gg/jZAJ7Yy\", icon_url=\"https://n0tj.com/g_center.png\")\n embed.set_footer(text=\"Message jay#8008 with any bugs or concerns.\", icon_url=\"https://n0tj.com/buddha.jpeg\")\n embed.add_field(name=\"**Updating your gear screenshot**\", value=\"**!gear **\")\n embed.add_field(name=\"**Looking up someone or your own gear**\", value=\"**!gear <@user>**\")\n\n\n await ctx.send(embed=embed)\n\n\ndef setup(bot):\n bot.add_cog(errors_Cog(bot))\n","sub_path":"cogs/errors.py","file_name":"errors.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"484997514","text":"from time import sleep\nimport Adafruit_GPIO.SPI as SPI\nimport Adafruit_SSD1306\nimport Adafruit_LSM303\nimport RPi.GPIO as GPIO\n\nfrom PIL import Image\nfrom PIL import ImageDraw\nfrom PIL import ImageFont\n\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(17, GPIO.IN)\n\nRST = 24\nDC = 23\nSPI_PORT = 0\nSPI_DEVICE = 0\n\nlsm303 = Adafruit_LSM303.LSM303()\ndisp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3d)\ndisp.begin()\n\ndisp.clear()\ndisp.display()\n\nwidth = disp.width\nheight = disp.height\nimage = Image.new('1', (width, height))\n\npadding = 2\nshape_width = 20\ntop = padding\nbottom = height-padding\n# x = padding\nfont = ImageFont.load_default()\n\ndata = []\nlength = 25\ngraphWidth = 110\ngraphHeight = 50\nxPadding = width - graphWidth\nspacing = graphWidth / length\nyAxisText = 'a(m/s^2)'\n#batteryFull = None\nshowIcon = False\nflashCounter = 0\n\ndef mapNum(value, leftMin, leftMax, rightMin, rightMax):\n leftSpan = leftMax - leftMin\n rightSpan = rightMax - rightMin\n valueScaled = float(value - leftMin) / float(leftSpan)\n return rightMin + (valueScaled * rightSpan)\n\nwhile True:\n accel, mag = lsm303.read()\n accel_x, accel_y, accel_z = accel\n mag_x, mag_y, mag_z = mag\n\n accel_x /= 100\n accel_y /= 100\n accel_z /= 100\n\n draw = ImageDraw.Draw(image)\n draw.rectangle((0,0,width,height), outline=0, fill=0)\n\n data.append(accel_x)\n if(len(data) > length) :\n data.pop(0)\n\n draw.line((xPadding, 5, xPadding, graphHeight), fill=255)\n draw.line((xPadding, graphHeight, width -5, graphHeight), fill=255)\n draw.text((width / 2, graphHeight + 5), 't(s)', font=font, fill=255)\n #draw.line((width - width, graphHeight / 2), yAxisText, font = font, fill=255)\n\n rotImg = Image.new('1',\n (font.getsize(yAxisText)[0] + 2,\n font.getsize(yAxisText)[1] + 2), color=0)\n rotDraw = ImageDraw.Draw(rotImg)\n rotDraw.text((0,0), yAxisText, fill = 255)\n rotImg = rotImg.rotate(90, expand = 1)\n image.paste(rotImg, (2, top))\n\n for x, y in enumerate(data):\n if(x < len(data) -1):\n draw.line((\n (x * spacing) + xPadding,\n ((mapNum(y, -10, 10, 0, graphHeight))),\n ((x + 1) * spacing) + xPadding,\n ((mapNum(data[x+1], -10, 10, 0, graphHeight)))),\n fill = 255)\n\n# batteryFull = GPIO.input(17)\n\n if(flashCounter > 1):\n showIcon = False if(showIcon) else True\n flashCounter = 0\n else:\n flashCounter += 1\n#\n# if(showIcon and batteryFull == 0):\n# draw.rectangle((width - 20, 4, width - 7, 10), outline=255, fill=0)\n# draw.rectangle((width - 20, 4, width - 17, 10), outline=255, fill=255)\n# draw.rectangle((width - 7, 6, width - 5, 8), outline=255, fill=255)\n# elif(batteryFull == 1):\n# draw.rectangle((width - 20, 4, width - 7, 10), outline=255, fill=0)\n# draw.rectangle((width - 20, 4, width - 11, 10), outline=255, fill=255)\n# draw.rectangle((width - 7, 6, width - 5, 8), outline=255, fill=255)\n \n disp.image(image)\n disp.display()\n sleep(0.01)\n","sub_path":"Python/headless.py","file_name":"headless.py","file_ext":"py","file_size_in_byte":3118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"162679667","text":"import scipy.io\r\nimport numpy as np\r\nfrom datascience import Table\r\nfrom sklearn import svm\r\nimport pandas as pd\r\n\r\npd.set_option('display.max_columns', 500)\r\npd.set_option('display.width', 1000)\r\n\r\n#--------------------------------------DATA EXTRACTION--------------------------------------\r\ndef read_file(file_name,data_type):\r\n mat = scipy.io.loadmat(file_name)\r\n if data_type == 1:\r\n RWEM = mat['rwe']\r\n return RWEM\r\n elif data_type == 2:\r\n EM = mat['em']\r\n return EM\r\n elif data_type == 3:\r\n SM = mat['sm']\r\n return SM\r\n elif data_type == 4:\r\n AM = mat['am']\r\n return AM\r\n \r\ndef allData(file,data_type,test_type):\r\n data = [[],[]]\r\n dataMatrix = read_file(file,data_type)\r\n l = len(dataMatrix)\r\n if test_type == 1:\r\n for i in range(l):\r\n data[0].append(dataMatrix[i,0:-3])\r\n data[1].append(dataMatrix[i,-2])\r\n elif test_type == 2:\r\n for i in range(l):\r\n if dataMatrix[i,-1] == 1:\r\n data[0].append(dataMatrix[i,0:-3])\r\n data[1].append(dataMatrix[i,-2])\r\n return data\r\n\r\ndef allWordData(file,data_type,word,test_type):\r\n possible_words = ['A','E','I','O','U','Arriba','Abajo','Adelante','Atrás','Derecha','Izquierda']\r\n index = possible_words.index(word)+1\r\n dataMatrix = read_file(file,data_type)\r\n l = len(dataMatrix)\r\n data = [[],[]]\r\n if test_type == 1:\r\n for i in range(l):\r\n if dataMatrix[i,-2] == index:\r\n data[0].append(dataMatrix[i,0:-3])\r\n data[1].append(file[:3])\r\n elif test_type == 2:\r\n for i in range(l):\r\n if (dataMatrix[i,-2] == index) and (dataMatrix[i,-1] == 1):\r\n data[0].append(dataMatrix[i,0:-3])\r\n data[1].append(file[:3])\r\n\r\n return data\r\n\r\n\r\n#--------------------------------------CLASSIFICATION---------------------------------------\r\n\r\ndef classification(training_data,labels,prediction_values,real_labels,c,g): \r\n clf = svm.SVC(C=c,gamma=g,cache_size=10000,class_weight='balanced')\r\n clf.fit(training_data,labels) \r\n algorithm_labels = clf.predict(prediction_values) \r\n comparisson = []\r\n for i in range(len(algorithm_labels)):\r\n if algorithm_labels[i] == real_labels[i]:\r\n comparisson.append(1)\r\n else:\r\n comparisson.append(0)\r\n accuracy = (sum(comparisson)/len(comparisson))*100\r\n results = [algorithm_labels,real_labels,accuracy]\r\n return results\r\n\r\n\r\n#------------------------------------------TESTS--------------------------------------------\r\n\r\ndef loocv(excluded,all_files,data_type,g,c,test_type):\r\n training_set = []\r\n for i in all_files:\r\n training_set.append(i)\r\n training_set.remove(excluded)\r\n training_data = []\r\n training_labels = []\r\n for i in training_set:\r\n data = allData(i,data_type,test_type)\r\n for j in data[0]:\r\n training_data.append(j)\r\n for j in data[1]:\r\n training_labels.append(j)\r\n data = allData(excluded,data_type,test_type)\r\n prediction_data = []\r\n prediction_labels = data[1]\r\n for i in data[0]:\r\n prediction_data.append(i)\r\n results = classification(training_data,training_labels,prediction_data,prediction_labels,g,c)\r\n codes = [1,2,3,4,5,6,7,8,9,10,11]\r\n total_codes = [0,0,0,0,0,0,0,0,0,0,0]\r\n for i in results[1]:\r\n total_codes[int(i)-1]+=1\r\n predicted_codes = [0,0,0,0,0,0,0,0,0,0,0]\r\n for i in range(len(results[0])):\r\n if results[0][i] == results[1][i]:\r\n predicted_codes[int(results[0][i])-1]+=1\r\n codes_accuracy = []\r\n for i in range(11):\r\n codes_accuracy.append((predicted_codes[i]/total_codes[i])*100)\r\n return [codes_accuracy,results[2]]\r\n\r\ndef tfcv(word,files,data_type,c,g,test_type):\r\n all_possibilities = []\r\n for file in files:\r\n data = allWordData(file,data_type,word,test_type)\r\n for i in range(len(data[0])):\r\n all_possibilities.append((data[0][i],data[1][i]))\r\n for i in range(np.random.choice(3,1)[0]+1):\r\n np.random.shuffle(all_possibilities)\r\n training_set = np.random.choice(len(all_possibilities),int(len(all_possibilities)*0.75),replace=False)\r\n training_data = []\r\n training_labels = []\r\n prediction_data = []\r\n prediction_labels = []\r\n for i in range(len(all_possibilities)):\r\n data = all_possibilities[i]\r\n if i in training_set:\r\n training_data.append(data[0])\r\n training_labels.append(data[1])\r\n else:\r\n prediction_data.append(data[0])\r\n prediction_labels.append(data[1])\r\n results = classification(training_data,training_labels,prediction_data,prediction_labels,c,g) \r\n codes = ['S01','S02','S03','S04','S05','S06','S07','S08','S09','S10','S11','S12','S13','S14','S15']\r\n total_codes = []\r\n for i in codes:\r\n total_codes.append(results[1].count(i))\r\n predicted_codes = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\r\n for i in range(len(results[0])):\r\n if results[0][i] == results[1][i]:\r\n predicted_codes[int(results[0][i][1:])-1]+=1\r\n codes_accuracy = []\r\n for i in range(15):\r\n if total_codes[i] != 0:\r\n codes_accuracy.append((predicted_codes[i]/total_codes[i])*100)\r\n else:\r\n if predicted_codes[i] == 0:\r\n codes_accuracy.append(100)\r\n else:\r\n codes_accuracy.append(0)\r\n return [codes_accuracy,results[2]]\r\n\r\ndef leaveOneOutCrossValidation(data_type,c,g,test_type):\r\n if data_type == 1:\r\n files = ['S01_RWEM.mat','S02_RWEM.mat','S03_RWEM.mat','S04_RWEM.mat','S05_RWEM.mat','S06_RWEM.mat','S07_RWEM.mat','S08_RWEM.mat','S09_RWEM.mat','S10_RWEM.mat','S11_RWEM.mat','S12_RWEM.mat','S13_RWEM.mat','S14_RWEM.mat','S15_RWEM.mat'] \r\n elif data_type == 2:\r\n files = ['S01_EM.mat','S02_EM.mat','S03_EM.mat','S04_EM.mat','S05_EM.mat','S06_EM.mat','S07_EM.mat','S08_EM.mat','S09_EM.mat','S10_EM.mat','S11_EM.mat','S12_EM.mat','S13_EM.mat','S14_EM.mat','S15_EM.mat'] \r\n elif data_type == 3:\r\n files = ['S01_SM.mat','S02_SM.mat','S03_SM.mat','S04_SM.mat','S05_SM.mat','S06_SM.mat','S07_SM.mat','S08_SM.mat','S09_SM.mat','S10_SM.mat','S11_SM.mat','S12_SM.mat','S13_SM.mat','S14_SM.mat','S15_SM.mat'] \r\n elif data_type == 4:\r\n files = ['S01_AM.mat','S02_AM.mat','S03_AM.mat','S04_AM.mat','S05_AM.mat','S06_AM.mat','S07_AM.mat','S08_AM.mat','S09_AM.mat','S10_AM.mat','S11_AM.mat','S12_AM.mat','S13_AM.mat','S14_AM.mat','S15_AM.mat'] \r\n results = []\r\n for file in files:\r\n results.append(loocv(file,files,data_type,c,g,test_type))\r\n table_rows = []\r\n means = [[],[],[],[],[],[],[],[],[],[],[],[]]\r\n for i in results:\r\n row = []\r\n row.append(i[1])\r\n means[0].append(i[1])\r\n for j in range(len(i[0])):\r\n row.append(i[0][j])\r\n means[j+1].append(i[0][j])\r\n table_rows.append(row)\r\n mean = []\r\n for i in means:\r\n mean.append(np.mean(i))\r\n codes = ['General accuracy','A','E','I','O','U','Arriba','Abajo','Adelante','Atrás','Derecha','Izquierda']\r\n T = Table().with_columns('Codes',codes,'S01',table_rows[0],'S02',table_rows[1],'S03',table_rows[2],'S04',table_rows[3],'S05',table_rows[4],'S06',table_rows[5],'S07',table_rows[6],'S08',table_rows[7],'S09',table_rows[8],'S10',table_rows[9],'S11',table_rows[10],'S12',table_rows[11],'S13',table_rows[12],'S14',table_rows[13],'S15',table_rows[14],'MEAN',mean)\r\n df = T.to_df()\r\n df = df.round(3)\r\n return df\r\n\r\ndef tenFoldCrossValidation(data_type,c,g,test_type):\r\n if data_type == 1:\r\n files = ['S01_RWEM.mat','S02_RWEM.mat','S03_RWEM.mat','S04_RWEM.mat','S05_RWEM.mat','S06_RWEM.mat','S07_RWEM.mat','S08_RWEM.mat','S09_RWEM.mat','S10_RWEM.mat','S11_RWEM.mat','S12_RWEM.mat','S13_RWEM.mat','S14_RWEM.mat','S15_RWEM.mat'] \r\n elif data_type == 2:\r\n files = ['S01_EM.mat','S02_EM.mat','S03_EM.mat','S04_EM.mat','S05_EM.mat','S06_EM.mat','S07_EM.mat','S08_EM.mat','S09_EM.mat','S10_EM.mat','S11_EM.mat','S12_EM.mat','S13_EM.mat','S14_EM.mat','S15_EM.mat'] \r\n elif data_type == 3:\r\n files = ['S01_SM.mat','S02_SM.mat','S03_SM.mat','S04_SM.mat','S05_SM.mat','S06_SM.mat','S07_SM.mat','S08_SM.mat','S09_SM.mat','S10_SM.mat','S11_SM.mat','S12_SM.mat','S13_SM.mat','S14_SM.mat','S15_SM.mat'] \r\n elif data_type == 4:\r\n files = ['S01_AM.mat','S02_AM.mat','S03_AM.mat','S04_AM.mat','S05_AM.mat','S06_AM.mat','S07_AM.mat','S08_AM.mat','S09_AM.mat','S10_AM.mat','S11_AM.mat','S12_AM.mat','S13_AM.mat','S14_AM.mat','S15_AM.mat'] \r\n words = ['A','E','I','O','U','Arriba','Abajo','Adelante','Atrás','Derecha','Izquierda']\r\n whole_table = []\r\n aux = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]\r\n for word in words:\r\n results=[]\r\n for i in range(10):\r\n results.append(tfcv(word,files,data_type,c,g,test_type))\r\n grouped_data = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]\r\n for i in results:\r\n aux1 = i[0]\r\n aux2 = i[1]\r\n for j in range(1,16):\r\n grouped_data[j].append(aux1[j-1])\r\n grouped_data[0].append(aux2)\r\n means = []\r\n for i in grouped_data:\r\n means.append(np.mean(i))\r\n whole_table.append(means)\r\n for i in range(len(means)):\r\n aux[i].append(means[i])\r\n mean_column = []\r\n for i in aux:\r\n mean_column.append(np.mean(i))\r\n codes = ['General accuracy','S01','S02','S03','S04','S05','S06','S07','S08','S09','S10','S11','S12','S13','S14','S15']\r\n T = Table().with_columns('Codes',codes,'A',whole_table[0],'E',whole_table[1],'I',whole_table[2],'O',whole_table[3],'U',whole_table[4],'Arriba',whole_table[5],'Abajo',whole_table[6],'Adelante',whole_table[7],'Atrás',whole_table[8],'Derecha',whole_table[9],'Izquierda',whole_table[10],'MEAN',mean_column)\r\n df = T.to_df()\r\n df = df.round(3)\r\n return df\r\n\r\ndf1 = leaveOneOutCrossValidation(1,200,0.1,1)\r\ndf2 = tenFoldCrossValidation(1,200,0.1,1)\r\n\r\n","sub_path":"Tests.py","file_name":"Tests.py","file_ext":"py","file_size_in_byte":10124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"561650567","text":"#!/usr/bin/python\nimport pandas as pd\nimport time\n\n# Constants\n# Value of Interval Time in second\nTIME = 300\nTIME_MS = TIME * 1000\n# Scale factor for the packet rate. It will be equal to [ pkts / scale ] per second.\nSCALE = 400\n# CSV Entries\nSIZE = 576\n# Simulation Time in CSV hours\nSIM = 720\n# Simulation in number of intevals\nSIM_N = SIM * 12\ncomputername=\"jedi\"\n# CSV File\nCSV = '/home/'+computername+'/Scrivania/RyuDatapathMonitor-master/CSV/vlan_interfaccia1_DOS.csv'\n# ToS \nSERV_0 = \"0\"\nSERV_1 = \"32\"\nSERV_2 = \"72\"\nSERV_3 = \"96\"\nSERV_4 = \"136\"\nSERV_5 = \"160\"\nSERV_6 = \"192\"\nSERV_7 = \"224\"\n\n# IDT_OPT\n# constant\nc_idt = \"-C\"\n#poisson\np_idt = \"-O\"\n#esponential\ne_idt =\"-E\"\n\n# PS_OPT\n# constant\nc_ps = \"-c\"\n# poisson\np_ps = \"-o\"\n# esponential\ne_ps =\"-e\"\n\n# default value for protocol and packet size \nDEFAULT_P = \"UDP\"\nDEFAULT_PS = \"512\"\n\n# Host Ip\nsrc = \"10.0.0.11\"\ndst = \"10.0.0.13\"\n\n# Type of distribution\nchoice_i = c_idt\nchoice_s = c_ps\n\n\n# Cmd creation\ndef createCmd(src, dst, tos, nPkts, avg, protocol=DEFAULT_P, ps_dim=DEFAULT_PS):\n com = 'ITGManager ' + src + ' -a ' + dst + ' -b ' + tos + ' ' + choice_i + ' ' + str(avg) + ' ' + choice_s + ' ' + ps_dim + ' -t ' + str(TIME_MS-8000)\n return com\n\n# Cmd creation\ndef createCmd_2(dst, port, tos, nPkts, avg, protocol=DEFAULT_P, ps_dim=DEFAULT_PS):\t\t\n com = 'ITGSend -a ' + dst + ' -rp ' + str(port) + ' -b ' + tos + ' ' + choice_i + ' ' + str(avg) + ' ' + choice_s + ' ' + ps_dim + ' -t ' + str(TIME_MS-10000) + ' &'\t\t\t\t\n return com\n\n# Cmd creation Iperf\ndef createCmd_3(dst, port, tos, nPkts, avg, protocol=DEFAULT_P, ps_dim=DEFAULT_PS):\t\t\n com = 'iperf3 -c ' + dst + ' -p ' + str(port) + ' -S ' + tos + ' ' + ' -k ' + str(nPkts) + ' &'\t\t\n return com\n","sub_path":"ditg.py","file_name":"ditg.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"604454814","text":"from selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom time import sleep\nimport requests\nimport json\nimport re\nfrom selenium.common.exceptions import NoSuchElementException\nimport csv\n\nheader = {'User-Agent': ''}\nd = webdriver.Chrome('./chromedriver')\nd.implicitly_wait(3)\nd.get('http://www.melon.com/chart/index.htm')\nd.get(\"http://www.melon.com/chart/search/index.htm\")\nd.find_element_by_xpath('//*[@id=\"d_chart_search\"]/div/h4[1]/a').click()\n\n\nfor i in range(1, 5):\n # age 10년 단위\n age_xpath = '//*[@id=\"d_chart_search\"]/div/div/div[1]/div[1]/ul/li[' + str(i) + ']/span/label'\n age = d.find_element_by_xpath(age_xpath)\n age.click()\n\n # year\n for i in range(1, 11):\n\n\n try:\n year_xpath = '//*[@id=\"d_chart_search\"]/div/div/div[2]/div[1]/ul/li[' + str(i) + ']/span/label'\n year = d.find_element_by_xpath(year_xpath)\n year.click()\n print(year.text)\n\n except:\n print(\"year_xpath not found\")\n continue\n \n # month\n for i in range(1,13):\n try:\n month_xpath = '//*[@id=\"d_chart_search\"]/div/div/div[3]/div[1]/ul/li[' + str(i) + ']/span/label'\n month = d.find_element_by_xpath(month_xpath)\n month.click()\n print(month.text)\n\n except:\n print(\"month_xpath not found\")\n continue\n \n # week\n for i in range(1,6):\n # weekly save\n result = list()\n try:\n week_xpath = '//*[@id=\"d_chart_search\"]/div/div/div[4]/div[1]/ul/li[' + str(i) + ']/span/label'\n week = d.find_element_by_xpath(week_xpath)\n week.click()\n print(week.text)\n\n except:\n print(\"week_xpath not found\")\n continue\n \n\n # genre selection\n try:\n classCd = d.find_element_by_xpath('//*[@id=\"d_chart_search\"]/div/div/div[5]/div[1]/ul/li[2]/span/label')\n except:\n classCd = d.find_element_by_xpath('//*[@id=\"d_chart_search\"]/div/div/div[5]/div[1]/ul/li/span/label')\n \n \n classCd.click()\n print(classCd.text)\n\n # search button\n d.find_element_by_xpath('//*[@id=\"d_srch_form\"]/div[2]/button/span/span').click()\n sleep(10)\n\n # check whether next_page exists\n next_exist = True\n page_list = ['''\"lst50\"'''] # initialize with the first page\n try:\n next_xpath = '//*[@id=\"frm\"]/div[2]/span/a'\n next_button = d.find_element_by_xpath(next_xpath)\n except: \n next_exist = False\n if next_exist:\n page_list.append('''\"lst100\"''') # next page\n\n for page in page_list:\n song_ids = d.find_elements_by_xpath('//*[@id={}]/td[4]/div/a'.format(page))\n song_ids = [re.sub('[^0-9]', '', song_id.get_attribute(\"href\")) for song_id in song_ids]\n ranks = d.find_elements_by_xpath('//*[@id={}]/td[2]/div/span[1]'.format(page))\n\n for rank, song_id in zip(ranks, song_ids):\n sleep(5)\n print(song_id)\n\n req = requests.get('http://www.melon.com/song/detail.htm?songId=' + song_id, headers = header)\n html = req.text\n soup = BeautifulSoup(html, \"html.parser\")\n\n title = soup.find(attrs={\"class\": \"song_name\"}).text.replace('곡명', '')\n\n if '19금' in title:\n title = title.replace('19금', '')\n\n title = re.sub('^\\s*|\\s+$','', title)\n \n # 가수\n singers = re.sub('<[^>]*>|\\s|\\[|\\]', '', str(soup.find('div', class_ = \"artist\")))\n\n album = soup.select('#downloadfrm > div > div > div.entry > div.meta > dl > dd')[0].text\n date = soup.select('#downloadfrm > div > div > div.entry > div.meta > dl > dd')[1].text\n genre = soup.select('#downloadfrm > div > div > div.entry > div.meta > dl > dd')[2].text \n \n # 작사가\n creator = re.sub('<[^>]*>|\\s|\\[|\\]', '', str(soup.find_all(\"div\", attrs={\"class\": \"entry\"})))\n creator = re.sub('^\\s*|\\s+$', '', creator)\n clist = creator.split(',')\n creator = []\n for x in clist:\n if '작사' in x:\n creator.append(x[:-2])\n creator = ','.join(creator) \n \n # 가사\n lyric = re.sub('<[^>]*>|\\s|\\[|\\]', ' ', str(soup.find_all(attrs={\"class\": \"lyric\"})[0]))\n lyric = re.sub('^\\s*|\\s+$', '', lyric)\n \n result.append({\n 'time': re.sub('[^0-9~]', '.', year.text + week.text),\n 'rank': rank.text,\n 'song_id': song_id,\n 'title': title,\n 'singers': singers,\n 'album': album,\n 'date' : date,\n 'genre': genre,\n 'creator' : creator,\n 'lyric' : lyric\n })\n print(\"차트 기간:\", year.text +\" \"+ week.text)\n print(\"순위:\", rank.text)\n print(\"곡 id:\", song_id)\n print(\"제목:\", title)\n print(\"가수:\", singers)\n print(\"앨범:\", album)\n print(\"발매날짜:\", date)\n print(\"장르:\", genre)\n print(\"작사:\", creator)\n print(\"가사:\", lyric)\n print(\"*_*_*_*_*_*_*_*_*_*_*__*_*_*\")\n\n try:\n next_button.click()\n except:\n print(\"No next page\")\n\n with open('./result_{}_{}.csv'.format(year.text, week.text), 'w') as csvfile:\n fieldnames = [\"time\", \"rank\", \"song_id\", \"title\", \"singers\", \"album\", \"date\", \"genre\", \"creator\", \"lyric\"]\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n\n writer.writeheader()\n for i in range(len(result)):\n writer.writerow(result[i])","sub_path":"crawler/crawl.py","file_name":"crawl.py","file_ext":"py","file_size_in_byte":7006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"33595987","text":"# Resolve the problem!!\nimport re\n\nFILE_NAME = 'encoded.txt'\n\n\ndef run():\n with open(FILE_NAME, encoding = 'utf-8') as input_file:\n contents = input_file.read()\n message = ''.join(re.findall(r'[a-z]', contents))\n print(message)\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"567988486","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 8 14:29:47 2018\n\n@author: gonsoomoon\n\"\"\"\n\nimport pandas as pd\nfrom pandas import Series\n\n\nimport time\ndef time_start():\n start_time = time.time()\n return start_time\n\ndef time_end(start_time):\n end_time = time.time()\n duration = end_time - start_time\n print(\"start time: \", start_time)\n print(\"end time: \", end_time) \n print(\"Total exectution time (Min): \" + str(duration/60))\n \ndef set_seed():\n from numpy.random import seed\n seed(1)\n from tensorflow import set_random_seed\n set_random_seed(2)\n \ndef save_csv_file(data, filename=\"../debug/df.csv\"):\n if(type(data) is Series):\n df = pd.DataFrame(data.values.reshape(-1,1))\n elif(type(data) is numpy.ndarray):\n df = pd.DataFrame(data)\n elif(type(data) is list):\n df = pd.DataFrame(data)\n elif(type(data) is pd.DataFrame):\n df = data\n else:\n print(\"data is not either Series or numpy .array\")\n return None\n df.to_csv(filename)\n \n ","sub_path":"time-series-prediction/util/fresh_general_util.py","file_name":"fresh_general_util.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"484183291","text":"from collections import deque, Counter\nimport itertools\n\nfrom util.distribution import Distribution\nfrom util.pipeline import PipelineProcess, get_all_from_queue\nfrom util.schedule import create_periodic_event\n\n\nclass AudioFeature(PipelineProcess):\n\n def __init__(self, feature_id, audio_sources, audio_video_pair_map, window_length=10):\n super().__init__(pipeline_id=feature_id,\n target_function=AudioFeature.establish_process_loop,\n params=(audio_video_pair_map, window_length),\n sources=audio_sources)\n\n @staticmethod\n def establish_process_loop(input_queue, output_queue, audio_video_pair_map, window_length):\n window = deque(maxlen=window_length) # A sliding window containing the most active stream for each frame\n video_ids = set(audio_video_pair_map.values())\n\n def weight_sources():\n # Inform Python we are using vars from the outer scope.\n nonlocal window, video_ids, audio_video_pair_map\n\n source_audio = {source_id: [] for source_id in audio_video_pair_map}\n for update_step in get_all_from_queue(input_queue):\n for source_id, audio_frame_list in update_step.items():\n source_audio[source_id] += list(itertools.chain.from_iterable(audio_frame_list))\n\n # Determine loudest source; append corresponding video ID to sliding window\n max_audio_id = max(source_audio, key=lambda id: max(source_audio[id], default=0))\n window.append(audio_video_pair_map[max_audio_id])\n\n # Vote proportionally based on count in window\n vote = Distribution(Counter(window))\n for key in video_ids - vote.keys(): # add missing keys\n vote[key] = 0.0\n vote.normalize() # scale down to [0, 1]\n\n # Output vote distribution\n output_queue.put_nowait(vote)\n\n scheduler = create_periodic_event(interval=1 / 30, action=weight_sources)\n scheduler.run()\n\n\n\n\n\n","sub_path":"features/audio_feature.py","file_name":"audio_feature.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"113806443","text":"\"\"\"\n\nThis is a program designed to help someone understand the concept of recursion.\n\nA recursive function is a function that calls itself until a base condition is met.\n\nSo what does this mean? Well it means that the function in question will continue to call itself until\nthe thing it was waiting for becomes true.\n\nThe factorial of a number is simply the product of all the positive integers less than or equal to that number.\n\nIt is denoted with n!. For example 5! = 5 * 4 * 3 * 2 * 1 = 120.\n\nYou can use a recursive function to find the factorial of a given number.\n\n\"\"\"\nnumber = 0\n\n\ndef factorial(number):\n if number == 0 or number == 1:\n return 1\n else:\n return number * factorial(number - 1)\n\n\nfactorial(5)\n\n\"\"\"\n\nSo what exactly did this do? First, we have the base condition:\n\nif number == 0 or number == 1:\n return 1\n \nThis is the way to exit the recursive function. The function will not end until this is true (or the computer runs out\nof memory). \n\nThen we have the recursive bit:\n\nelse:\n return number * factorial(number - 1)\n \nIf you look closely, you can see that the function calls itself again, with a slightly different parameter. Rather\nthan calling itself with the original parameter it was given, it gives the new copy of the function the original\nparameter minus 1. I'll show you why this is important later.\n\nFinally, the code runs the recursive function with the parameter 5. This means we want to find the factorial of 5.\n\nSo how does this work in context?\n\nGiving the parameter 5, we can see that it doesn't pass the base condition. 5 is neither 0 nor 1, and so it moves on.\nThe function then runs itself, but with the original parameter (5) minus 1 (i.e 4). The function is now awaiting the\nresult of factorial(4), so that it can multiply it by its original parameter (5) and return to the caller of the\nfunction.\n\nSo now that the function has run itself and awaiting response, we can see what happens to the second iteration.\nThe function is now running with the parameter 4, which doesn't meet the base condition. It does the same thing as the\nfirst function, and multiplies its parameter (4) by the return value of itself with the parameter 3 (4 - 1). This means\nthat this iteration of the function is now awaiting the return value of itself with the new parameters.\n\nSo now we're looking at the function thats been run for a third time, this time with the parameter 3. Once again, 3\ndoesn't meet the base condition (0 or 1), and so continues to the else statement. It then tries to return its parameter\n(3) multiplied by the result of itself with the parameter (2). Awaiting the response, we follow the new iteration.\n\nThe new iteration is running with the parameter 2. Once again, it doesn't meet the base condition, so it tries to \nreturn its original parameter (2) multiplied by the result of the same function with the parameter 1.\n\nNow it gets interesting. The new instance of the function has the parameter 1, which meets the base value. This returns\n1 back to the previous function (i.e the function with the parameter of 2. The previous function, now knowing the\nvalue of the called function, it can return (2 * 1) to the function that called it.\n\nThe function that called it (i.e the function with the original parameter of 3) now can return (3 * 2) (With 2 being\nthe result of the function it called) to the function that called it. Said function (the function with the original\nparameter of 4) can now return (4 * 6) (Keep in mind that 6 is the result of 2 * 3) to the function that called it.\n\nThat function (with the original parameter of 5) is the first function to be called. It can now return the result of\n(5 * 24) to the thing that called it. That would be factorial(5), the thing that started it all. And thats how\nyou can get the value of 5!. Thats also the concept of recursive functions.\n\nOf course, there's a lot more to cover, like how it compares to iterative programming, other parts of recursion, etc -\nbut you know what, I'm too lazy to do that now. So as it stands, this is what you get. You're welcome.\n\n\"\"\"","sub_path":"understanding_recursion.py","file_name":"understanding_recursion.py","file_ext":"py","file_size_in_byte":4101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"329399671","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[7]:\n\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\n# In[8]:\n\n\n# This class create a on-lattice KMC model which simulates the\n# non-reactive surface processes.\nclass KMC_lattice():\n\n def __init__(self, height, width, k_ads_expo, p, k_des):\n\n # Height and width are sizes of the lattice we create.\n self.height = height\n\n self.width = width\n\n # Pre-exponential of adsorption rate constant.\n self.k_ads_expo = k_ads_expo\n\n # Partial pressure of adsorbates.\n self.p = p\n\n # Rate constant of desorption.\n self.alpha_ads = self.k_ads_expo * self.p\n\n # The rate constant of desorption.\n self.alpha_des = k_des\n\n # Since rate of diffusion has no influence on the results, we assume it\n # is one.\n self.alpha_diff = 1\n\n # Since for different events, there are different rate constants.\n # We Create a list named \"alpha_type\" to store different types of\n # alpha.\n self.alpha_type = [self.alpha_ads, self.alpha_des, self.alpha_diff]\n\n self.t = 0\n\n # Initialize a vacant lattice based on the given height and width.\n # Create a list named 'lattice_state' which contains the state(vacant or occupied)\n # of all sites on the lattice.\n # If a value in the list 'lattice_state' equals zero, it means the corresponding site\n # is vacant. If it is one, it means the site is occupied.\n\n def lattice_initialization(self):\n twoD_matrix = np.zeros((self.height, self.width), dtype=np.int)\n lattice_state = []\n for x_pos in range(self.height):\n for y_pos in range(self.width):\n lattice_state.append(twoD_matrix[x_pos, y_pos])\n return twoD_matrix, lattice_state\n\n # This function gives a list named 'neighbours' which contains the four neighbouring site's\n # states of each site on the lattice.\n # The list 'neighbours' looks like [[0,1,0,1],[0,0,0,0], [1,0,1,0],...]\n\n def site_neighbours(self):\n\n neighbours = []\n self.N_sites = np.size(self.twoD_matrix)\n\n for n in range(self.N_sites):\n # upper-left corner site\n if n == 0:\n up = (self.height - 1) * self.width\n right = n + 1\n down = n + self.width\n left = self.width - 1\n\n # uppermost boundary sites except lupper-eft and upper-right corner\n # sites\n elif 0 < n < self.width - 1:\n up = n + (self.height - 1) * self.width\n right = n + 1\n down = n + self.width\n left = n - 1\n\n # upper-right corner site\n elif n == self.width - 1:\n up = self.height * self.width - 1\n right = 0\n down = n + self.width\n left = n - 1\n\n # bottom-left corner site\n elif n == (self.height - 1) * self.width:\n up = n - self.width\n right = n + 1\n down = 0\n left = self.height * self.width - 1\n\n # bottom-right corner site\n elif n == self.height * self.width - 1:\n up = n - self.width\n right = (self.height - 1) * self.width\n down = self.width - 1\n left = n - 1\n\n # bottom sites except bottom-left and bottom-right corner sites\n elif (self.height - 1) * self.width < n < self.height * self.width - 1:\n up = n - self.width\n right = n + 1\n down = n - (self.height - 1) * self.width\n left = n - 1\n\n # left boundary sites except upper-left and bottom-left corner\n # sites\n elif n % self.width == 0 & n != 0 & n != (self.height - 1) * self.width:\n up = n - self.width\n right = n + 1\n down = n + self.width\n left = n + self.width - 1\n\n # right boundary sites except upper-right and bottom-right corner\n # sites\n elif (n + 1) % self.width == 0 & n != self.width - 1 & n != self.height * self.width - 1:\n up = n - self.width\n right = n - (self.width - 1)\n down = n + self.width\n left = n - 1\n\n # inner sites\n else:\n up = n - self.width\n right = n + 1\n down = n + self.width\n left = n - 1\n\n neighbours.append([up, right, down, left])\n\n return neighbours, self.N_sites\n\n def events_list(self):\n\n events = []\n\n alpha_list = []\n\n for i_site in range(self.N_sites):\n\n # This site is vacant. The only possible elementary event for it is\n # adsorption.\n if self.lattice_state[i_site] == 0:\n\n # 7 denotes adsorption\n i_site_event = [7]\n\n alpha_list.append(self.alpha_type[0])\n\n # This site is occupied and the events of this site depends on\n # status of its 4 neighbouring sites.\n else:\n\n # This site is occupied and its four neighbouring sites are vacant.\n # There are 5 possible events for this site. Go up/right/down/left or desorption.\n # 0 denotes the vacant site.\n # 1 denotes the occupied site.\n # 6 desorption\n # 7 adsorption\n # 8 go up\n # 9 go right\n # 10 go down\n # 11 left\n if self.neighbours[i_site] == [0, 0, 0, 0]:\n i_site_event = [8, 9, 10, 11, 6]\n # with no occupied neighbouring site\n alpha_list.append(self.alpha_type[2])\n alpha_list.append(self.alpha_type[2])\n alpha_list.append(self.alpha_type[2])\n alpha_list.append(self.alpha_type[2])\n alpha_list.append(self.alpha_type[1])\n\n else:\n if np.sum(self.neighbours[i_site]) == 1:\n\n if self.neighbours[i_site] == [1, 0, 0, 0]:\n i_site_event = [9, 10, 11, 6]\n\n elif self.neighbours[i_site] == [0, 1, 0, 0]:\n i_site_event = [8, 10, 11, 6]\n\n elif self.neighbours[i_site] == [0, 0, 1, 0]:\n i_site_event = [8, 9, 11, 6]\n\n else:\n # status_i_neighbours == [0,0,0,1]:\n i_site_event = [8, 9, 10, 6]\n\n # with one occupied neighbouring site\n alpha_list.append(self.alpha_type[2])\n alpha_list.append(self.alpha_type[2])\n alpha_list.append(self.alpha_type[2])\n alpha_list.append(self.alpha_type[1])\n\n elif np.sum(self.neighbours[i_site]) == 2:\n\n if self.neighbours[i_site] == [1, 1, 0, 0]:\n i_site_event = [10, 11, 6]\n\n elif self.neighbours[i_site] == [1, 0, 1, 0]:\n i_site_event = [9, 11, 6]\n\n elif self.neighbours[i_site] == [1, 0, 0, 1]:\n i_site_event = [9, 10, 6]\n\n elif self.neighbours[i_site] == [0, 1, 1, 0]:\n i_site_event = [8, 11, 6]\n\n elif self.neighbours[i_site] == [0, 1, 0, 1]:\n i_site_event = [8, 10, 6]\n\n else:\n # status_i_neighbours == [0,0,1,1]:\n i_site_event = [8, 9, 6]\n\n # with two occupied neighbouring site\n alpha_list.append(self.alpha_type[2])\n alpha_list.append(self.alpha_type[2])\n alpha_list.append(self.alpha_type[1])\n\n elif np.sum(self.neighbours[i_site]) == 3:\n\n if self.neighbours[i_site] == [1, 1, 1, 0]:\n i_site_event = [11, 6]\n\n elif self.neighbours[i_site] == [1, 1, 0, 1]:\n i_site_event = [10, 6]\n\n elif self.neighbours[i_site] == [1, 0, 1, 1]:\n i_site_event = [9, 6]\n\n else:\n # status_i_neighbours == [0,1,1,1]:\n i_site_event = [8, 6]\n\n # with three occupied neighbouring site\n alpha_list.append(self.alpha_type[2])\n alpha_list.append(self.alpha_type[1])\n\n # This site is occupied and all of its neighbouring sites are occupied.\n # The only possible elementary event is desorption.\n else:\n i_site_event = [6]\n alpha_list.append(self.alpha_type[1])\n\n events.append(i_site_event)\n\n return events, alpha_list\n\n # This function gives sum of rate constants of all events.\n def sum_of_alpha(self):\n\n sum_alpha = np.sum(self.alpha_list)\n\n return sum_alpha\n\n # This function gives a random waiting time for the selected event.\n def waiting_time_generation(self):\n\n r1 = np.random.rand()\n\n waiting_time = - 1.0 / self.sum_alpha * np.log(1.0 - r1)\n\n return waiting_time\n\n # Direct method.\n\n def site_event_selection(self):\n\n r2 = np.random.rand()\n\n left_side = 0\n\n medium = 0\n\n right_side = self.alpha_list[medium]\n\n exit_flag = False\n\n for i_site in range(self.N_sites):\n\n for i_event in range(len(self.events[i_site])):\n\n if left_side < r2 * self.sum_alpha < right_side:\n\n site_to_change = i_site\n\n which_event_to_execute = i_event\n\n exit_flag = True\n\n break\n\n else:\n\n left_side = right_side\n\n medium += 1\n\n right_side += self.alpha_list[medium]\n\n if exit_flag:\n\n break\n\n return site_to_change, which_event_to_execute\n\n # Once an event is executed, this function updates the list\n # 'lattice_state'.\n def event_executing(self):\n\n event_chosen = self.events[self.site_to_change][self.which_event_to_execute]\n\n # desorption\n if event_chosen == 6:\n self.lattice_state[self.site_to_change] = 0\n\n # adsorption\n elif event_chosen == 7:\n self.lattice_state[self.site_to_change] = 1\n\n # go up\n elif event_chosen == 8:\n self.lattice_state[site_to_change] = 0\n site_influenced = self.neighbours[self.site_to_change][0]\n self.lattice_state[site_influenced] = 1\n\n # go right\n elif event_chosen == 9:\n self.lattice_state[self.site_to_change] = 0\n site_influenced = self.neighbours[self.site_to_change][1]\n self.lattice_state[site_influenced] = 1\n\n # go down\n elif event_chosen == 10:\n self.lattice_state[site_to_change] = 0\n site_influenced = self.neighbours[self.site_to_change][2]\n self.lattice_state[site_influenced] = 1\n\n # go left (event_chosen == 11)\n else:\n self.lattice_state[self.site_to_change] = 0\n site_influenced = self.neighbours[self.site_to_change][3]\n self.lattice_state[site_influenced] = 1\n\n return self.lattice_state\n\n # This function calculates the coverage of the lattice.\n def coverage(self):\n\n num_occupied = np.sum(self.lattice_state)\n\n cov = num_occupied / len(self.lattice_state)\n\n return cov\n\n def events_progressing(self):\n\n self.twoD_matrix, self.lattice_state = self.lattice_initialization()\n\n self.neighbours, self.N_sites = self.site_neighbours()\n\n cov_all = []\n\n time_all = []\n\n for i in range(10000):\n\n self.cov = self.coverage()\n\n cov_all.append(self.cov)\n\n self.events, self.alpha_list = self.events_list()\n\n self.sum_alpha = self.sum_of_alpha()\n\n self.waiting_time = self.waiting_time_generation()\n\n self.site_to_change, self.which_event_to_execute = self.site_event_selection()\n\n self.lattice_state = self.event_executing()\n\n time_all.append(self.t)\n\n self.t += self.waiting_time\n\n average_coverage = np.sum(cov_all) / len(cov_all)\n\n print('The average covergae from KMC simulation is {0}.'.format(average_coverage))\n\n return cov_all, time_all\n\n def plot(self):\n cov_all, time_all = self.events_progressing()\n plt.figure()\n plt.plot(time_all, cov_all, color='black')\n plt.xlabel('time')\n plt.ylabel('coverage')\n plt.title('Simulation results of KMC')\n plt.savefig('average coverage from KMC simulation')\n plt.show()\n\n\n# In[ ]:\n\n\n# In[ ]:\n","sub_path":"OnLatticeKMC.py","file_name":"OnLatticeKMC.py","file_ext":"py","file_size_in_byte":13308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"241889150","text":"# -*- coding: utf-8 -*- \n# @Time : 2021/4/7 9:25 \n# @Author : 张丽雯 \n# @File : test_weightwo.py \n# @中文描述 : 称量工单-用例\nimport sys\nimport pytest\nfrom DataApp.WeightWoData import *\nfrom src.pageobjectAPP.pageWeightwo import *\nfrom src.public.common.Close_current_tab import Close_current_tab\nfrom src.public.common.Search_Item import *\n\n\nclass Test_Weightwo:\n def setup_class(self):\n app_login(username, password)\n login_weightwo()\n\n def teardown_class(self):\n Close_current_tab()\n app_logout()\n\n # 称量工单-筛选工单\n def test_weightwo_search(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n search_item('编码', WO1)\n sleep(1)\n assert is_text_present(WO1)\n\n # 称量工单-净重模式-结束称量\n @pytest.mark.parametrize('n,tare,selectmode', over_net)\n def test_weightwo_net_001(self, n, tare, selectmode):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n weight_wo_net(n, tare, selectmode)\n sleep(1)\n assert new_page_source('保存成功')\n\n # 称量工单-净重模式-取消称量\n @pytest.mark.parametrize('n,tare,selectmode', cancel_net)\n def test_weightwo_net_002(self, n, tare, selectmode):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n weight_wo_net(n, tare, selectmode)\n sleep(1)\n assert new_js_text(input_container) == ''\n\n # 称量工单-净重模式-相同容器\n @pytest.mark.parametrize('n,tare,selectmode', same_net)\n def test_weightwo_net_003(self, n, tare, selectmode):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n weight_wo_net(n, tare, selectmode)\n sleep(1)\n assert new_page_source('保存成功')\n\n # 称量工单-人工输入模式\n @pytest.mark.parametrize('n, netvalue, tarevalue', manual_list)\n def test_weightwo_manual(self, n, netvalue, tarevalue):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n weight_wo_manual(n, netvalue, tarevalue)\n assert new_page_source('保存成功')\n\n # 称量工单-计数称量模式\n @pytest.mark.parametrize('n,tare',count_list)\n def test_weightwo_count(self,n,tare):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n search_item('编码', WO2)\n sleep(1)\n weight_wo_count(n,tare)\n sleep(1)\n assert new_page_source('保存成功')\n\n # 称量工单-批次信息\n def test_weightwo_lot_detail(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n weight_wo_lot_detail('0')\n sleep(1)\n assert new_js_text(input_container) != ''\n\n # 称量工单-取消称量\n @pytest.mark.parametrize('n,cancel1,cancel2', [('0', '取消称量', '否'), ('0', '否', '取消称量')])\n def test_weightwo_cancel_weight(self, n, cancel1, cancel2):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n weight_wo_cancel(n, cancel1, cancel2)\n sleep(2)\n assert new_js_text(input_container) == ''\n\n\t # 毛重称量\n def test_gross_weigh(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n grossweighmode(\"0.2\")\n time.sleep(2)\n\n # RM混合\n def test_rmmix_weigh(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n rmweighmode(\"0.2\")\n time.sleep(2)\n\n # 称量次数\n def test_weigh_times(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n sleep(7)\n times1 = new_js_text(weightimes)\n grossweighmode(\"0.2\")\n time.sleep(2)\n times2 = new_js_text(weightimes)\n assert int(times1)+1 == int(times2)\n\n # 总重量\n def test_total_weigh(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n sleep(7)\n weigh1 = new_js_text(totalweigh)\n grossweighmode(\"0.2\")\n time.sleep(2)\n weigh2 = new_js_text(totalweigh)\n assert float(weigh1)+3.087 == float(weigh2)\n\n # 强制称量\n def test_force_weigh(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n forceweigh()\n assert new_page_source('称量完成')\n\n # 物料信息\n def test_material_info(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n material_info()\n sleep(1)\n assert new_get_text(stage) == '0001'\n assert new_get_text(seq) == '0001'\n assert new_get_text(dose) == '1'\n new_click(closed)\n\n # 托盘标签\n def test_pallet_label(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n pallet_label()\n assert new_get_text(alert_txt) == '打印信息发送成功'\n\n\n # 输入容器识别号-容器号不存在\n @pytest.mark.parametrize('CID', ['1232323'])\n def test_weightwo_containerid_adnormal_001(self, CID):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n weight_wo_container_ID(CID)\n sleep(1)\n assert is_text_present('不存在该批次信息的容器')\n\n # 输入容器识别号-容器已过期\n @pytest.mark.parametrize('CID', ['RL00000033 0001'])\n def test_weightwo_containerid_adnormal_002(self, CID):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n weight_wo_container_ID(CID)\n sleep(1)\n assert is_text_present('容器已过期')\n\n # 净重称量模式-剩余量正确性比对\n def test_weightwo_net_remain(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n # 选择称量工单物料\n new_click(material(n3))\n sleep(1)\n remain1 = float(new_js_text(remain_number))\n weight_wo_net(n3, tarevalue1, selectmode1)\n sleep(1)\n remain2 = float(new_js_text(remain_number))\n net = round(remain1 - remain2, 3)\n weight_wo_net(n3, tarevalue1, selectmode1)\n sleep(1)\n remain3 = round(float(new_js_text(remain_number)), 3)\n assert remain3 == round(remain2 - net, 3)\n\n # 人工输入模式-剩余量正确性比对\n def test_weightwo_manual_remain(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n # 选择称量工单物料\n new_click(material(n3))\n sleep(1)\n remain1 = float(new_js_text(remain_number))\n weight_wo_manual(n3, '10', '0.002')\n sleep(1)\n remain2 = float(new_js_text(remain_number))\n assert remain2 == remain1 - 10\n\n # 净重称量模式-净重正确性比对\n def test_weightwo_net_netvalue(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n # 选择称量工单物料\n weight_wo_net_netvalue(n3, tarevalue1)\n sleep(1)\n netvalue = new_js_text(net_number)\n # 3.090是秤的度数,这值根据实际情况而定\n assert netvalue == '3.090'\n new_click(CanWeigh)\n\n # 净重称量模式-皮重正确性比对\n def test_weightwo_net_tarevalue(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n # 选择称量工单物料\n weight_wo_net_netvalue(n3, '0.033')\n sleep(1)\n tare_value = new_js_text(tare_number)\n assert tare_value == '0.033'\n","sub_path":"TestcaseApp/Weigh/test_weightwo.py","file_name":"test_weightwo.py","file_ext":"py","file_size_in_byte":7451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"439807143","text":"def height(root):\n if not root:\n return 0\n return 1 + max(height(root.left), height(root.right))\n\ndef recursive_append(node,cur_height,lo,hi,output):\n if node is None:\n return\n mid = (lo + hi)//2\n output[cur_height][mid] = str(node.val)\n recursive_append(node.left,cur_height+1,lo,mid-1,output)\n recursive_append(node.right,cur_height+1,mid+1,hi,output)\n\n\ndef binaryTreeToStr(root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[str]]\n \"\"\"\n tree_height = height(root)\n length = 2**tree_height-1\n output = [[\" \" for x in range(length)] for x in range(tree_height)]\n recursive_append(root,0,0,length-1,output)\n str_out = \"\"\n for row in output:\n for c in row:\n str_out += c\n str_out += \"\\n\"\n return str_out","sub_path":"Recursion/prettyPrint.py","file_name":"prettyPrint.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"47897672","text":"from itertools import combinations, chain\nfrom collections import Counter\n\n\ndef generation_list(total_person):\n \"\"\"Создает список человек\"\"\"\n return [x + 1 for x in range(total_person)]\n\n\ndef count_elements(general_list, list_of_elements):\n \"\"\"Считает количество переданных элементов в списке\"\"\"\n count = Counter(general_list)\n res = {i: count[i] for i in list_of_elements}\n return res\n\n\ndef get_a_combination(roll, count=2, iterable=False):\n \"\"\"Составляет все пары для списка\n (также можно использовать для генерации любых других\n сочетаний указывая второй параметр, а ещё получать итерируемый объект)\"\"\"\n if iterable:\n return combinations(roll, count)\n else:\n return list(combinations(roll, count))\n\n\ndef find_pairs(schedule):\n \"\"\"Функция составляет пары для каждой смены в переданном расписании\"\"\"\n return [get_a_combination(shift) for shift in schedule]\n\n\ndef concatenate_lists(lists):\n \"\"\"Функция сцепляет несколько списков в один\"\"\"\n return list(chain(*lists))\n\n\ndef did_everyone_meet(schedule, all_pairs):\n \"\"\"Проверяет все ли встетились в переданном расписании\"\"\"\n return 0 not in count_elements(concatenate_lists(find_pairs(schedule)), all_pairs).values()\n\n\ndef calc(number_of_people, people_in_shift):\n \"\"\"Считает расписания с указанными данными\"\"\"\n # Определение задачи\n list_people = generation_list(number_of_people)\n all_pairs = get_a_combination(list_people)\n all_shifts = get_a_combination(list_people, people_in_shift)\n list_schedule = []\n\n number_of_shifts = 0\n find_min_count_shift = True\n while find_min_count_shift:\n # Итерируемый объект - все варианты расписаний для переданного кол-ва смен\n timetables = get_a_combination(all_shifts, number_of_shifts, True)\n for schedule in timetables:\n if did_everyone_meet(schedule, all_pairs):\n find_min_count_shift = False\n list_schedule.append(schedule)\n number_of_shifts += 1\n return list_schedule\n\n\nif __name__ == '__main__':\n i, j = map(int, input('Кол-во игроков и кол-во людей в смене (через пробел): ').split())\n timetables = calc(i, j)\n [print(i) for i in timetables]\n input()\n","sub_path":"v1/1.1/make_a_schedule.py","file_name":"make_a_schedule.py","file_ext":"py","file_size_in_byte":2706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"635652581","text":"import tornado.options\nimport tornado.httpserver\nimport tornado.ioloop\n\nimport logging\nimport os\n\nimport app.main\nimport app.courses\nimport app.affairs\nimport app.dining\nimport app.athletics\nimport app.housing\nimport app.uem\nimport app.auth\nimport app.documentation\n\n\nclass Application(tornado.web.Application):\n def __init__(self):\n logging.getLogger().setLevel(logging.DEBUG)\n\n app_settings = {\n 'debug': \"dev\",\n \"xsrf_cookies\" : False,\n \"cookie_secret\" : \"32oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=\",\n \"template_path\" : os.path.join(os.path.dirname(__file__), \"templates\"),\n \"static_path\" : os.path.join(os.path.dirname(__file__), \"static\"),\n \"autoescape\" : None,\n \"login_url\" : \"http://data.adicu.com/login\",\n }\n\n handlers = [\n (r\"/$\", app.main.MainHandler),\n (r\"/ping$\", PingHandler),\n (r\"/courses$\", app.courses.CoursesHandler),\n (r\"/dining$\", app.dining.DiningHandler),\n (r\"/uem$\", app.uem.UemHandler),\n (r\"/affairs$\", app.affairs.AffairsHandler),\n (r\"/affairs/([^/]+)\", app.affairs.AffairsHandler),\n (r\"/athletics$\", app.athletics.athleticsHandler),\n (r\"/housing/rooms$\", app.housing.RoomHandler),\n (r\"/housing/buildings$\", app.housing.BuildingHandler),\n (r\"/docs$\", app.main.MainHandler),\n (r\"/docs/([^/]+)\", app.documentation.DocsHandler),\n (r\"/login$\", app.auth.LoginHandler),\n (r\"/logout$\", app.auth.LogoutHandler),\n (r\"/profile$\", app.main.ProfileHandler),\n\n ]\n debug = True\n tornado.web.Application.__init__(self, handlers, **app_settings)\n\nclass PingHandler(tornado.web.RequestHandler):\n def get(self):\n self.finish('OK')\n def head(self):\n self.finish('OK')\n\n\nif __name__ == \"__main__\":\n # this port should be unique system wide; all ports used should be listed in ~/services.py\n tornado.options.define(\"port\", default=int(os.environ[\"PORT\"]), help=\"Listen on port\", type=int)\n tornado.options.parse_command_line()\n logging.info(\"starting app on 0.0.0.0:%d\" % tornado.options.options.port)\n http_server = tornado.httpserver.HTTPServer(request_callback=Application())\n http_server.listen(tornado.options.options.port, address=\"0.0.0.0\")\n tornado.ioloop.IOLoop.instance().start()\n","sub_path":"data/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"250917053","text":"import os\nimport sys\nimport click\nfrom stringprocessor import StringProcessor as sp\nimport loggers\n\nimport app\nfrom yammler import DownloadLog\nfrom settings import (\n FSEC_DOWNLOAD_DIR,\n EXCLUDE_TOKENS,\n FSEC_FTP_URL,\n FSEC_OUTPUT_DIR,\n FSEC_TO_CSV,\n FSEC_TO_DATABASE,\n DATABASE_URI,\n FRAC_SCHEDULE_TABLENAME,\n DOWNLOADLOGPATH,\n)\nfrom util import tokenize\n\n\nCONTEXT_SETTINGS = dict(help_option_names=[\"-h\", \"--help\"])\n\nOP_COLOR = \"red\"\n\n\ndef set_verbosity(level: int):\n if level is not None:\n loggers.standard_config(verbosity=level)\n\n\n@click.group(context_settings=CONTEXT_SETTINGS)\ndef cli():\n pass\n\n\n@click.command()\n@click.option(\n \"--download_to\",\n \"-d\",\n default=os.path.abspath(FSEC_DOWNLOAD_DIR or \"\") or os.path.abspath(\"./data\"),\n show_default=True,\n help=f\"Directory to save downloads from the FTP ({FSEC_FTP_URL}). If no location is specified here, the file will be downloaded to the value of the FSEC_DOWNLOAD_DIR environment variable. If that also doesn't exists, the schedule will be downloaded to the ./data directory in the project root.\",\n type=click.Path(exists=True, dir_okay=True, file_okay=False),\n envvar=\"FSEC_DOWNLOAD_DIR\",\n)\n@click.option(\n \"--output_to\",\n \"-out\",\n default=os.path.abspath(FSEC_OUTPUT_DIR or \"\") or os.path.abspath(\"./output\"),\n show_default=True,\n help=f\"Directory to save the parsed output schedule. If no location is specified here, the output will be saved to the location specified in the FSEC_OUTPUT_DIR environment variable. If that also doesn't exists, the schedule will be saved to the ./output directory in the project root.\",\n type=click.Path(exists=True, dir_okay=True, file_okay=False),\n envvar=\"FSEC_OUTPUT_DIR\",\n)\n@click.option(\n \"--no-download\",\n is_flag=True,\n show_default=True,\n help=f\"Skips downloading any new files before initiating the parsing process. If enabled, only existing files will be parsed.\",\n)\n@click.option(\"--no-parse\", is_flag=True, help=f\"Skips parsing the frac schedules.\")\n@click.option(\n \"--no-cleanup\",\n is_flag=True,\n show_default=True,\n help=f\"Disables the removal of previously downloaded frac schedules.\",\n)\n@click.option(\n \"--verbose\",\n \"-v\",\n help=\"Set the verbosity level. A higher verbosity level will generate more output during the process' execution. Repeat the flag to increase the verbosity level. (ex. -vvv)\",\n show_default=True,\n count=True,\n)\n@click.pass_context\ndef run(ctx, download_to, no_download, no_parse, no_cleanup, verbose):\n \"\"\"Run the app\"\"\"\n set_verbosity(verbose)\n\n app.run(to, no_cleanup=no_cleanup, no_download=no_download, no_parse=no_parse)\n\n\n@click.command()\n@click.option(\n \"--path\",\n \"-p\",\n default=os.path.abspath(FSEC_DOWNLOAD_DIR or \"\") or os.path.abspath(\"./data\"),\n show_default=True,\n help=\"Specify an alternate filepath to the directory containing the frac schedules.\",\n type=click.Path(exists=True, dir_okay=True, file_okay=False),\n envvar=(\"FSEC_DOWNLOAD_DIR\"),\n)\n@click.option(\n \"--verbose\",\n \"-v\",\n help=\"Set the verbosity level. A higher verbosity level will generate more output during the process' execution. Repeat the flag to increase the verbosity level. (ex. -vvv)\",\n show_default=True,\n count=True,\n)\ndef show(path, verbose):\n \"List the currently downloaded frac schedules\"\n click.secho(\n \"\\n\" + f\"Current download directory: {os.path.abspath(path)}\",\n bold=True,\n fg=\"cyan\",\n )\n paths = app.list_downloads(os.path.abspath(path))\n op_paths = app.operator_filenames(paths)\n click.secho(\n \"\\n\"\n + f\"{'operator alias':<25} {'original name':<25} {'conf':<10} {'filename':<75}\",\n bold=True,\n )\n click.secho(\"-\" * 125 + \"\\n\", bold=True)\n for idx, x in enumerate(op_paths):\n path, op = x\n p = os.path.basename(path)\n\n click.secho(\n f\"{op.alias:<25} {op.orig:<25} {op.pscore:<10} {p:<75}\",\n dim=True if idx % 2 else False,\n )\n\n click.secho(\"\\n\" + \"-\" * 125 + \"\\n\", bold=True)\n\n\n@click.command()\n@click.option(\n \"--to\",\n \"-t\",\n default=os.path.abspath(FSEC_DOWNLOAD_DIR or \"\") or os.path.abspath(\"./data\"),\n show_default=True,\n help=f\"Directory to save downloads from the FTP ({FSEC_FTP_URL}). If no location is specified here, the file will be downloaded to the value of the FSEC_DOWNLOAD_DIR environment variable. If that also doesn't exists, the schedule will be downloaded to the ./data directory in the project root.\",\n type=click.Path(exists=True, dir_okay=True, file_okay=False),\n envvar=\"FSEC_DOWNLOAD_DIR\",\n)\n@click.option(\n \"--verbose\",\n \"-v\",\n help=\"Set the verbosity level. A higher verbosity level will generate more output during the process' execution. Repeat the flag to increase the verbosity level. (ex. -vvv)\",\n show_default=True,\n count=True,\n)\ndef download(to, verbose):\n \"Download all frac schedules\"\n\n set_verbosity(verbose)\n click.echo(\n click.style(\n \"\\n\" + f\"Downloading frac schedules to: {os.path.abspath(to)}\",\n fg=\"cyan\",\n bold=True,\n )\n )\n\n with DownloadLog.context(DOWNLOADLOGPATH) as dlog:\n for path, filename, status in app.download(to):\n click.secho(\n f\"{filename:<60} {status:<25}\",\n fg=\"green\" if status == \"success\" else \"red\",\n )\n dlog.add(os.path.abspath(os.path.join(path, filename)))\n\n\n@click.command()\n@click.option(\n \"--operator\",\n \"-o\",\n help=\"Attempt to locate and parse an operator's latest frac schedule\",\n)\n@click.option(\n \"--filename\",\n \"-f\",\n help=\"Parse a specific frac schedule\",\n type=click.Path(exists=True, dir_okay=False, file_okay=True),\n)\n@click.option(\n \"--directory\",\n \"-d\",\n default=os.path.abspath(FSEC_DOWNLOAD_DIR or \"\") or os.path.abspath(\"./data\"),\n show_default=True,\n help=\"Parse all frac schedules in a directory. The directory should ONLY include original frac schedules.\",\n type=click.Path(exists=True, dir_okay=True, file_okay=False),\n envvar=\"FSEC_DOWNLOAD_DIR\",\n)\n@click.option(\n \"--to\",\n \"-t\",\n default=os.path.abspath(FSEC_OUTPUT_DIR or \"\") or os.path.abspath(\"./output\"),\n show_default=True,\n help=f\"Directory to save the parsed output schedule. If no location is specified here, the output will be saved to the location specified in the FSEC_OUTPUT_DIR environment variable.\",\n type=click.Path(exists=True, dir_okay=True, file_okay=False),\n envvar=\"FSEC_OUTPUT_DIR\",\n)\n@click.option(\n \"--merge\",\n \"-m\",\n is_flag=True,\n default=True,\n help=f\"Option to merge the parsed output into a single file.\",\n show_default=True,\n envvar=\"FSEC_AUTO_MERGE\",\n)\n@click.option(\n \"--csv\",\n \"-c\",\n is_flag=True,\n default=True,\n help=f\"Option to save parsed output as a csv file\",\n show_default=True,\n envvar=\"FSEC_TO_CSV\",\n)\n@click.option(\n \"--db\",\n is_flag=True,\n default=FSEC_TO_DATABASE or False,\n help=f\"Option to save the parsed output to the configured database. The currently configured database is: {DATABASE_URI.split('@')[-1]}. The frac schedule table is set to {FSEC_FRAC_SCHEDULE_TABLE}\",\n show_default=True,\n envvar=\"FSEC_TO_DATABASE\",\n)\n@click.option(\n \"--verbose\",\n \"-v\",\n help=\"Set the verbosity level. A higher verbosity level will generate more output during the process' execution. Repeat the flag to increase the verbosity level. (ex. -vvv)\",\n show_default=True,\n count=True,\n)\n@click.pass_context\ndef parse(ctx, to, operator, filename, directory, merge, csv, db, verbose):\n \"Parse a frac schedule\"\n\n set_verbosity(verbose)\n from operator_index import Operator\n import pandas as pd\n\n click.echo(\"\") # spacer\n path = None\n to_parse = []\n try:\n basepath = os.path.abspath(directory or FSEC_DOWNLOAD_DIR)\n paths: list = app.list_downloads(basepath)\n paths_with_ops: list = app.operator_filenames(paths, with_index=False)\n except Exception:\n raise Exception(\"Unable to load paths\")\n\n if operator is not None:\n op = Operator(operator)\n # search in paths for resemblence to passed operator name\n to_parse = [f for f in paths_with_ops if f[1].alias == op.alias]\n\n elif filename is not None:\n # search in paths based on matching the given filename\n filename = os.path.basename(filename)\n to_parse = [f for f in paths_with_ops if os.path.basename(f[0]) == filename]\n\n elif directory is not None:\n # parse 'em all\n to_parse = paths_with_ops\n\n if len(to_parse) > 0:\n n = len(to_parse)\n click.secho(f\"Found {n} schedule{'s' if n > 1 else ''} to parse\", fg=\"green\")\n click.secho(\"\\n\" + \"-\" * 125 + \"\\n\", bold=True, dim=True)\n\n else:\n msg = f\"Could not find any frac schedules matching the given criteria :(\"\n click.secho(\"\\n\" + msg, bold=True, fg=\"red\")\n ctx.invoke(show, path=basepath)\n\n # print(\"\\n\".join([x[0] for x in to_parse]))\n # return 0\n # click.secho(\"\\n\" + f\"parsing {n} schedules...\")\n parsers = []\n to_save = []\n\n click.secho() # spacer\n for p, op in to_parse:\n path = os.path.dirname(p)\n basename = os.path.basename(p)\n\n pl = click.style(\"(\", dim=True)\n pr = click.style(\")\", dim=True)\n fs = click.style(\"/\", dim=True)\n # s = click.style(f\"{spath} {p1}{sop_a}{fs}{sop_n}{p2}\", dim=True)\n\n try:\n parser = app.parse(filepath=p)\n\n color = \"red\"\n msgs = []\n dim = True\n\n if parser.status == \"ok\":\n color = \"green\"\n bold = False\n elif parser.status == \"warning\":\n color = \"yellow\"\n msgs = parser.status_messages[\"warning\"]\n dim = False\n bold = True\n elif parser.status == \"error\":\n color = \"red\"\n msgs = parser.status_messages[\"error\"]\n dim = False\n bold = True\n else:\n pass\n\n s_basename = click.style(\n basename,\n dim=True if parser.status == \"ok\" else False,\n bold=False if parser.status == \"ok\" else True,\n fg=\"white\" if parser.status == \"ok\" else color,\n )\n s_status = click.style(\n f\"{op.name:<20} {parser.status:<10}\", fg=color, bold=bold\n )\n s_n_records = click.style(f\"{len(parser.df)} records\", dim=True)\n\n click.echo(f\"{s_status} {s_basename} {pl}{s_n_records}{pr}\")\n # print([\"messages\"] + msgs)\n if len(msgs) > 0:\n\n for m in msgs:\n click.secho(\"\\t\" + m, bold=True, fg=color)\n # for m in msgs:\n # for cats in m:\n # for c in cats:\n # click.secho(c, fg=color, bold=False)\n\n parsers.append(parser)\n\n if not merge:\n to_save.append((op.alias, p.df, None))\n\n except:\n s_basename = f\"{click.style(basename, dim=False, bold=True, fg=color)}\"\n s_status = click.style(\n f\"{op.name:<20} {parser.status:<10}\", fg=color, bold=True\n )\n s_n_records = click.style(f\"{len(parser.df)} records\", dim=True)\n\n click.secho(f\"{s_status} {s_basename} {pl}{s_n_records}{pr}\")\n\n click.secho(\"\\n\" + \"-\" * 125 + \"\\n\", bold=True, dim=True)\n\n if merge:\n df = pd.concat([p.df for p in parsers], sort=False)\n to_save.append((\"Combined frac schedule saved to:\", df, \"frac-schedules\"))\n\n nframes = len(to_save)\n\n if db:\n # click.secho(f\"Saving {nframes} schedule{'s' if nframes > 1 else ''}\")\n\n for msg, frame, _ in to_save:\n try:\n n = frame.shape[0]\n loc = app.to_db(frame)\n click.secho(f\"{msg} -> {loc} ({n} records)\", bold=True)\n except Exception as e:\n click.secho(\n f\"{msg} -> Failed writing to database: {e}\", fg=\"red\", bold=True\n )\n csv = True\n click.secho(f\"{msg} -> Trying csv instead...\", fg=\"yellow\")\n\n if csv:\n # click.secho(f\"Saving {nframes} csv file{'s' if nframes > 1 else ''}\")\n\n for msg, frame, prefix in to_save:\n s_n = click.style(f\"({frame.shape[0]} records)\", dim=True)\n s_loc = click.style(\n os.path.basename(app.to_csv(frame, to, prefix)), bold=True, fg=\"cyan\"\n )\n try:\n if n > 0:\n click.secho(f\"{msg} -> {s_loc} {s_n}\" + \"\\n\\n\")\n except Exception as e:\n click.secho(f\"{msg} -> Failed writing to csv: {e}\" + \"\\n\\n\", fg=\"red\")\n\n\n@click.command()\n@click.option(\"--simulate\", \"-s\", is_flag=True, default=False, show_default=True)\n@click.option(\"--force\", \"-f\", is_flag=True, default=False, show_default=True)\ndef cleanup(simulate, force):\n to_be_cleaned = os.path.abspath(FSEC_DOWNLOAD_DIR)\n ct = 0\n click.echo() # spacer\n for fname, status, status_message in app.remove_previous_downloads(\n to_be_cleaned, simulate\n ):\n\n if status == \"success\":\n color = \"green\"\n elif status == \"warning\":\n color = \"yellow\"\n elif status == \"failed\":\n color = \"red\"\n else:\n color = \"white\"\n\n click.secho(f\"{fname:<60} {status_message}\", fg=color, bold=False)\n ct += 1\n click.secho(\n \"\\n\" + f\"Deleted {ct} frac schedules from {to_be_cleaned}\" + \"\\n\",\n fg=\"cyan\",\n bold=True,\n )\n\n remaining = os.listdir(to_be_cleaned)\n n = len(remaining)\n\n if n > 0:\n click.secho(\n f\"{n} lingering file{'s' if n > 0 else ''} in {to_be_cleaned}\" + \"\\n\",\n dim=False if n > 0 else True,\n fg=\"yellow\" if n > 0 else \"white\",\n bold=True if n > 0 else False,\n )\n\n for f in remaining:\n click.secho(\"\\t\" + f\"{f}\", bold=False, dim=True)\n\n click.secho(\n \"\\n\\trun 'fsec cleanup --force' to cleanup the remaining files\\n\\n\"\n if n > 0\n else \"\",\n dim=False,\n fg=\"yellow\",\n bold=True,\n )\n\n\n# Error\n# cli.add_command(initdb)\n# cli.add_command(dropdb)\ncli.add_command(run)\ncli.add_command(download)\ncli.add_command(parse)\ncli.add_command(show)\ncli.add_command(cleanup)\n\n\ndef main(argv=sys.argv):\n \"\"\"\n Args:\n argv (list): List of arguments\n Returns:\n int: A return code\n Does stuff.\n \"\"\"\n # print(argv)\n cli()\n return 0\n","sub_path":"src/fsec/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":14800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"66582580","text":"\n\n#calss header\nclass _ORWELLIAN():\n\tdef __init__(self,): \n\t\tself.name = \"ORWELLIAN\"\n\t\tself.definitions = [u'used to describe a political system in which the government tries to control every part of people\\'s lives, similar to that described in the novel \"Nineteen Eighty Four\", by George Orwell: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_orwellian.py","file_name":"_orwellian.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"632855737","text":"import itertools\nimport textwrap\nfrom pairs import Direction, add_dir, add_pair\nfrom enum import Enum\n\n\nclass LightGrid(object):\n _neighbor_pairs = [\n (0, -1),\n (-1, 0), (1, 0),\n (0, 1)\n ]\n # _neighbor_pairs = [\n # (-1, -1), (0, -1), (1, -1),\n # (-1, 0), (1, 0),\n # (-1, 1), (0, 1), (1, 1)\n # ]\n\n def __init__(self, width, height):\n self.grid = list([[0 for _ in range(width)] for _ in range(height)])\n self.width = width\n self.height = height\n\n def __str__(self):\n return '\\n'.join(''.join('#' if v else '.' for v in row) for row in self.grid)\n\n def __eq__(self, other):\n return self.grid == other.grid\n\n def __ne__(self, other):\n return self.grid != other.grid\n\n def biodiversity(self):\n return sum(pow(2, idx) if gridval == 1 else 0 for idx, gridval in enumerate(itertools.chain(*self.grid)))\n\n def at(self, x, y):\n if not (0 <= x < self.width and 0 <= y < self.height):\n raise IndexError\n return self.grid[y][x]\n\n def turn_on(self, x, y):\n self.grid[y][x] = 1\n\n def turn_off(self, x, y):\n self.grid[y][x] = 0\n\n def toggle(self, x, y):\n self.grid[y][x] = (self.grid[y][x] + 1) % 2\n\n def num_lit(self):\n return sum(v for row in self.grid for v in row)\n\n def num_lit_neighbors(self, x, y):\n num_lit = 0\n for offset in LightGrid._neighbor_pairs:\n try:\n num_lit += self.at(x+offset[0], y+offset[1])\n except IndexError:\n pass\n return num_lit\n\n def step(self):\n to_modify = dict()\n for x, y in itertools.product(range(self.width), range(self.height)):\n num_lit_neighbors = self.num_lit_neighbors(x, y)\n if self.at(x, y) == 1 and num_lit_neighbors != 1:\n to_modify[(x, y)] = 0\n elif self.at(x, y) == 0 and num_lit_neighbors in [1, 2]:\n to_modify[(x, y)] = 1\n for loc, val in to_modify.items():\n self.grid[loc[1]][loc[0]] = val\n\n\nclass FractalBugGrid(object):\n def __init__(self):\n self.width = self.height = 5\n self.grid = list([[0 for _ in range(self.width)] for _ in range(self.height)])\n self.center = (2, 2)\n self.inner_grid = None\n self.outer_grid = None\n self.lifetime = 0\n\n def __str__(self):\n return '\\n'.join(''.join('#' if v else '.' for v in row) for row in self.grid)\n\n def __eq__(self, other):\n return self.grid == other.grid\n\n def __ne__(self, other):\n return self.grid != other.grid\n\n def num_bugs(self):\n return self._num_bugs_outward() + self._num_bugs_inward() + self._num_bugs_thislevel()\n\n def _num_bugs_thislevel(self):\n return sum(itertools.chain(*self.grid))\n\n def _num_bugs_outward(self):\n if self.outer_grid is None:\n return 0\n else:\n return self.outer_grid._num_bugs_thislevel() + self.outer_grid._num_bugs_outward()\n\n def _num_bugs_inward(self):\n if self.inner_grid is None:\n return 0\n else:\n return self.inner_grid._num_bugs_thislevel() + self.inner_grid._num_bugs_inward()\n\n def at(self, x, y):\n if not (0 <= x < self.width and 0 <= y < self.height):\n raise IndexError\n return self.grid[y][x]\n\n def outer_grid_at(self, x, y):\n return 0 if self.outer_grid is None else self.outer_grid.at(x, y)\n\n def inner_grid_at(self, x, y):\n return 0 if self.inner_grid is None else self.inner_grid.at(x, y)\n\n def adj_bugs(self, x, y, d):\n if x == 0 and d == Direction.WEST:\n return self.outer_grid_at(1, 2)\n elif y == 0 and d == Direction.NORTH:\n return self.outer_grid_at(2, 1)\n elif x == self.width-1 and d == Direction.EAST:\n return self.outer_grid_at(3, 2)\n elif y == self.height-1 and d == Direction.SOUTH:\n return self.outer_grid_at(2, 3)\n elif x == 1 and y == 2 and d == Direction.EAST:\n return sum(self.inner_grid_at(0, yp) for yp in range(self.height))\n elif x == 2 and y == 1 and d == Direction.SOUTH:\n return sum(self.inner_grid_at(xp, 0) for xp in range(self.width))\n elif x == 3 and y == 2 and d == Direction.WEST:\n return sum(self.inner_grid_at(self.width-1, yp) for yp in range(self.height))\n elif x == 2 and y == 3 and d == Direction.NORTH:\n return sum(self.inner_grid_at(xp, self.height-1) for xp in range(self.width))\n else:\n return self.at(*add_dir((x, y), d))\n\n def turn_on(self, x, y):\n self.grid[y][x] = 1\n\n def turn_off(self, x, y):\n self.grid[y][x] = 0\n\n def num_lit_neighbors(self, x, y):\n return sum(self.adj_bugs(x, y, d) for d in Direction)\n\n def step(self, step_outward=True, step_inward=True):\n if step_outward and self.outer_grid is None:\n self.outer_grid = FractalBugGrid()\n self.outer_grid.inner_grid = self\n self.outer_grid.lifetime = -2\n if step_inward and self.inner_grid is None:\n self.inner_grid = FractalBugGrid()\n self.inner_grid.outer_grid = self\n self.inner_grid.lifetime = -2\n\n to_modify = dict()\n for x, y in itertools.product(range(self.width), range(self.height)):\n if (x, y) == self.center:\n continue\n num_lit_neighbors = self.num_lit_neighbors(x, y)\n if self.at(x, y) == 1 and num_lit_neighbors != 1:\n to_modify[(x, y)] = 0\n elif self.at(x, y) == 0 and num_lit_neighbors in [1, 2]:\n to_modify[(x, y)] = 1\n\n if self.outer_grid is not None and step_outward and self.lifetime >= 0:\n self.outer_grid.step(step_inward=False, step_outward=True)\n if self.inner_grid is not None and step_inward and self.lifetime >= 0:\n self.inner_grid.step(step_inward=True, step_outward=False)\n\n for loc, val in to_modify.items():\n self.grid[loc[1]][loc[0]] = val\n self.lifetime += 1\n\n\ndef parse_input(big_str):\n light_grid = LightGrid(5, 5)\n for y, line in enumerate(big_str.splitlines(keepends=False)):\n for x, c in enumerate(line):\n if c == '#':\n light_grid.turn_on(x, y)\n print('{:b}'.format(light_grid.biodiversity()))\n return light_grid\n\n\ndef parse_input_2(big_str):\n bug_grid = FractalBugGrid()\n for y, line in enumerate(big_str.splitlines(keepends=False)):\n for x, c in enumerate(line):\n if c == '#':\n bug_grid.turn_on(x, y)\n return bug_grid\n\n\ndef test():\n light_grid = parse_input(textwrap.dedent(\"\"\"\\\n ....#\n #..#.\n #..##\n ..#..\n #....\"\"\"))\n for step in range(5):\n print(step)\n print(light_grid)\n light_grid.step()\n\n\ndef part_1(big_str):\n light_grid = parse_input(big_str)\n biodiversities = set()\n while light_grid.biodiversity() not in biodiversities:\n biodiversities.add(light_grid.biodiversity())\n light_grid.step()\n return light_grid.biodiversity()\n\n\ndef part_2(grid_str):\n bug_grid = parse_input_2(grid_str)\n for _ in range(200):\n bug_grid.step()\n return bug_grid.num_bugs()\n\n\nif __name__ == \"__main__\":\n with open('input/dec24.txt', 'r') as file:\n the_big_str = file.read()\n\n test_str = textwrap.dedent(\"\"\"\\\n ....#\n #..#.\n #..##\n ..#..\n #....\"\"\")\n\n # print('Part 1:', part_1(the_big_str))\n print('Part 2:', part_2(the_big_str))\n","sub_path":"2019/dec24.py","file_name":"dec24.py","file_ext":"py","file_size_in_byte":7608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"57171334","text":"\"\"\"\nReceiver hooks to use oauth data provided by Aalto-LeTech/django-lti-login.\nThis is modified from the example app:\nhttps://github.com/Aalto-LeTech/django-lti-login/blob/master/example/\n\"\"\"\n\nimport logging\nfrom django.conf import settings\nfrom django.contrib.auth.signals import user_logged_in\nfrom django.contrib import messages\nfrom django.core.exceptions import PermissionDenied\nfrom django.shortcuts import reverse\nfrom django.dispatch import receiver\nfrom django_lti_login.signals import lti_login_authenticated\n\nfrom .utils import add_user_to_course\n\n\nlogger = logging.getLogger(__name__)\n\n\n@receiver(lti_login_authenticated)\ndef store_last_login(sender, **kwargs):\n \"\"\"\n Example thing to do before user is actually authenticated, but does exists.\n Django sets user.last_login after this, so it's last time to use it.\n \"\"\"\n request = kwargs.get('request', None)\n user = kwargs.get('user', None)\n if request and user:\n request.session['last_login'] = str(user.last_login)\n\n\n@receiver(user_logged_in)\ndef store_course_info(sender, **kwargs):\n \"\"\"\n Get required course information after user is fully authenticated.\n \"\"\"\n request = kwargs.get('request', None)\n user = kwargs.get('user', None)\n oauth = getattr(request, 'oauth', None)\n\n if request and user and oauth:\n required_fields = [\"context_label\", \"context_title\", \"roles\",\n \"custom_context_api\", \"tool_consumer_instance_guid\",\n \"custom_user_api_token\", \"custom_context_api_id\"]\n accepted_roles = [\"Instructor\", \"TA,TeachingAssistant\"]\n login_info = {}\n\n for field in required_fields:\n login_info[field] = getattr(oauth, field, None)\n\n if None in login_info.values():\n logger.error(\"LTI login request doesn't contain all required \"\n \"fields for course membership update. User that \"\n \"tried to login: {}\".format(user))\n raise PermissionDenied(\"Not all required fields \"\n \"present in LTI login\")\n\n if login_info[\"roles\"] not in accepted_roles:\n raise PermissionDenied(\"Allowed only for teachers and TA's\")\n\n logger.info(\"New authentication by {user} for {label} {name}.\".format(\n user=user,\n label=login_info[\"context_label\"],\n name=login_info[\"context_title\"],\n ))\n\n # Add user to the course according to login information\n if not add_user_to_course(user, login_info):\n messages.error(request, f\"Requested course not found. Only \"\n f\"teachers can create new courses.\")\n\n # Redirect to notresponded page after login\n oauth.redirect_url = reverse('submissions:index')\n\n # List LTI params in debug\n if settings.DEBUG:\n logger.debug(\"LTI login accepted for user %s\", user)\n for k, v in sorted(oauth.params):\n print(\" \\w param -- %s: %s\", k, v)\n","sub_path":"submissions/receivers.py","file_name":"receivers.py","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"129782007","text":"from django.core.management.base import BaseCommand\nfrom query.models import Video, Face\nfrom scannerpy import Database, DeviceType, Job\nfrom scannerpy.stdlib import parsers, pipelines\nimport os\nimport cv2\n\nclass Command(BaseCommand):\n help = 'Detect faces in videos'\n\n def add_arguments(self, parser):\n parser.add_argument('path')\n\n def handle(self, *args, **options):\n with open(options['path']) as f:\n paths = [s.strip() for s in f.readlines()]\n\n with Database() as db:\n # Only run the detector over videos we haven't yet processed\n filtered = []\n for path in paths:\n video = Video.objects.filter(path=path)\n if len(video) == 0: continue\n video = video[0]\n if len(Face.objects.filter(video=video)) > 0: continue\n filtered.append(path)\n\n # Run the detector via Scanner\n stride = 12\n c = db.new_collection('tmp', filtered, force=True)\n faces_c = pipelines.detect_faces(\n db, c, lambda t: t.strided(stride), 'tmp_faces')\n\n # Save the results to the database\n for path, video_faces_table in zip(filtered, faces_c.tables()):\n video = Video.objects.filter(path=path).get()\n table = db.table(path)\n frames = table.load(['frame'], rows=range(0, table.num_rows(), stride))\n\n video_faces = video_faces_table.load(['bboxes'], parsers.bboxes)\n for (i, frame_faces), (_, frame) in zip(video_faces, frames):\n for bbox in frame_faces:\n f = Face()\n f.video = video\n f.frame = i * stride\n f.bbox = bbox\n f.save()\n\n thumbnail_path = 'assets/thumbnails/{}_{}.jpg'.format(video.id, f.id)\n thumbnail = frame[0][int(bbox.y1):int(bbox.y2),\n int(bbox.x1):int(bbox.x2)]\n cv2.imwrite(thumbnail_path, cv2.cvtColor(thumbnail, cv2.COLOR_RGB2BGR))\n","sub_path":"esper/query/management/commands/face_detect.py","file_name":"face_detect.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"284588459","text":"class Solution:\r\n def rotate(self, matrix):\r\n \"\"\"\r\n :type matrix: List[List[int]]\r\n :rtype: void Do not return anything, modify matrix in-place instead.\r\n \"\"\"\r\n n = len(matrix)\r\n\r\n def r(x, y):\r\n if y == 0 or y == 1:\r\n return\r\n for i in range(x, x + y - 1):\r\n matrix[x][i], matrix[i][x + y - 1], \\\r\n matrix[x + y - 1][2 * x + y - i - 1], matrix[2 * x + y - i - 1][x] \\\r\n = matrix[2 * x + y - i - 1][x], matrix[x][i], \\\r\n matrix[i][x + y - 1], matrix[x + y - 1][2 * x + y - i - 1]\r\n r(x + 1, y - 2)\r\n\r\n r(0, n)\r\n\r\n\r\nsol = Solution()\r\nl1 = [[1, 2], [3, 4]]\r\nsol.rotate(l1)\r\nprint(l1)\r\nl1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\r\nsol.rotate(l1)\r\nprint(l1)\r\nl1 = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]]\r\nsol.rotate(l1)\r\nprint(l1)\r\n","sub_path":"Python3/48. Rotate Image.py","file_name":"48. Rotate Image.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"110175595","text":"# !/user/bin/env python\n# _*_ coding: utf-8 _*_\n# @Time : 2021/5/16 17:57\n# @Author : 王俊\n# @File : read_config.py\n# @Software : PyCharm\nimport os\nimport yaml\nfrom common import CONF_DIR\n\n\nclass ReadeConfig(object):\n __instance = None\n\n def __new__(cls, *args, **kwargs):\n if cls.__instance is None:\n cls.__instance = super().__new__(cls)\n return cls.__instance\n\n def __init__(self, f):\n \"\"\" 此类用于读取配置文件信息,配置文件采用yaml形式\n :param f: config配置文件的配置文件名称\n \"\"\"\n self.filename = os.path.join(CONF_DIR, f)\n self._data = None\n\n def get(self, key=None, index=0, hot=False) -> dict:\n \"\"\" 用于获取配置文件某个值\n :param key: 需要获取的配置文件项\n :param index: 索引,配置项以‘---’分隔,默认为0\n :param hot:热加载配置,默认为False不启动,True表示每次都从文件中读取数据\n :return: 返回配置项信息\n \"\"\"\n if self._data is None or hot:\n with open(self.filename, \"rb\") as f:\n self._data = list(yaml.safe_load_all(f))\n if key is None:\n return self._data[index]\n else:\n return self._data[index][key]\n\n\nconf = ReadeConfig(\"dbconfig.yaml\").get()\nbase_conf = ReadeConfig(\"baseconfig.yaml\")\n\n\ndef select_db(db_type):\n db_map = {\n \"weijian\": conf.get(\"WeiJianDBConfig\"),\n \"mydb\": conf.get(\"MyDBConfig\"),\n \"dbpoolmaster\": conf.get(\"MyDBConfig\"),\n \"dbpoollocal\": conf.get(\"DBPoolLocalHostConfig\"),\n }\n db_conf = db_map.get(db_type)\n return db_conf\n","sub_path":"common/read_config.py","file_name":"read_config.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"503308879","text":"import asyncio\nfrom builtins import dict\nfrom contextlib import suppress\nfrom copy import copy\nfrom io import BytesIO\n\nimport discord\nimport pprint\n\nfrom redbot.core import commands, checks, Config\nfrom redbot.core.utils import common_filters, mod\nfrom redbot.core.utils.chat_formatting import pagify, humanize_list\nfrom redbot.core.utils.predicates import MessagePredicate\nfrom redbot.core.i18n import Translator, cog_i18n\n\ncheck_permissions = getattr(mod, \"check_permissions\", checks.check_permissions)\n\nfrom .converter import RiftConverter, search_converter, SearchError\n\n\nCog = getattr(commands, \"Cog\", object)\n\n\n_ = Translator(\"Rift\", __file__)\n\n\nmax_size = 8_000_000 # can be 1 << 23 but some unknowns also add to the size\nm_count = 0\n\nasync def close_check(ctx):\n \"\"\"Admin / manage channel OR private channel\"\"\"\n if isinstance(ctx.channel, discord.DMChannel):\n return True\n return await mod.is_admin_or_superior(ctx.bot, ctx.author) or await check_permissions(\n ctx, {\"manage_channels\": True}\n )\n\n\nclass RiftError(Exception):\n pass\n\n\nclass Rift(Cog):\n \"\"\"\n Communicate with other servers/channels.\n \"\"\"\n\n def __init__(self, bot):\n super().__init__()\n self.bot = bot\n self.open_rifts = {}\n self.requesting_users = []\n self.bot.loop.create_task(self.load_rifts())\n\n self.config = Config.get_conf(self, identifier=2_113_674_295, force_registration=True)\n self.config.register_global(rifts=[])\n self.config.register_channel(blacklisted=False)\n self.config.register_guild(blacklisted=False)\n self.config.register_user(blacklisted=False)\n\n async def save_rift(self, rift):\n async with self.config.rifts() as rifts:\n rifts.append(rift.toIDs())\n\n async def load_rifts(self):\n\n def add_rift(sources, rift):\n if rift.source in sources:\n sources[rift.source].append(rift)\n else:\n sources[rift.source] = [rift]\n\n loaded = []\n sources = {}\n async with self.config.rifts() as rifts:\n for rift in rifts:\n author = self.bot.get_user(rift[0])\n if not isinstance(author, discord.User): continue\n source = self.bot.get_channel(rift[1]) or self.bot.get_user(rift[1])\n if not isinstance(source, discord.TextChannel) and not isinstance(source, discord.User): continue\n destination = self.bot.get_channel(rift[2]) or self.bot.get_user(rift[2])\n if not isinstance(destination, discord.TextChannel) and not isinstance(destination, discord.User): continue\n rift = RiftConverter.create(author, source, destination)\n loaded.append(rift)\n add_rift(sources, rift)\n\n self.open_rifts.update(((rift, {}) for rift in loaded))\n for source, rifts in sources.items():\n try:\n embed = await self.create_simple_embed(rift.author,\n \"Rift has been reloaded! \\n{}\".format(\"\\n\".join(str(rift) for rift in rifts)),\n \"Rift Loaded\" if len(rifts) == 1 else \"Rifts Loaded\")\n await source.send(embed=embed)\n except (discord.Forbidden, discord.HTTPException):\n pass\n\n # COMMANDS\n\n @commands.group()\n async def rift(self, ctx):\n \"\"\"\n Communicate with other channels through Red.\n \"\"\"\n pass\n\n @rift.group()\n async def blacklist(self, ctx):\n \"\"\"\n Configures blacklists.\n\n Blacklisted destinations cannot have rifts opened to them.\n \"\"\"\n pass\n\n @blacklist.command(name=\"channel\")\n @commands.check(close_check)\n async def blacklist_channel(self, ctx, *, channel: discord.TextChannel = None):\n \"\"\"\n Blacklists the current channel or the specified channel.\n\n Can also blacklist DM channels.\n \"\"\"\n if channel and isinstance(ctx.channel, discord.DMChannel):\n raise commands.BadArgument(_(\"You cannot blacklist a channel in DMs.\"))\n if isinstance(ctx.channel, discord.DMChannel):\n channel = ctx.author\n group = self.config.user(channel)\n else:\n channel = channel or ctx.channel\n group = self.config.channel(channel)\n blacklisted = not await group.blacklisted()\n await group.blacklisted.set(blacklisted)\n await ctx.maybe_send_embed(\n _(\"Channel is {} blacklisted.\".format(\"now\" if blacklisted else \"no longer\"))\n )\n if blacklisted:\n await self.close_rifts(ctx, ctx.author, channel)\n\n @blacklist.command(name=\"server\")\n @commands.guild_only()\n @checks.admin_or_permissions(manage_guild=True)\n async def blacklist_server(self, ctx):\n \"\"\"\n Blacklists the current server.\n\n All channels and members in a server are considered blacklisted if the server is blacklisted.\n Members can still be reached if they are in another, non-blacklisted server.\n \"\"\"\n group = self.config.guild(ctx.guild)\n blacklisted = not await group.blacklisted()\n await group.blacklisted.set(blacklisted)\n await ctx.maybe_send_embed(\n _(\"Server is {} blacklisted.\".format(\"now\" if blacklisted else \"no longer\"))\n )\n if blacklisted:\n await self.close_rifts(ctx, ctx.author, ctx.guild)\n\n @rift.command(name=\"close\")\n @commands.check(close_check)\n async def rift_close(self, ctx, channel : discord.TextChannel = None):\n \"\"\"\n Closes all rifts that lead to this channel.\n \"\"\"\n if channel is None:\n channel = ctx.author if isinstance(ctx.channel, discord.DMChannel) else ctx.channel\n await self.close_rifts(ctx, ctx.author, channel)\n\n @rift.command(name=\"open\")\n async def rift_open(self, ctx, *rifts: RiftConverter(_, globally=True)):\n \"\"\"\n Opens a rift to the specified destination.\n\n The destination may be any channel or user that both you and the bot are connected to, even across servers.\n \"\"\"\n if not rifts:\n return await ctx.send_help()\n rifts = set(rifts)\n create_queue = []\n for rift in rifts:\n if not await self.rift_exists(rift):\n if ctx.guild is None or rift.destination not in ctx.guild.channels:\n accepted, reason = await self.request_access(ctx, rift)\n if not accepted:\n continue\n dest_open_embed = await self.create_simple_embed(ctx.author,\n _(rift.mention()),\n \"A Rift has been opened.\"\n )\n #ctx.bot.loop.create_task(\n # rift.destination.send(embed=dest_open_embed)\n #)\n await rift.destination.send(embed=dest_open_embed)\n create_queue.append(rift)\n\n with suppress(NameError):\n if reason is not None:\n await ctx.maybe_send_embed(reason)\n if not accepted:\n return\n if not create_queue:\n return await ctx.maybe_send_embed(\"Rift(s) already exist.\")\n # add new rifts\n self.open_rifts.update(((rift, {}) for rift in create_queue))\n for rift in create_queue:\n await self.save_rift(rift)\n\n open_embed = await self.create_simple_embed(ctx.author,\n _(\"A rift has been opened to {}! Everything you say will be relayed there.\\n\"\n \"Responses will be relayed here.\\nType `exit` here to quit.\"\n ).format(humanize_list([str(rift.destination) for rift in create_queue]))\n , \"Rift Opened!\")\n await ctx.send(embed=open_embed)\n\n @rift.command(name=\"sources\")\n async def rift_list_sources(self, ctx, destination: discord.TextChannel = None):\n \"\"\"List sources for opened rifts\"\"\"\n if destination is None:\n destination = ctx.channel\n rifts = await self.get_rifts(destination, False)\n if rifts:\n message = (\"Rifts:\") + \"\\n\\n\"\n message += \"\\n\".join(rift.mention() for rift in rifts)\n for page in pagify(message):\n await ctx.maybe_send_embed(page)\n else:\n embed = await self.create_simple_embed(self.bot.user, \"No Rift Found.\")\n await ctx.send(embed=embed)\n\n @rift.command(name=\"destinations\", aliases=[\"dests\"])\n async def rift_list_destinations(self, ctx, source: discord.TextChannel = None):\n \"\"\"List destinations for opened rifts\"\"\"\n if source is None:\n source = ctx.channel\n rifts = await self.get_rifts(source, True)\n if rifts:\n message = (\"Rifts:\") + \"\\n\\n\"\n message += \"\\n\".join(rift.mention() for rift in rifts)\n for page in pagify(message):\n await ctx.maybe_send_embed(page)\n else:\n embed = await self.create_simple_embed(self.bot.user, \"No Rift Found.\")\n await ctx.send(embed=embed)\n\n @rift.command(name=\"search\")\n async def rift_search(self, ctx, searchby: search_converter(_) = None, *, search=None):\n \"\"\"\n Searches through open rifts.\n\n searchby: author, source, or destination. If this isn't provided, all\n three are searched through.\n search: Search for the specified author/source/destination. If this\n isn't provided, the author or channel of the command is used.\n \"\"\"\n searchby = searchby or list(range(3))\n if search is None:\n search = [ctx.author, ctx.channel, ctx.author]\n else:\n try:\n search = await RiftConverter.search(ctx, search, False, _)\n except commands.BadArgument as e:\n embed = await self.create_simple_embed(self.bot.user, str(e), \"Bot Exception\")\n return await ctx.send(embed=embed)\n results = set()\n for rift in self.open_rifts:\n for i in searchby:\n if rift[i] in search:\n results.add(rift)\n if not results:\n return await ctx.maybe_send_embed(_(\"No rifts were found with these parameters.\"))\n message = _(\"Results:\") + \"\\n\\n\"\n message += \"\\n\".join(str(rift) for rift in results)\n for page in pagify(message):\n await ctx.maybe_send_embed(page)\n\n @rift_open.error\n @rift_search.error\n async def rift_error(self, ctx, error):\n if isinstance(error, commands.ConversionError):\n embed = discord.Embed(color=ctx.guild.me.color, \n description=str(error.__cause__),\n title=\"Destination not found\")\n return await ctx.send(embed=embed)\n raise error\n\n # UTILITIES\n\n #async def select_from_rifts(self, rifts):\n # message = (\"Rifts:\") + \"\\n\\n\"\n # message += f\"\\n**{rifts.index(rift) + 1}.** \".join(rift.mention() for rift in rifts)\n # for page in pagify(message):\n # await ctx.maybe_send_embed(page)\n\n # await ctx.send(\"Select the rift's number you would like to edit the settings of\")\n # try:\n # msg = await ctx.bot.wait_for(\"message\", check=MessagePredicate.same_context(ctx), timeout=15)\n # except asyncio.TimeoutError:\n # await ctx.maybe_send_embed(\"Timeout. Selection cancelled.\")\n # return None\n # try:\n # index = int(msg.content)\n # except ValueError:\n # await ctx.maybe_send_embed(\"Invalid input.\")\n # return None\n # try:\n # rift = rifts[index]\n # return rift\n # except IndexError:\n # await ctx.maybe_send_embed(\"Rift not found\")\n # return None\n\n async def request_access(self, ctx, rift) -> (bool, str):\n author = ctx.author\n if author.id in self.requesting_users:\n failed_embed = await self.create_simple_embed(author,\n \"You currently have a Rift request open. Please wait \"\n \"until that expires before trying again.\",\n \"Existing rift request.\")\n try:\n await ctx.send(embed=failed_embed)\n except discord.Forbidden:\n pass\n return False, None\n destination = rift.destination\n source = rift.source\n self.requesting_users.append(author.id)\n embed = await self.create_simple_embed(\n author,\n (f\"{author} is requesting to open a rift to here from #{source} in {ctx.guild.name}\" + \"\\n\" +\n f\"{rift}\" + \"\\n\\n\" +\n f\"An admin can enter `accept` or `decline` to accept/decline this request.\"),\n \"Requesting Cross-Server Rift Permission\")\n try:\n request_msg = await destination.send(embed=embed)\n except discord.Forbidden:\n return False, f\"I do not have permissions to send in {destination}\"\n\n def check(m):\n is_accept_message = m.content.lower().strip() in [\"accept\", \"yes\", \"y\", \"decline\", \"no\", \"n\"]\n is_correct_channel = m.channel.id == rift.destination.id\n if isinstance(m.channel, discord.channel.DMChannel):\n is_correct_channel = m.channel.recipient.id == rift.destination.id or m.channel.id == rift.destination.id\n return is_correct_channel and is_accept_message\n return is_correct_channel and is_accept_message and m.author.guild_permissions.manage_channels\n\n try:\n msg = await ctx.bot.wait_for(\"message\", check=check, timeout=25)\n except asyncio.TimeoutError:\n try:\n await request_msg.delete()\n except discord.NotFound:\n pass\n if author.id in self.requesting_users:\n self.requesting_users.remove(author.id)\n return False, \"No staff response to request.\"\n response = msg.content.lower().strip()\n if response in [\"accept\", \"yes\", \"y\"]:\n accepted, reason = True, f\"{msg.author.name} has __**accepted**__ the request to open the cross-server rift.\\n{rift}\"\n elif response in [\"decline\",\"no\",\"n\"]:\n accepted, reason = False, f\"{msg.author.name} has __**declined**__ the request to open the cross-server rift.\\n{rift}\"\n else:\n accepted, reason = False, \"Unknown response.\"\n\n try:\n await request_msg.delete()\n except discord.NotFound:\n pass\n if author.id in self.requesting_users:\n self.requesting_users.remove(author.id)\n return accepted, reason\n\n async def close_rifts(self, ctx, closer, destination, search_source : bool = False):\n rifts = await self.get_rifts(destination, search_source)\n if rifts:\n for rift in rifts:\n del self.open_rifts[rift]\n async with self.config.rifts() as rifts:\n if rift.toIDs() in rifts:\n rifts.remove(rift.toIDs())\n source_embed = await self.create_simple_embed(ctx.author,\n _(\"{} has closed the rift to {}.\").format(closer, rift.destination),\n \"Rift Closed\")\n await rift.source.send(embed=source_embed)\n dest_embed = await self.create_simple_embed(ctx.author,\n _(\"Rift from {} closed by {}.\").format(rift.source, closer),\n \"Rift Closed\")\n await rift.destination.send(embed=dest_embed)\n else:\n embed = await self.create_simple_embed(self.bot.user, _(\"No rifts were found that connect to here.\"), \"No Rifts Found\")\n await ctx.send(embed=embed)\n\n async def get_rifts(self, destination, toggle=False):\n rifts = []\n if isinstance(destination, discord.Guild):\n if toggle:\n check = lambda rift: rift.source in destination.channels\n else:\n check = lambda rift: rift.destination in destination.channels\n else:\n if toggle:\n check = lambda rift: rift.source == destination\n else:\n check = lambda rift: rift.destination == destination\n for rift in self.open_rifts.copy():\n if check(rift):\n rifts.append(rift)\n return rifts\n\n async def get_embed(self, destination, attachments):\n attach = attachments[0]\n if (\n hasattr(destination, \"guild\")\n and await self.bot.db.guild(destination.guild).use_bot_color()\n ):\n color = destination.guild.me.colour\n else:\n color = self.bot.color\n description = \"\\n\\n\".join(\n f\"{self.xbytes(attach.size)}\\n**[{attach.filename}]({attach.url})**\"\n for a in attachments\n )\n embed = discord.Embed(colour=color, description=description)\n embed.set_image(url=attach.url)\n return embed\n\n async def rift_exists(self, rift):\n for rift2 in await self.get_rifts(rift.source, True):\n if rift2.destination == rift.destination:\n return True\n return False\n\n\n def permissions(self, destination, user, is_owner=False):\n if isinstance(destination, discord.User):\n return destination.dm_channel.permissions_for(user)\n if not is_owner:\n member = destination.guild.get_member(user.id)\n if member:\n return destination.permissions_for(member)\n else:\n every = destination.guild.default_role\n overs = destination.overwrites_for(every)\n overs.read_messages = True\n overs.send_messages = True\n perms = (every.permissions.value & ~overs[1].value) | overs[0].value\n return discord.Permissions(perms)\n return discord.Permissions.all()\n\n async def process_message(self, rift, message, destination):\n if isinstance(destination, discord.Message):\n send_coro = destination.edit\n else:\n send_coro = destination.send\n channel = (\n message.author if isinstance(message.channel, discord.DMChannel) else message.channel\n )\n send = channel == rift.source\n destination = rift.destination if send else rift.source\n source = rift.source if send else rift.destination\n author = message.author\n me = (\n destination.dm_channel.me\n if isinstance(destination, discord.User)\n else destination.guild.me\n )\n is_owner = await self.bot.is_owner(author)\n author_perms = self.permissions(destination, author, is_owner)\n bot_perms = self.permissions(destination, me)\n content = message.content\n if not is_owner:\n if not author_perms.administrator:\n content = common_filters.filter_invites(content)\n if not author_perms.mention_everyone:\n content = common_filters.filter_mass_mentions(content)\n attachments = message.attachments\n files = []\n embed = None\n if attachments and author_perms.attach_files and bot_perms.attach_files:\n overs = await asyncio.gather(*(self.save_attach(file, files) for file in attachments))\n overs = list(filter(bool, overs))\n if overs:\n content += (\n \"\\n\\n\"\n + _(\"Attachments:\")\n + \"\\n\"\n + \"\\n\".join(f\"({self.xbytes(a.size)}) {a.url}\" for a in attachments)\n )\n if not any((content, files, embed)):\n raise RiftError(_(\"No content to send.\"))\n msg_embed = await self.create_message_embed(ctx=message, source=source, content=content, files=attachments)\n return await send_coro(embed=msg_embed)\n\n async def save_attach(self, file: discord.Attachment, files) -> discord.File:\n if file.size > max_size:\n return file\n buffer = BytesIO()\n await file.save(buffer, seek_begin=True)\n files.append(discord.File(buffer, file.filename))\n return None\n\n def xbytes(self, b):\n blist = (\"B\", \"KB\", \"MB\")\n index = 0\n while True:\n if b > 900:\n b = b / 1024.0\n index += 1\n else:\n return \"{:.3g} {}\".format(b, blist[index])\n\n # EVENTS\n\n async def on_message(self, m):\n if m.author.bot:\n return\n channel = m.author if isinstance(m.channel, discord.channel.DMChannel) else m.channel\n sent = {}\n ctx = (await self.bot.get_context(m))\n is_command = ctx.valid or m.content.startswith(str(ctx.prefix))\n if is_command: return\n for rift, record in self.open_rifts.copy().items():\n privilege_check = (rift.author == m.author if not isinstance(m.channel, discord.channel.DMChannel) else m.author == channel)\n if privilege_check and m.content.lower() == \"exit\":\n await self.close_rifts(ctx, m.author, channel, search_source=(True if channel == rift.source else False))\n return\n\n if rift.source == channel:\n try:\n record[m] = await self.process_message(rift, m, rift.destination)\n except discord.HTTPException as e:\n embed = await self.create_simple_embed(self.bot.user,\n _(\"I couldn't send your message due to an error: {}\").format(e),\n \"Bot Exception\")\n await channel.send(embed=embed)\n elif rift.destination == channel:\n rift_chans = (rift.source, rift.destination)\n if rift_chans in sent:\n record[m] = sent[rift_chans]\n else:\n record[m] = sent[rift_chans] = await self.process_message(rift, m, rift.source)\n\n async def on_message_delete(self, m):\n if m.author.bot and not self.bot.user:\n return\n deleted = set()\n for record in self.open_rifts.copy().values():\n for source_m, embed_m in record.items():\n if m.id == source_m.id:\n with suppress(KeyError, discord.NotFound):\n record.pop(source_m)\n if embed_m not in deleted:\n deleted.add(source_m)\n await embed_m.delete()\n break\n elif m.id == embed_m.id:\n with suppress(KeyError, discord.NotFound):\n record.pop(source_m)\n if source_m not in deleted:\n deleted.add(source_m)\n await source_m.delete()\n break\n\n async def on_message_edit(self, b, a):\n if a.author.bot:\n return\n channel = a.author if isinstance(a.channel, discord.DMChannel) else a.channel\n sent = set()\n for rift, record in self.open_rifts.copy().items():\n if rift.source == channel and rift.author == a.author:\n with suppress(KeyError, discord.NotFound):\n await self.process_message(rift, a, record[a])\n elif rift.destination == channel:\n rift_chans = (rift.source, rift.destination)\n if rift_chans not in sent:\n sent.add(rift_chans)\n with suppress(KeyError, discord.NotFound):\n await self.process_message(rift, a, record[a])\n\n async def create_message_embed(self, ctx, source, content, files):\n message_content = (content[:1000] if len(content) > 1000 else content)\n embed = discord.Embed(color=ctx.author.color, description=message_content)\n embed.set_author(icon_url=ctx.author.avatar_url,name=ctx.author.name + \" from #\" + source.name)\n if len(files) == 1:\n file = files[0]\n if file.height is not None and file.height > 64 and file.width > 64 and not file.is_spoiler():\n embed.set_image(url=file.url)\n else:\n embed.add_field(name=\"Attachment:\", value=file.url)\n elif len(files) > 1:\n file_str = \"\"\n for file in files:\n file_str += file.url\n file_str += \"\\n\\n\"\n embed.add_field(name=\"Attachments:\", value=file_str)\n return embed\n\n async def create_simple_embed(self, author: discord.Member, message: str, title: str = None):\n simple_embed = discord.Embed(color=author.color, description=message)\n if title is not None:\n simple_embed.set_author(icon_url=author.avatar_url,name=title)\n return simple_embed\n","sub_path":"rift/rift.py","file_name":"rift.py","file_ext":"py","file_size_in_byte":25331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"327538039","text":"# 이번 가을학기에 '문제 해결' 강의를 신청한 학생들은 텀 프로젝트를 수행해야 한다.\n# 프로젝트 팀원 수에는 제한이 없다. 심지어 모든 학생들이 동일한 팀의 팀원인 경우와 같이 한 팀만 있을 수도 있다.\n# 프로젝트 팀을 구성하기 위해, 모든 학생들은 프로젝트를 함께하고 싶은 학생을 선택해야 한다.\n# (단, 단 한 명만 선택할 수 있다.)\n# 혼자 하고 싶어하는 학생은 자기 자신을 선택하는 것도 가능하다.\n#\n# 학생들이(s1, s2, ..., sr)이라 할 때, r=1이고 s1이 s1을 선택하는 경우나,\n# s1이 s2를 선택하고, s2가 s3를 선택하고,..., sr-1이 sr을 선택하고, sr이 s1을 선택하는 경우에만 한 팀이 될 수 있다.\n#\n# 예를 들어, 한 반에 7명의 학생이 있다고 하자. 학생들을 1번부터 7번으로 표현할 때, 선택의 결과는 다음과 같다.\n#\n# 1 2\t3\t4\t5\t6\t7\n# 3\t 1 3\t7\t3\t4\t6\n# 위의 결과를 통해 (3)과 (4, 7, 6)이 팀을 이룰 수 있다. 1, 2, 5는 어느 팀에도 속하지 않는다.\n#\n# 주어진 선택의 결과를 보고 어느 프로젝트 팀에도 속하지 않는 학생들의 수를 계산하는 프로그램을 작성하라.\n#\n# 입력\n# 첫째 줄에 테스트 케이스의 개수 T가 주어진다.\n# 각 테스트 케이스의 첫 줄에는 학생의 수가 정수 n (2 ≤ n ≤ 100,000)으로 주어진다.\n# 각 테스트 케이스의 둘째 줄에는 선택된 학생들의 번호가 주어진다. (모든 학생들은 1부터 n까지 번호가 부여된다.)\n#\n# 출력\n# 각 테스트 케이스마다 한 줄에 출력하고, 각 줄에는 프로젝트 팀에 속하지 못한 학생들의 수를 나타내면 된다.\n\n\nimport sys\n\n\nT = int(sys.stdin.readline().rstrip())\nfor t in range(T):\n n = int(sys.stdin.readline().rstrip())\n wish = [0] + list(map(int, sys.stdin.readline().rstrip().split()))\n\n alone = []\n visited = [False] * (n + 1)\n\n for start in range(1, n + 1):\n if visited[start]:\n continue\n\n start_of_2nd_loop = start\n # v가 두번째 루프의 시작이 될 때까지 이동\n # (start == wish[start]일 경우 그대로 있음)\n while not visited[start_of_2nd_loop]:\n visited[start_of_2nd_loop] = True\n start_of_2nd_loop = wish[start_of_2nd_loop]\n\n w = start\n # 두번째 루프의 시작 v == 첫번째 루프의 시작 인덱스값.\n # 따라서 v와 만나기 전까지 start부터 이동시키며 alone을 센다.\n while w != start_of_2nd_loop:\n alone.append(w)\n w = wish[w]\n\n print(len(alone))\n","sub_path":"Baekjoon/TermProject_2.py","file_name":"TermProject_2.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"570126800","text":"#!/usr/bin/env python3\n\nimport pika\nimport sys, os\nimport time\nimport threading\nimport logging\nimport redis\nimport queue\nimport pdfkit\nimport time\n\ntime.sleep(20)\n\nxrange=range\n\nif sys.argv[1:]:\n max_threads = int(sys.argv[1])\nelse:\n max_threads = int(os.environ.get('MAX_THREADS'))\n\nlogfile = os.environ.get('LOGFILE')\nrabbit_host = os.environ.get('RABBIT_HOST')\nrabbit_queue = os.environ.get('RABBIT_QUEUE')\nrabbit_user = os.environ.get('RABBIT_USER')\nrabbit_password = os.environ.get('RABBIT_PASS')\nredis_host = os.environ.get('REDIS_HOST')\nredis_port = os.environ.get('REDIS_PORT')\nredis_db = os.environ.get('REDIS_DB')\nlogging.basicConfig(level=logging.DEBUG,format='%(asctime)-15s - %(threadName)-10s - %(message)s',filename=logfile)\n\npdfkitoptions = {\n 'enable-local-file-access': None,\n 'javascript-delay': 200,\n 'wait-for-network-idle': None\n}\n\ntime.sleep(15)\n\ndef render_pdf(msg_id):\n output_file = '/tmp/' + msg_id + '.pdf'\n input_file = '/tmp/' + msg_id + '.html'\n logging.debug('loading html from redis')\n redis_server = redis.Redis(redis_host, port=redis_port, db=redis_db)\n redis_response = redis_server.get(msg_id)\n logging.debug('html loaded')\n m = open(input_file, \"wb\")\n m.write(redis_response)\n m.close()\n logging.debug('html writed')\n start_time = time.time()\n sys_output = pdfkit.from_file(input_file, output_file, options=pdfkitoptions)\n finish_time = time.time()\n input_size = str(os.path.getsize(input_file)/1024) #.decode('utf-8')\n output_size = str(os.path.getsize(output_file)/1024) #.decode('utf-8')\n dbg_mesg = '[R] Render [msg.id:' + msg_id + '] ' + '[rend.time:' + str(finish_time-start_time) + 'sec]' + '[in.fle:' + input_file + '(' + input_size + 'kb)]' + '[ou.fle:' + output_file + '(' + output_size + 'kb)]'\n logging.debug(dbg_mesg)\n n = open(output_file, \"rb\")\n binary_data = n.read()\n n.close()\n logging.debug('pdf loaded')\n msg_out = msg_id.split('_')\n msg = 'R_' + msg_out[1]\n redis_server.set(msg, binary_data)\n logging.debug('pdf writed')\n redis_server.delete(msg_id)\n logging.debug('db record removed: ' + msg_id)\n os.remove(output_file)\n logging.debug('tmp file removed: ' + input_file)\n os.remove(input_file)\n logging.debug('tmp file removed: ' + output_file)\n logging.debug('render done')\n if not sys_output:\n return True, output_file\n return False, sys_output\n\n#logging.debug('backend node starting...')\nprint('backend node starting...')\nTQ = queue.Queue()\n#logging.debug('threads pool starting...')\nprint('threads pool starting...')\n\ndef catcher(q):\n while True:\n try:\n print (\"trying...\")\n print (q)\n item = q.get()\n print (\"wut...\")\n except Empty:\n break\n\n #logging.debug('render get task: ' + item.strip().decode('utf-8'))\n print('render get task: ' + item.strip().decode('utf-8'))\n render_pdf(item.strip().decode('utf-8'))\n q.task_done()\n\nfor i in xrange(max_threads):\n wrkr_T = threading.Thread(target = catcher, args=(TQ,))\n print('thread created...')\n wrkr_T.daemon = True\n wrkr_T.start()\n logging.debug('thread: ' + str(i) + ' started')\n\nlogging.debug('consumer started...')\ncredentials = pika.PlainCredentials(rabbit_user, rabbit_password)\ntry:\n rabbit_server = pika.BlockingConnection(pika.ConnectionParameters(host=rabbit_host,credentials=credentials))\n channel = rabbit_server.channel()\n channel.queue_declare(queue=rabbit_queue)\n def callback(ch, method, properties, body):\n TQ.put(body)\n logging.debug('consumer got task: ' + body.strip().decode('utf-8'))\n channel.basic_consume(rabbit_queue, callback, auto_ack = True)\n channel.start_consuming()\n\nexcept KeyboardInterrupt:\n logging.debug('backen daemon stopt')\n print (\"backend node stopt\")\n\n\n","sub_path":"backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":3884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"508701429","text":"# -*- coding: utf-8 -*-\n# !/usr/bin/python\n# python 3.6\n\nimport pandas as pd\nfrom numpy import asmatrix\nfrom xgboost import XGBClassifier\nfrom sklearn.model_selection import train_test_split, RandomizedSearchCV\nfrom numpy import abs, mean\nimport scipy.stats as st\n\n# 读取文件\nfile_name = 'C.test_data201803.csv'\ndata = pd.read_csv(file_name)\nY = data['KWH']\n\nprint('real y values: ')\nprint(Y)\n\ndata = asmatrix(data)\nX = data[:, 0]\nprint(X)\n\n\n# 划分训练集和测试集\nseed = 7\ntest_size = 0.1\nX_train, X_test, y_train, y_test = train_test_split(X,\n Y,\n test_size=test_size,\n random_state=seed)\n\nX_train = asmatrix(X_train)\n\n\n# 建立模型\nmodel = XGBClassifier()\nmodel.fit(X_train, y_train)\n\n\n# 预测\ny_pred = model.predict(X)\nmape = mean(abs(Y - y_pred)/Y)\n\nprint('prediction of y')\nprint(y_pred)\nprint('Mean Absolute Percentage Error')\nprint(mape)\n\n# 通过交叉验证寻找最优参数并且优化模型\nparams = {\"n_estimators\": st.randint(100, 500),\n 'max_depth': st.randint(6, 30)}\nmodel_updated = RandomizedSearchCV(\n model, params, cv=10, random_state=1, n_iter=20)\n\n# 预测\ny_pred_update = model_updated.predict(X)\nmape_update = mean(abs(Y - y_pred_update)/Y)\n\nprint('prediction updated of y')\nprint(y_pred_update)\nprint('Mean Absolute Percentage Error')\nprint(mape_update)\n","sub_path":"entretien/xgboost/example3.py","file_name":"example3.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"247628392","text":"\"\"\"Problem:\n Given a staircase with N stairs and a set X of steps \n that you can take at a time i.e. {1,2} write an algorithm \n that determines the number of possible paths to reach the \n top of the staircase.\n Note: There are multiple solutions, however, the dynamic\n programming solution is preferable to the others. \"\"\"\n#It would take minimal effort to modify this to output the \n#actual paths i.e. N=4, X=[1,3,5], Paths=[[4,3,2,1,0],[4,1,0],[4,3,0]]\n\ndef num_ways(N,X,current_stair):\n ways = 0\n if current_stair == N:\n return 1; #The trivial case, only one way to get from step 4 to step 4\n for i in range(len(X)): #Walk through all the cases on the current step\n if X[i] + current_stair <= N:\n ways += num_ways(N,X,X[i] + current_stair) #if we've found a possible case take the step\n return ways\n\ndef num_ways_bottomup(N,X):\n if 0 == N:\n return 1;\n ways = list(range(N+1))\n ways[0] = 1 #Trival Solution\n for i in range(1,N+1,1):\n total = 0\n #print(i)\n for j in range(len(X)):\n #print(X[j])\n if i - X[j] >= 0:\n #print(i,\"-\",X[j],\">=\",0)\n total += ways[i-X[j]]\n ways[i] = total\n #print(\"ways to \",i,\" = \",ways[i])\n return ways[N]\n\nN=4\n#N=3\n#N=2\nX=[1,3,5] #Should be 3 for N = 4\n#X=[1,2] #Should be 5 for N = 4, 3 for N = 3, 2 for N = 2\nx=[[1,2],[1,3,5]]\nfor n in range(N+1): #Use the for loops to test multiple cases.\n for i in range(len(x)):\n print(\"The staircase is: \",n,\" steps.\")\n print(\"We can take: \",x[i],\" steps at a time.\")\n #print(\"There are: \",num_ways(n,x[i],0),\" ways to the top.\")\n print(\"There are: \",num_ways_bottomup(n,x[i]),\" way(s) to the top.\")\n print(' ')\n\"\"\"print(\"The staircase is: \",N,\" steps.\")\nprint(\"We can take: \",X,\" steps at a time.\")\n#print(\"There are: \",num_ways(N,X,0),\" way(s) to the top.\")\nprint(\"There are: \",num_ways_bottomup(N,X),\" ways to the top.\")\"\"\"","sub_path":"Python/staircase.py","file_name":"staircase.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"33361885","text":"# project/server/auth/views.py\n\nimport datetime\n\nfrom flask import Blueprint, request, make_response, jsonify\nfrom flask.views import MethodView\n\nfrom project.server import bcrypt, db\nfrom project.server.models.DPIAudit import DpiAudit\nfrom flask_cors import CORS\n\ndpiaudit_blueprint = Blueprint('Dpiaudit', __name__)\nCORS(dpiaudit_blueprint)\n\nclass DPIAuditPOSTAPI(MethodView):\n def post(self):\n\n post_data = request.get_json()\n try:\n assObj = DpiAudit(\n question_id=post_data.get('question_id'),\n section_id=post_data.get('section_id'),\n owner_id=post_data.get('owner_id'),\n description=post_data.get('description')\n )\n db.session.add(assObj)\n db.session.commit()\n print(assObj.to_dict())\n responseObject = {\n \"id\":assObj.id,\n \"question_id\":assObj.question_id,\n \"section_id\":assObj.section_id,\n \"description\":assObj.owner_id,\n \"owner_id\":assObj.owner_id\n }\n return make_response(jsonify(responseObject)), 200\n except Exception as e:\n responseObject = {\n 'status': 'fail',\n 'message': 'Some error occurred. Please try again.'\n }\n return make_response(jsonify(responseObject)), 401\n\n\nclass DPIAuditGETAPI(MethodView):\n def get(self):\n try:\n assessments = DpiAudit.query.all()\n assessmentArr = []\n for assessment in assessments:\n assessmentArr.append(assessment.to_dict())\n return jsonify(assessmentArr)\n except Exception as e:\n responseObject = {\n 'status': 'fail',\n 'message': 'Some error occurred. Please try again.'\n }\n return make_response(jsonify(responseObject)), 401\n\n\n\n@dpiaudit_blueprint.route('/dpiaudit/', methods=['GET', 'PUT', 'DELETE'])\ndef bucketlist_manipulation(id, **kwargs):\n gotData = DpiAudit.query.filter_by(id=id).first()\n\n if request.method == \"DELETE\":\n if(gotData):\n db.session.delete(gotData)\n db.session.commit()\n response = {\n \"id\":gotData.id,\n 'message':\"Removed successfully\"\n }\n return make_response(jsonify(response)), 201\n else:\n return \"Error while deleting\"\n\n elif request.method == 'PUT':\n obj = request.get_json()\n if(obj):\n\n # gotData.active = obj.get('active')\n gotData.question_id = obj.get('question_id')\n gotData.section_id = obj.get('section_id')\n gotData.owner_id = obj.get('owner_id')\n gotData.description = obj.get('description')\n gotData.modified_date = datetime.datetime.now()\n\n db.session.add(gotData)\n db.session.commit()\n\n response = {\n \"id\":gotData.id,\n \"question_id\":gotData.question_id,\n \"section_id\":gotData.section_id,\n \"owner_id\":gotData.owner_id,\n \"description\":gotData.description,\n 'message':\"Updated successfully\"\n }\n return make_response(jsonify(response)), 200\n else:\n return \"Error while updating\"\n else:\n if(gotData):\n response = {\n \"id\":gotData.id,\n \"question_id\":gotData.question_id,\n \"section_id\":gotData.section_id,\n \"owner_id\":gotData.owner_id,\n \"description\":gotData.description,\n 'message': \"Retrieved successfully\"\n }\n return make_response(jsonify(response)), 200\n else:\n return \"Error while fetching data\"\n\n# define the API resources\n\n\ndpiaudit_post_view = DPIAuditPOSTAPI.as_view('dpiaudit_post_api')\ndpiaudit_get_view = DPIAuditGETAPI.as_view('dpiaudit_get_api')\n\ndpiaudit_blueprint.add_url_rule(\n '/dpiaudit',\n view_func=dpiaudit_post_view,\n methods=['POST']\n)\n\n\ndpiaudit_blueprint.add_url_rule(\n '/dpiaudit',\n view_func=dpiaudit_get_view,\n methods=['GET']\n)\n","sub_path":"DPIA_WEBSERVICE/project/server/DPIAuditViews/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"314038165","text":"from django.shortcuts import render, get_object_or_404, get_list_or_404, reverse, redirect\nfrom .models import Article, Comment, UserProfile\nfrom .forms import CommentForm\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nimport random\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\nimport markdown\n\n\n# _LABEL_COLOR = ['red', 'orange', 'yellow', 'green', 'teal', 'blue', 'purple']\n# UniformMetaData.article_all = Article.objects.order_by('-created_at')\n\n# # make sure labels is unique in template\n# def labels():\n# labels = set()\n# for article in UniformMetaData.article_all:\n# labels.add(article.label)\n# return sample(labels,15)\n#\n#\n# def created_date():\n# created_date = set()\n# for article in UniformMetaData.article_all:\n# dt = article.created_at.strftime('%Y-%m')\n# created_date.add(dt)\n# return created_date\n\n#\nclass UniformMetaData(object):\n label_color = ['red', 'orange', 'yellow', 'green', 'teal', 'blue', 'purple']\n\n @classmethod\n def article_all(cls):\n article_all = Article.objects.order_by('-id')\n return article_all\n\n @classmethod\n def label(cls):\n labels = set()\n for article in cls.article_all():\n if article.label.strip():\n labels.add(article.label.strip())\n print(labels)\n # if len(labels) > 15:\n # return random.sample(labels, 15)\n # else:\n return labels\n\n @classmethod\n def created_date(cls):\n created_date = set()\n for article in cls.article_all():\n dt = article.created_at.strftime('%Y-%m')\n created_date.add(dt)\n return created_date\n\n\n# 本来写了好几段的重复代码,这里取相同的变量article——list就好了,不用重复写渲染的代码了\ndef article(request, article_set=None, article_date=None):\n if article_set:\n article_list = get_list_or_404(Article, label=article_set)\n # print('article_set ======================= ' , article_list)\n\n elif article_date:\n article_list = []\n for article in UniformMetaData.article_all():\n if article.created_at.strftime('%Y-%m') == article_date:\n article_list.append(article)\n # print('article_cate ======================= ' , article_list)\n else:\n article_list = UniformMetaData.article_all()\n # print('article_all ======================= ', article_list)\n # print(article_list)\n # articles已经变成page对象,不再是普通的变量\n paginator = Paginator(article_list, 5)\n page = request.GET.get('page')\n try:\n articles = paginator.page(page)\n except EmptyPage:\n articles = paginator.page(paginator.num_pages)\n except PageNotAnInteger: # 如果get到none则捕捉此错误\n articles = paginator.page(1)\n # print('article in page ==========', articles)\n for article in articles:\n article.content = markdown.markdown(article.content,\n extensions=[\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n 'markdown.extensions.toc',\n ])\n return render(request, 'blog/blog.html', {'articles': articles,\n 'labels': UniformMetaData.label(),\n 'label_color': UniformMetaData.label_color,\n 'article_all': UniformMetaData.article_all(),\n 'article_filter_by_month': UniformMetaData.created_date(),\n }\n )\n\n\ndef article_detail(request, article_id, err_form=None):\n article = get_object_or_404(Article, pk=article_id)\n article.content = markdown.markdown(article.content,\n extensions=[\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n 'markdown.extensions.toc',\n ])\n comment_list = article.comment_set.order_by('-created_at')\n if err_form:\n comment_form = err_form\n else:\n comment_form = CommentForm\n # if request.method == 'POST':\n # comment_form = CommentForm(request.POST) # 绑定表单\n # if comment_form.is_valid(): # 没有此行,校验依然可行,添加此行只是为了逻辑判断\n # comment_content = comment_form.cleaned_data['comment_content']\n # comment = Comment(article=article,content=comment_content)\n # comment.save()\n # return HttpResponseRedirect(reverse('blog:article', args=[article.id, ])) # 记得return\n return render(request, 'blog/article.html', {'article': article,\n 'label_color': UniformMetaData.label_color,\n 'labels': UniformMetaData.label(),\n 'article_all': UniformMetaData.article_all(),\n 'article_filter_by_month': UniformMetaData.created_date(),\n 'comment_form': comment_form,\n 'comment_list': comment_list,\n }\n )\n\n\n@login_required(login_url='blog:login')\ndef article_detail_comment(request, article_id):\n comment_form = CommentForm(request.POST) # 绑定表单\n # if not authenticate(request.user):\n # redirect(to=)\n\n if comment_form.is_valid(): # 没有此行,校验依然可行,添加此行只是为了逻辑判断\n article = Article.objects.get(pk=article_id)\n comment_content = comment_form.cleaned_data['comment_content']\n comment = Comment(article=article, content=comment_content, author=request.user)\n comment.save()\n return HttpResponseRedirect(reverse('blog:article', args=(article.id,)))\n else:\n return article_detail(request, article_id, err_form=comment_form) # view内传递数据依然可以传递表单错误信息,而直接重定向则失效\n\n\ndef blog_login(request):\n redirect_to = request.POST.get('next', request.GET.get('next', ''))\n if request.method == 'GET':\n form = AuthenticationForm\n elif request.method == 'POST':\n form = AuthenticationForm(data=request.POST)\n if form.is_valid():\n login(request, form.get_user())\n if redirect_to:\n return redirect(redirect_to)\n else:\n return redirect('/blog')\n context = {}\n context['form'] = form\n context['next'] = redirect_to\n return render(request, 'blog/register_login.html', context)\n\n\ndef blog_register(request):\n if request.user.is_authenticated:\n logout(request)\n context = {}\n redirect_to = request.POST.get('next', request.GET.get('next', ''))\n if request.method == 'GET':\n form = UserCreationForm\n elif request.method == 'POST':\n form = UserCreationForm(request.POST)\n if form.is_valid():\n form.save()\n user = authenticate(username=form.cleaned_data['username'],\n password=form.cleaned_data['password1'],\n )\n avatar = request.FILES.get('avatar') # 注意这里是files\n userprofile = UserProfile(belong_to=user, profile_image=avatar)\n userprofile.save()\n login(request, user)\n if redirect_to:\n return redirect(redirect_to)\n else:\n return redirect('blog:article_list')\n context['form'] = form\n context['next'] = redirect_to\n return render(request, 'blog/register_login.html', context)\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"21158927","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport urllib\nimport subprocess\nimport simplejson\nimport mimetypes\nimport os\nimport shutil\n\nclass ImageSearch:\n\tdef __init__(self, folder = '/tmp/CoverGrabber'):\n\t\tself.folder = folder\n\t\tif os.path.exists(self.folder):\n\t\t\tshutil.rmtree(self.folder)\n\t\tos.mkdir(self.folder)\n\t\t\n\tdef search(self, search):\n\t\tquery = urllib.urlencode({'q' : search})\n\t\turl = 'http://ajax.googleapis.com/ajax/services/search/' + \\\n\t\t\t'images?v=1.0&%s'%(query)\n\t\tsearchResults = urllib.urlopen(url)\n\t\tjson = simplejson.loads(searchResults.read())\n\t\tresults = json['responseData']['results']\n\n\t\tfilenameRoot = os.path.join(\n\t\t\tself.folder,\n\t\t\t'-'.join(search)\n\t\t)\n\t\tf = []\n\t\tc = 1\n\t\tfor i in results:\n\t\t\tfilename = filenameRoot + '-%i.jpg'%c\n\t\t\turllib.urlretrieve(i['url'], filename)\n\t\t\tmime = subprocess.Popen(\n\t\t\t\t'file -i \"%s\"'%filename, \n\t\t\t\tshell=True,\n\t\t\t\tstdout=subprocess.PIPE\n\t\t\t\t).communicate()[0]\n\t\t\tif not 'image/jpeg;' in mime:\n\t\t\t\tos.remove(filename)\n\t\t\telse:\n\t\t\t\tc += 1\n\t\t\t\tf.append(filename)\n\t\treturn f\n","sub_path":"imagesearch.py","file_name":"imagesearch.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"566847734","text":"\ndef output_student(L):\n name_w = 15\n age_w = 10\n score_w = 10\n print()\n head1 = '+' + '-'*name_w + '+' + '-'*age_w + '+' + '-'*score_w + '+'\n print(head1)\n head_text = '|' + '姓名'.center(name_w - 2) +\\\n '|' + '年龄'.center(age_w - 2)+ '|' + '成绩'.center(score_w - 2) + '|'\n print(head_text)\n print(head1)\n for i in L:\n fmt = '|%s|%s|%s|'\n name_text = i['name'].center(name_w)\n age_text = str(i['age']).center(age_w)\n score_text = str(i['score']).center(score_w)\n print(fmt % (name_text, age_text, score_text))\n print(head1)","sub_path":"aid1807a/练习题/python练习题/python基础习题/13/homework/chengjipaixu/dayin.py","file_name":"dayin.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"189606814","text":"import numpy as np\nimport sys\n\nf = open(sys.argv[1])\ndata = np.loadtxt(f)\ntrain = data[:,1:]\ntrainlabels = data[:,0]\n\nonearray = np.ones((train.shape[0],1))\ntrain = np.append(train,onearray,axis=1)\n\nprint(train)\nprint(\"train shape=\",train.shape)\n\nf = open(sys.argv[2])\ndata = np.loadtxt(f)\ntest = data[:,1:]\ntestlabels = data[:,0]\n\nrows = train.shape[0]\ncols = train.shape[1]\n\nw = np.random.rand(cols)\n#w = np.ones(cols)\nprint(\"w=\",w)\n\nepochs = 10000\neta = .001\nprevobj = np.inf\ni=0\n\nobj = np.sum(np.square(np.matmul(train, np.transpose(w)) - trainlabels))\nprint(\"Obj=\",obj)\n\nwhile(prevobj - obj > 0 and i < epochs):\n#while(prevobj - obj > 0):\n\n\t#Update previous objective\n\tprevobj = obj\n\n\t#Calculate gradient\n\tdellf = (np.dot(train[0,:],w)-trainlabels[0])*train[0,:]\n\tfor j in range(1, rows):\n\t\tdellf += (np.dot(train[j,:],w)-trainlabels[j])*train[j,:]\n\n#\tprint(\"dellf=\",dellf)\n\t\n\t#Update w\n\tw = w - eta*dellf\n\n\t#Recalculate objective\n\tobj = np.sum(np.square(np.matmul(train, np.transpose(w)) - trainlabels))\n\t\n\ti = i + 1\n\tprint(\"Objective=\",obj)\n\t\n\npredictions = np.sign(np.matmul(train, np.transpose(w)))\nprint(predictions)\n\nprint(w)\n","sub_path":"Assignment4/least_squares_gd.py","file_name":"least_squares_gd.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"209624575","text":"from manimlib.imports import *\r\nimport math\r\nimport numpy as np\r\n\r\nclass CountDown(Scene):\r\n def construct(self):\r\n self.count_down()\r\n\r\n def count_down(self):\r\n count_down = TexMobject(\r\n \"\\\\sqrt{25}\",\r\n \"2^2\",\r\n \"\\\\lfloor\\\\pi\\\\rfloor\",\r\n \"\\\\sum_{n=0}^{\\\\infty} \\\\frac{1}{2^n}\",\r\n \"-e^{\\\\pi i}\"\r\n )\r\n for i in range(0,len(count_down)):\r\n count_down[i].to_corner(DR)\r\n self.play(Write(count_down[0]))\r\n for i in range(0,len(count_down)-1):\r\n self.play(ReplacementTransform(count_down[i],count_down[i+1]))\r\n self.wait(0.5)\r\n self.play(FadeOut(count_down[len(count_down)-1]))\r\n\r\n\r\nclass ForCoins(Scene):\r\n def construct(self):\r\n self.for_coins()\r\n\r\n def for_coins(self):\r\n text = [\r\n \"如果你觉得不错就点个三连吧\",\r\n \"你的三连是对我最好的支持\",\r\n \"我是病态小鸽\",\r\n \"我们下期再见~~~~\"\r\n ]\r\n texts = VGroup(*[TextMobject(t) for t in text])\r\n texts.arrange(DOWN, buff=1)\r\n texts.set_color_by_gradient(RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE)\r\n\r\n for i in range(0,len(text)):\r\n self.play(Write(texts[i]))\r\n self.wait(0.7)\r\n self.wait()","sub_path":"useful_code.py","file_name":"useful_code.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"580463463","text":"from tkinter import *\nimport json\nfrom itertools import product\nimport math\nimport time\n\n\nwith open(\"DBV2.json\") as f:\n DB = json.load(f)\n\nwith open(\"Int.json\") as f:\n Int = json.load(f)\n\n\ndef convtime(timec):\n timestr = time.localtime(timec)\n if len(str(timestr[3])) == 1:\n hour = +str(timestr[3])\n else:\n hour = str(timestr[3])\n\n if len(str(timestr[4])) == 1:\n minute = str(timestr[4])\n else:\n minute = str(timestr[4])\n\n if len(str(timestr[5])) == 1:\n second = \"0\"+str(timestr[5])\n else:\n second = str(timestr[5])\n \n return(hour+\":\"+minute+\":\"+second)\n\n\ndef timen():\n return time.time()\ndef et(t1,t2):\n time = t2-t1\n return(time)\n\n\ndef checker(item,source):\n if item in source:\n return(True)\n else:\n return(False)\n\ndef check2(v1 , v2 , v3 ,v4):\n if v1 in v4:\n return False\n\n elif v2 in v4:\n return False\n \n elif v1 == v3:\n return True\n\n elif v2 == v3:\n return True\n\n else:\n return False\n\ndef match(searching):\n weapons = []\n head = []\n chest = []\n legs = []\n hands = []\n for query in searching:\n typ = DB[\"12\"][query]\n for item in DB[\"10\"]:\n if DB[\"10\"][item][\"Cell0\"] == int(query):\n weapons.append(item)\n print(\"Pass\")\n\n## elif check2(DB[\"10\"][item][\"Cell1\"],DB[\"10\"][item][\"Cell2\"],typ,weapons) == True:\n## weapons.append(item)\n\n for item in DB[\"0\"]:\n if DB[\"0\"][item][\"Cell0\"] == int(query):\n head.append(item)\n \n## elif check2(DB[\"0\"][item][\"Cell1\"],DB[\"0\"][item][\"Cell2\"],typ,weapons) == True:\n## head.append(item)\n\n \n for item in DB[\"1\"]:\n if DB[\"1\"][item][\"Cell0\"] == int(query):\n chest.append(item)\n## elif check2(DB[\"1\"][item][\"Cell1\"],DB[\"1\"][item][\"Cell2\"],typ,weapons) == True:\n## chest.append(item)\n\n\n for item in DB[\"2\"]:\n if DB[\"2\"][item][\"Cell0\"] == int(query):\n legs.append(item)\n## elif check2(DB[\"2\"][item][\"Cell1\"],DB[\"2\"][item][\"Cell2\"],typ,weapons) == True:\n## legs.append(item)\n\n for item in DB[\"3\"]:\n if DB[\"3\"][item][\"Cell0\"] == int(query):\n hands.append(item)\n## elif check2(DB[\"3\"][item][\"Cell1\"],DB[\"3\"][item][\"Cell2\"],typ,weapons) == True:\n## hands.append(item)\n\n\n z = set(product(weapons,head,chest,legs,hands))\n print(\"GG\") \n tt = [] \n for combo in z:\n tt.append(combo)\n print(len(tt))\n return(tt)\n\n\ndef build(Sets):\n begin = timen()\n\n Criteria = {}\n for item in Sets:\n if item[0] != \"None\":\n if item[0] not in Criteria: \n Criteria.update({item[0] : int(item[1])})\n else:\n Criteria[item[0]] += int(item[1])\n# for item in Criteria:\n# Criteria[item] = int(math.ceil(float(Criteria[item]/3)))\n\n pack = []\n for item in Criteria:\n pack.append(item) \n##This Is Going To Form All Possible Matches Based On Perks Asked For\n con = match(pack)\n end3 = timen()\n print(et(begin,end3),\"Time Time To Make All Matches\")\n values = Criteria\n mat = []\n for item in con:\n val = perfect(extract(item),values,item)\n if val == False:\n fin = item\n# fin.append(extract(item))\n mat.append(str(fin))\n# print(item)\n print(len(mat))\n end = timen()\n\n nam = \"XX\"\n fn = nam+\".txt\"\n final = open(fn,\"w\")\n\n final.write(str(\"\\n\\n\".join(mat)))\n final.close()\n end2 = timen()\n print(\"Done\")\n print(et(begin,end),\"Time To Check All Comboes\")\n print(et(begin,end2),\"Time Including Writing To Disc\")\n\ndef perfect(setii,crit,arm):\n# print(rej)\n crit = dict(crit)\n orig = dict(crit)\n seti = setii\n cri = crit\n# print(seti,\"set perks\")\n# print(cri,\"criteria perks\")\n\n for item in seti:\n# print(item)\n if item in cri:\n cri[item] = cri[item] - seti[item]\n# print(cri)\n fail = False\n# print()\n for item in cri:\n if cri[item] != 0:\n# print(item)\n fail = True\n if fail == True:\n cri = celcheck(setii,cri)\n# print(cri)\n\n fail = False\n for item in cri:\n if cri[item] != 0:\n # print(item)\n fail = True\n## for item in rej:\n## if item in setii and item != \"None\":\n## fail = True\n## \n return(fail)\n\ndef build2(Sets):\n begin = timen()\n\n Criteria = {}\n for item in Sets:\n if item[0] != \"None\":\n if item[0] not in Criteria: \n Criteria.update({item[0] : int(item[1])})\n else:\n Criteria[item[0]] += int(item[1])\n for item in Criteria:\n Criteria[item] = int(math.ceil(float(Criteria[item]/3)))\n\n pack = []\n for item in Criteria:\n pack.append(item) \n##This Is Going To Form All Possible Matches Based On Perks Asked For\n con = match2(pack)\n\n end3 = timen()\n print(et(begin,end3),\"Time Time To Make All Matches\")\n\n values = Criteria\n mat = []\n for item in con:\n print(con.index(item))\n val = perfect(extract(item),values,item)\n if val == False:\n fin = list(item)\n fin.append(extract(item))\n mat.append(fin)\n# print(item)\n# print(len(mat))\n end = timen()\n end2 = timen()\n print(\"Done\")\n print(et(begin,end),\"Time To Check All Comboes\")\n print(et(begin,end2),\"Time Including Writing To Disc\")\n\ndef celcheck(setii,crit):\n# print(crit)\n for item in crit:\n if item !=0:\n if DB[\"12\"][item] in setii:\n if (setii[DB[\"12\"][item]] - crit[item]) >= 0:\n setii[DB[\"12\"][item]] = setii[DB[\"12\"][item]] - crit[item]\n crit[item] = 0\n return(crit)\n\n\ndef extract(Set):\n com = {\"4\" : 1}\n# Weap,Helm,Chest,Legs,Hands\n for item in Set:\n\n if DB[\"13\"][item][\"Cell0\"] not in com:\n com.update({DB[\"13\"][item][\"Cell0\"] : 1})\n else:\n com[DB[\"13\"][item][\"Cell0\"]] += 1\n\n if DB[\"13\"][item][\"Cell1\"] not in com:\n com.update({DB[\"13\"][item][\"Cell1\"] : 1})\n else:\n com[DB[\"13\"][item][\"Cell1\"]] += 1\n\n if DB[\"13\"][item][\"Cell2\"] not in com:\n com.update({DB[\"13\"][item][\"Cell2\"] : 1})\n else:\n com[DB[\"13\"][item][\"Cell2\"]] += 1\n \n\n return(com)\n\n#def rank(mat,cri)\n# for item in \n\n\n\n#print(extract(('151', '135', '28', '2', '3')))\n\n#build([[\"33\",2],[\"0\",2]])\n\nbuild([[\"5\",2],[\"38\",2],[\"24\",2],[\"22\",2],[\"40\",2],[\"42\",2]])\n\n#x = extract(['Charrogg Exotic Weapon', 'Rezakiri Head', 'Drask Chest', 'Boreus Legs', 'Boreus Hands'])\n#print(x)\n##find()\n#perfect(extract(['Charrogg Exotic Weapon', 'Rezakiri Head', 'Drask Chest', 'Boreus Legs', 'Boreus Hands']),{'Aetheric Attunement': 2},('Charrogg Exotic Weapon', 'Hellion Head', 'Charrogg Chest', 'Charrogg Legs', 'Charrogg Hands'),[])\n","sub_path":"DBV2/DBV2.py","file_name":"DBV2.py","file_ext":"py","file_size_in_byte":7158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"298492971","text":"import pyperclip\nfrom tkinter import *\nfrom customModelSettingsAts1 import *\n\n\n\ndef scanProduct():\n root = Tk()\n root.geometry(\"800x150\")\n root.title(\"ATS Bot\")\n label = Label(root, text=\"Escanee la pieza del modelo a configurar:\")\n label.config(font=('ARIAL', '30'), fg='blue')\n global product\n product = StringVar()\n textBox = Entry(root, textvariable=product, width=20)\n textBox.config(font=('Arial', 30), bd=4)\n\n def enterEvent(event):\n global workOrder\n workOrder = StringVar()\n workOrder.set(product.get())\n root.destroy()\n\n root.bind('', enterEvent)\n\n label.pack()\n textBox.pack()\n textBox.focus()\n\n root.mainloop()\n\n\ndef mes():\n showDesktop()\n findAndClick(mesIconPic, 5, 0.9, True)\n findAndClick(mesLoginBtnPic, 10, 0.9, False)\n findAndClick(mesSideMenuBtnPic,10, 0.9,False)\n findAndClick(startWorkingSideMenuPic,10, 0.9,False)\n time.sleep(0.2)\n pag.press('tab')\n pag.write(workOrder.get())\n pag.press('enter')\n findAndClick(blueOKbtnPic,4, 0.9,False)\n time.sleep(0.2)\n pag.press('enter')\n findAndClick(processScanSearchPic, 5, 0.9, False)\n findAndClick(processScanSearchTextBoxPic, 5, 0.9, False)\n time.sleep(0.2)\n\n pag.write(workOrder.get())\n findAndClick(mesSearchBtnPic, 5, 0.9, False)\n time.sleep(0.5)\n pag.press('tab', presses=5)\n time.sleep(0.2)\n pag.keyDown('ctrlleft')\n pag.press('c')\n pag.keyUp('ctrlleft')\n global model\n model = pyperclip.paste()\n model = eval(model.replace('-',''))\n time.sleep(0.2)\n showDesktop()\n\n\ndef ats():\n # Open ATS\n findAndClick(atsShortcutPic,10, 0.90, True)\n time.sleep(0.2)\n\n #findAndClick(runBtnPic, 5, 0.9, False)\n findAndClick(settingsBtnPic, 20, 0.9, False)\n if findAndBool(barcodeLabelPic, 10, 0.9):\n time.sleep(1)\n pag.press('tab', presses=2, interval=0.1)\n pag.press('enter')\n findAndClick(botTestFilesPic, 5, 0.95, True)\n findAndClick(ATS1FolderPic if AtsModel() else ATS2FolderPic, 5, 0.95, True)\n\n # FIRST TIME OPENING FILE\n while pag.locateCenterOnScreen(modelAtsFile, confidence=0.95) is None:\n print('Encontré el archivo')\n pag.scroll(-300)\n # LOAD FILE\n pag.doubleClick(pag.locateCenterOnScreen(modelAtsFile, confidence=0.95))\n print('cargué el archivo')\n time.sleep(0.3)\n while pag.locateCenterOnScreen(atsOpenBtnPic, confidence=0.95) is None:\n print('no encuentro el boton de abrir')\n pag.scroll(-300)\n time.sleep(0.5)\n pag.click(pag.locateCenterOnScreen(atsOpenBtnPic))\n print('Ya encontré el botón de abrir y le piqué')\n findAndClick(botTestFilesPic, 5, 0.95, True)\n findAndClick(ATS1FolderPic if AtsModel() else ATS2FolderPic, 5, 0.95, True)\n\n\n # SECOND TIME OPENING FILE\n while pag.locateCenterOnScreen(modelAtsFile, confidence=0.95) is None:\n pag.scroll(-300)\n pag.doubleClick(pag.locateCenterOnScreen(modelAtsFile, confidence=0.95))\n print('Ya cargué el segundo archivo')\n time.sleep(0.3)\n\n\n print('termine proceso normal ats')\n # FINISHED LOADING FILE\n # NEXT COMES CUSTOM MODEL SETTINGS\n print('antes de custom settings')\n setSettings(model.writeCurrent, model.dwSwitch)\n print('despues de custom settings')\n\n ### VALIDATE EVERYTHINGS OK\n if findAndBool(inventronicsLogoPic, 5, 0.95):\n pag.alert('¡Configuración Exitosa! Puede comenza a probar.')\n\n\n\n# killTasks()\n# scanProduct()\n# mes()\n# print(model)\n# print(model.get_data)\n# modelAtsFile = model.ssAts1 if AtsModel() else model.ssAts2\n# print(modelAtsFile)\n# print(model)\n# ats()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"botTest.py","file_name":"botTest.py","file_ext":"py","file_size_in_byte":3657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"191135383","text":"import logging\nfrom argparse import Namespace\n\nfrom train import train\n\n\ndef main():\n logging.basicConfig(format='%(asctime)s | %(levelname)s | %(message)s', level=logging.INFO)\n\n args = Namespace()\n\n # args.ower_dir\n args.class_count = 100\n # args.sent_count\n\n args.activation = 'sigmoid'\n args.batch_size = 1024\n args.device = 'cuda'\n args.emb_size = None\n args.epoch_count = 200\n # args.log_dir\n args.log_steps = False\n args.lr = 0.003\n args.mode = 'mean'\n # args.model\n args.optim = 'adam'\n # args.save_dir\n args.sent_len = 64\n args.test = True\n args.tokenizer = 'spacy'\n args.update_vectors = True\n args.vectors = 'fasttext.simple.300d'\n # args.weight_factor\n\n dataset_choices = [\n ('ower-v4-cde-cde-100-1', 1),\n ('ower-v4-cde-irt-100-1', 1),\n ('ower-v4-cde-irt-100-5', 5),\n ('ower-v4-cde-irt-100-15', 15),\n ('ower-v4-cde-irt-100-30', 20),\n ('ower-v4-fb-irt-100-1', 1),\n ('ower-v4-fb-irt-100-5', 5),\n ('ower-v4-fb-irt-100-15', 15),\n ('ower-v4-fb-irt-100-30', 30),\n ('ower-v4-fb-owe-100-1', 1)\n ]\n\n for dataset, sent_count in dataset_choices:\n for model in ['base', 'ower']:\n for weight_factor in [0, 0.5, 1.0, 2.0]:\n args.ower_dir = f'data/ower/{dataset}'\n args.sent_count = sent_count\n\n args.log_dir = f'runs/weight_factor/{dataset}_{model}_{weight_factor}'\n args.model = model\n args.save_dir = f'models/weight_factor/{dataset}_{model}_{weight_factor}'\n args.weight_factor = weight_factor\n\n logging.info(f'Training on dataset {dataset} using model {model} with weight factor {weight_factor}')\n train(args)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/grid_search_weight_factor.py","file_name":"grid_search_weight_factor.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"89175410","text":"# -*- coding: utf-8 -*-\n\nimport tensorflow as tf\n\n# 텐서플로우를 활용한 머신러닝 예제\n\n# 학습데이터 정의 (회귀분석용 데이터)\nX_train = [10, 20, 30, 40, 50]\ny_train = [5, 7, 15, 20, 25]\n\n# 1. 데이터를 전달받기 위한 실행매개변수 선언\nX = tf.placeholder(tf.float32, shape=[None])\ny = tf.placeholder(tf.float32, shape=[None])\n\n# 2. 머신러닝을 위한 가설 정의\n# - 선형회기 분석을 위한 선형방정식\n# - X * W + b\n\n# 기울기(가중치) 변수 선언\nw = tf.Variable(0, dtype=tf.float32)\n\n# 절편(편향) 변수 선언\nb = tf.Variable(0, dtype=tf.float32)\n\n# 가설(문제를 해결하기 위한 식)\nh = X * w + b\n\n# 머신러닝 모델의 학습을 진행하기 위한\n# 오차 값의 계산(평균제곱오차)\nloss_1 = y - h\nloss_2 = tf.square(loss_1)\nloss = tf.reduce_mean(loss_2)\n\n# 오차 값을 감소시키는 방향으로\n# 학습을 진행할 수 있는 객체의 선언\n# (학습률(learning_rate)을 지정하여 학습의 속도를 제어)\noptimizer = tf.train.GradientDescentOptimizer(\n learning_rate=0.0001)\ntrain = optimizer.minimize(loss)\n\nwith tf.Session() as sess :\n sess.run(tf.global_variables_initializer())\n \n feed_dict = {X : X_train, y : y_train}\n for step in range(1, 1001): \n sess.run(train, feed_dict=feed_dict)\n \n if step % 10 == 0 :\n pred_loss = sess.run(loss, feed_dict=feed_dict)\n w_val, b_val = sess.run([w, b], feed_dict=feed_dict)\n print(\"(step-{0}) 오차 : {1}, w : {2}, b : {3}\".format(\n step, pred_loss, w_val, b_val))\n \n pred_loss = sess.run(loss, feed_dict=feed_dict)\n print(\"최종 오차 : {}\".format(pred_loss))\n pred = sess.run(h, feed_dict=feed_dict)\n print(\"예측 결과 : \", pred)\n \n from matplotlib import pyplot as plt\n \n plt.plot(X_train, y_train, 'or')\n plt.plot(X_train, pred, '--b')\n \n X_test = [37, 22]\n pred_test = sess.run(h, feed_dict={X : X_test})\n plt.plot(X_test, pred_test, 'xg')\n \n plt.show()\n \n \"\"\"\n feed_dict = {X : X_train, y : y_train}\n pred = sess.run(h, feed_dict=feed_dict)\n print(\"예측 결과 : \", pred)\n \n pred_loss = sess.run(loss_1, feed_dict=feed_dict)\n print(\"오차 값 1 : \", pred_loss)\n \n pred_loss = sess.run(loss_2, feed_dict=feed_dict)\n print(\"오차 값 2 : \", pred_loss)\n \n pred_loss = sess.run(loss, feed_dict=feed_dict)\n print(\"오차 값 : \", pred_loss)\n \n # 학습을 진행시키는 코드\n # (오차를 줄여나가는 방향으로 가중치(기울기)와 \n # 졀편의 값을 보정시킴)\n sess.run(train, feed_dict=feed_dict)\n \n pred = sess.run(h, feed_dict=feed_dict)\n print(\"예측 결과 : \", pred)\n \n pred_loss = sess.run(loss_1, feed_dict=feed_dict)\n print(\"오차 값 1 : \", pred_loss)\n \n pred_loss = sess.run(loss_2, feed_dict=feed_dict)\n print(\"오차 값 2 : \", pred_loss)\n \n pred_loss = sess.run(loss, feed_dict=feed_dict)\n print(\"오차 값 : \", pred_loss)\n \"\"\"\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Lecture_note_ML/3_tensorflow/1_basic/2_function_matrix/tf_11_example.py","file_name":"tf_11_example.py","file_ext":"py","file_size_in_byte":3098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"226654222","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n@created on 2019/4/21\n@author Yao Li\n\"\"\"\n\n\ndef bf(ts, ps):\n \"\"\"\n 暴力破解\n :param ts: 主串\n :param ps: 模式串\n :return: 如果找到返回主串中第一个模式字符出现索引,否则返回-1\n \"\"\"\n t_list = list(ts) # 主串索引\n p_list = list(ps) # 模式串索引\n i = j = 0\n while i < len(t_list) and j < len(p_list):\n if t_list[i] == p_list[j]: # 对应字符相同,就比较下一个\n i += 1\n j += 1\n else: # 一旦不匹配,则i本轮后移一位;j清0\n i = i - j + 1\n j = 0\n if j == len(p_list):\n return i - j\n else:\n return -1\n\n\nif __name__ == '__main__':\n import time\n t1 = time.time()\n ts = 'abcdbc' * 100000 + 'ABCDBCAABEFG'\n ps = 'ABEFG'\n index = bf(ts, ps)\n t2 = time.time()\n print('index=%s, time=%s' % (str(index), str(t2 - t1)))\n\n","sub_path":"KMP/violent_version.py","file_name":"violent_version.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"565309493","text":"# Copyright (c) 2016 b<>com\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\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\nfrom watcher_dashboard import api\nfrom watcher_dashboard.test import helpers as test\n\n\nclass WatcherAPITests(test.APITestCase):\n\n def test_goal_list(self):\n goals = {'goals': self.api_goals.list()}\n watcherclient = self.stub_watcherclient()\n\n watcherclient.goal = self.mox.CreateMockAnything()\n watcherclient.goal.list(detail=True).AndReturn(goals)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.Goal.list(self.request)\n self.assertIsInstance(ret_val, dict)\n self.assertIn('goals', ret_val)\n for n in ret_val['goals']:\n self.assertIsInstance(n, dict)\n\n def test_goal_get(self):\n goal = self.api_goals.first()\n goal_id = self.api_goals.first()['uuid']\n\n watcherclient = self.stub_watcherclient()\n watcherclient.goal = self.mox.CreateMockAnything()\n watcherclient.goal.get(goal_id).AndReturn(goal)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.Goal.get(self.request, goal_id)\n self.assertIsInstance(ret_val, dict)\n\n def test_strategy_list(self):\n strategies = {'strategies': self.api_strategies.list()}\n watcherclient = self.stub_watcherclient()\n\n watcherclient.strategy = self.mox.CreateMockAnything()\n watcherclient.strategy.list(detail=True).AndReturn(strategies)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.Strategy.list(self.request)\n self.assertIn('strategies', ret_val)\n for n in ret_val['strategies']:\n self.assertIsInstance(n, dict)\n\n def test_strategy_get(self):\n strategy = self.api_strategies.first()\n strategy_id = self.api_strategies.first()['uuid']\n\n watcherclient = self.stub_watcherclient()\n watcherclient.strategy = self.mox.CreateMockAnything()\n watcherclient.strategy.get(strategy_id).AndReturn(strategy)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.Strategy.get(self.request, strategy_id)\n self.assertIsInstance(ret_val, dict)\n\n def test_audit_template_list(self):\n audit_templates = {\n 'audit_templates': self.api_audit_templates.list()}\n watcherclient = self.stub_watcherclient()\n\n watcherclient.audit_template = self.mox.CreateMockAnything()\n watcherclient.audit_template.list(\n detail=True).AndReturn(audit_templates)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.AuditTemplate.list(self.request)\n\n self.assertIn('audit_templates', ret_val)\n for n in ret_val['audit_templates']:\n self.assertIsInstance(n, dict)\n\n def test_audit_template_list_with_filters(self):\n search_opts = {'name': 'Audit Template 1'}\n audit_templates = {\n 'audit_templates': self.api_audit_templates.filter(**search_opts)}\n watcherclient = self.stub_watcherclient()\n\n watcherclient.audit_template = self.mox.CreateMockAnything()\n\n watcherclient.audit_template.list(\n detail=True, **search_opts).AndReturn(audit_templates)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.AuditTemplate.list(\n self.request, **search_opts)\n\n self.assertIn('audit_templates', ret_val)\n for n in ret_val['audit_templates']:\n self.assertIsInstance(n, dict)\n\n self.assertEqual(ret_val, audit_templates)\n\n def test_audit_template_get(self):\n audit_template = self.api_audit_templates.first()\n audit_template_id = self.api_audit_templates.first()['uuid']\n\n watcherclient = self.stub_watcherclient()\n watcherclient.audit_template = self.mox.CreateMockAnything()\n watcherclient.audit_template.get(\n audit_template_id=audit_template_id).AndReturn(audit_template)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.AuditTemplate.get(self.request,\n audit_template_id)\n self.assertIsInstance(ret_val, dict)\n\n def test_audit_template_create(self):\n audit_template = self.api_audit_templates.first()\n name = audit_template['name']\n goal = audit_template['goal_uuid']\n strategy = audit_template['strategy_uuid']\n description = audit_template['description']\n scope = audit_template['scope']\n\n watcherclient = self.stub_watcherclient()\n watcherclient.audit_template = self.mox.CreateMockAnything()\n watcherclient.audit_template.create(\n name=name,\n goal=goal,\n strategy=strategy,\n description=description,\n scope=scope).AndReturn(audit_template)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.AuditTemplate.create(\n self.request, name, goal, strategy,\n description, scope)\n self.assertIsInstance(ret_val, dict)\n\n def test_audit_template_patch(self):\n audit_template = self.api_audit_templates.first()\n audit_template_id = self.api_audit_templates.first()['uuid']\n form_data = {'name': 'new Audit Template 1'}\n\n watcherclient = self.stub_watcherclient()\n watcherclient.audit_template = self.mox.CreateMockAnything()\n watcherclient.audit_template.patch(\n audit_template_id,\n [{'name': 'name', 'value': 'new Audit Template 1'}]\n ).AndReturn(audit_template)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.AuditTemplate.patch(\n self.request, audit_template_id,\n form_data)\n self.assertIsInstance(ret_val, dict)\n\n def test_audit_template_delete(self):\n audit_template_list = self.api_audit_templates.list()\n audit_template_id = self.api_audit_templates.first()['uuid']\n deleted_at_list = self.api_audit_templates.delete()\n\n watcherclient = self.stub_watcherclient()\n watcherclient.audit_template = self.mox.CreateMockAnything()\n watcherclient.audit_template.delete(\n audit_template_id=audit_template_id)\n self.mox.ReplayAll()\n api.watcher.AuditTemplate.delete(self.request,\n audit_template_id)\n self.assertEqual(audit_template_list, deleted_at_list)\n self.assertEqual(len(audit_template_list), len(deleted_at_list))\n\n def test_audit_list(self):\n audits = {'audits': self.api_audits.list()}\n\n watcherclient = self.stub_watcherclient()\n\n watcherclient.audit = self.mox.CreateMockAnything()\n watcherclient.audit.list(detail=True).AndReturn(audits)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.Audit.list(self.request)\n\n self.assertIn('audits', ret_val)\n for n in ret_val['audits']:\n self.assertIsInstance(n, dict)\n\n def test_audit_get(self):\n audit = self.api_audits.first()\n audit_id = self.api_audits.first()['uuid']\n\n watcherclient = self.stub_watcherclient()\n watcherclient.audit = self.mox.CreateMockAnything()\n watcherclient.audit.get(audit_id=audit_id).AndReturn(audit)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.Audit.get(self.request, audit_id)\n self.assertIsInstance(ret_val, dict)\n\n def test_audit_create(self):\n audit = self.api_audits.first()\n audit_template_id = self.api_audit_templates.first()['uuid']\n\n audit_type = self.api_audits.first()['audit_type']\n audit_template_uuid = audit_template_id\n\n watcherclient = self.stub_watcherclient()\n watcherclient.audit = self.mox.CreateMockAnything()\n watcherclient.audit.create(\n audit_template_uuid=audit_template_uuid,\n audit_type=audit_type, auto_trigger=False).AndReturn(audit)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.Audit.create(\n self.request, audit_template_uuid, audit_type)\n self.assertIsInstance(ret_val, dict)\n\n def test_audit_create_with_interval(self):\n audit = self.api_audits.list()[1]\n audit_template_id = self.api_audit_templates.first()['uuid']\n\n audit_type = self.api_audits.first()['audit_type']\n interval = audit['interval']\n audit_template_uuid = audit_template_id\n\n watcherclient = self.stub_watcherclient()\n watcherclient.audit = self.mox.CreateMockAnything()\n watcherclient.audit.create(\n audit_template_uuid=audit_template_uuid,\n audit_type=audit_type,\n auto_trigger=False,\n interval=interval).AndReturn(audit)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.Audit.create(\n self.request, audit_template_uuid, audit_type, False, interval)\n self.assertIsInstance(ret_val, dict)\n\n def test_audit_create_with_auto_trigger(self):\n audit = self.api_audits.list()[1]\n audit_template_id = self.api_audit_templates.first()['uuid']\n\n audit_type = self.api_audits.first()['audit_type']\n audit_template_uuid = audit_template_id\n\n watcherclient = self.stub_watcherclient()\n watcherclient.audit = self.mox.CreateMockAnything()\n watcherclient.audit.create(\n audit_template_uuid=audit_template_uuid,\n audit_type=audit_type,\n auto_trigger=True).AndReturn(audit)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.Audit.create(\n self.request, audit_template_uuid, audit_type, True)\n self.assertIsInstance(ret_val, dict)\n\n def test_audit_delete(self):\n audit_id = self.api_audits.first()['uuid']\n\n watcherclient = self.stub_watcherclient()\n watcherclient.audit = self.mox.CreateMockAnything()\n watcherclient.audit.delete(\n audit_id=audit_id)\n self.mox.ReplayAll()\n\n api.watcher.Audit.delete(self.request, audit_id)\n\n def test_action_plan_list(self):\n action_plans = {'action_plans': self.api_action_plans.list()}\n\n watcherclient = self.stub_watcherclient()\n\n watcherclient.action_plan = self.mox.CreateMockAnything()\n watcherclient.action_plan.list(detail=True).AndReturn(action_plans)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.ActionPlan.list(self.request)\n\n self.assertIn('action_plans', ret_val)\n for n in ret_val['action_plans']:\n self.assertIsInstance(n, dict)\n\n def test_action_plan_get(self):\n action_plan = self.api_action_plans.first()\n action_plan_id = self.api_action_plans.first()['uuid']\n\n watcherclient = self.stub_watcherclient()\n watcherclient.action_plan = self.mox.CreateMockAnything()\n watcherclient.action_plan.get(\n action_plan_id=action_plan_id).AndReturn(action_plan)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.ActionPlan.get(self.request, action_plan_id)\n self.assertIsInstance(ret_val, dict)\n\n def test_action_plan_start(self):\n action_plan_id = self.api_action_plans.first()['uuid']\n\n watcherclient = self.stub_watcherclient()\n watcherclient.action_plan = self.mox.CreateMockAnything()\n watcherclient.action_plan.start(action_plan_id)\n self.mox.ReplayAll()\n\n api.watcher.ActionPlan.start(self.request, action_plan_id)\n\n def test_action_plan_delete(self):\n action_plan_id = self.api_action_plans.first()['uuid']\n\n watcherclient = self.stub_watcherclient()\n watcherclient.action_plan = self.mox.CreateMockAnything()\n watcherclient.action_plan.delete(\n action_plan_id=action_plan_id)\n self.mox.ReplayAll()\n\n api.watcher.ActionPlan.delete(self.request, action_plan_id)\n\n def test_action_list(self):\n actions = {'actions': self.api_actions.list()}\n watcherclient = self.stub_watcherclient()\n\n watcherclient.action = self.mox.CreateMockAnything()\n watcherclient.action.list(detail=True).AndReturn(actions)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.Action.list(self.request)\n\n self.assertIn('actions', ret_val)\n for n in ret_val['actions']:\n self.assertIsInstance(n, dict)\n","sub_path":"watcher_dashboard/test/api_tests/watcher_tests.py","file_name":"watcher_tests.py","file_ext":"py","file_size_in_byte":12677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"478167320","text":"import urllib\nimport json\nimport re\nfrom urllib import FancyURLopener\n\n\nclass MyOpener(FancyURLopener):\n\tversion = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.77.4 (KHTML, like Gecko) Version/7.0.5 Safari/537.77.4'\n\ndef geturl(v):\n\tmyopener = MyOpener()\n\tpage = myopener.open(v)\n\ttxt = page.read()\n\tvideodata = re.findall(r'data-config-url=\"([^\"]*)\"', txt)[0].replace(\"&\", \"&\")\n\tfp=urllib.urlopen(videodata)\n\tj = json.load(fp)\n\n\treturn j[\"request\"][\"files\"][j[\"request\"][\"files\"][\"codecs\"][0]][\"sd\"][\"url\"]\n\n\n\ndef search(pattern):\n\tmyopener = MyOpener()\n\tpage = myopener.open(\"http://vimeo.com/search/sort:relevant/format:detail?\"+urllib.urlencode({\"q\": pattern}))\n\thtml = page.read()\n\t\n\tclipIDs = re.findall(r\"clip_([0-9]+)\", html,re.M)\n\t\n\toptions = []\n\tfor clipID in clipIDs:\n\t\tfp=urllib.urlopen(\"http://vimeo.com/api/v2/video/\"+clipID+\".json\")\n\t\tresults = json.load(fp)\n\t\toptions.append({\n\t\t\t\"title\": results[0][\"title\"],\n\t\t\t\"description\": results[0][\"description\"],\n\t\t\t\"author\": results[0][\"user_name\"],\n\t\t\t\"url\": results[0][\"url\"],\n\t\t\t\"platform\": \"vimeo\",\n\t\t\t\"SERVICE_MOD\": __name__\n\t\t})\n\n\treturn options\n\t#fp=urllib.urlopen(\"http://vimeo.com/search/sort:relevant/format:detail?\"+urllib.urlencode({\"q\": pattern}))\n\t#pattern=re.compile(r\"
  • ]*>(.*?)
  • \", re.S|re.DOTALL)\t\n\n#print search(\"all of me john legend\")\n","sub_path":"services/vimeo.py","file_name":"vimeo.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"617638119","text":"from scipy import *\nfrom pylab import *\nfrom numpy import *\nfrom matplotlib.animation import *\nimport time\n\n\n\"\"\"\nTakes two functions containing variables x, y and computes Newton's method.\n\"\"\"\n\n\nclass fractal2D:\n def __init__(self, f1, f2, f1dx, f1dy, f2dx, f2dy, tol=1.e-8, z=[]):\n self.f1 = f1\n self.f2 = f2\n self.f1dx = f1dx\n self.f1dy = f1dy\n self.f2dx = f2dx\n self.f2dy = f2dy\n self.tol = tol\n self.z = z\n\n # prints the two functions in the form of a Matrix\n def __repr__(self):\n return 'matrix([[{}], [{}]])'.format(self.f1, self.f2)\n def numdif(self, initial, h):\n v = array(initial)\n x, y = v[0], v[1]\n Jh = array([[self.f1(x+h,y), self.f1(x,y+h)],\n [self.f2(x+h,y), self.f2(x,y+h)]])\n J = array([[self.f1(x,y), self.f1(x,y)],\n [self.f2(x,y), self.f2(x,y)]])\n dif = (Jh-J)/h\n return dif\n # implements Newton's method\n def newton(self, initial,simplified, exact, h):\n if simplified == False:\n \"\"\"\n initial should be in the form [x0, y0]\n \"\"\"\n iterations=0\n v = array(initial)\n for i in range(200):\n iterations=iterations+1\n # used for comparison\n vold = v\n x, y = v[0], v[1]\n # computes Jacobian matrix at a given point\n if exact:\n J = array([[self.f1dx(x,y), self.f1dy(x,y)],\n [self.f2dx(x,y), self.f2dy(x,y)]])\n else:\n J = self.numdif(v,h)\n invert = inv(J)\n # computes function matrix at a given point\n F = array([self.f1(x,y), self.f2(x,y)])\n # implements Newton's method\n v = v - invert.dot(F)\n # tolerance check\n if abs(v[0]-vold[0]) < self.tol:\n if abs(v[1]-vold[1]) < self.tol:\n conv = ([v[0], v[1]], i)\n break\n else:\n conv = ((5,5),iterations)\n return conv\n else:\n \"\"\"\n initial should be in the form [x0, y0]\n \"\"\"\n iterations=0\n v = array(initial)\n x, y = v[0], v[1]\n # computes Jacobian matrix at a given point\n if exact:\n J = array([[self.f1dx(x,y), self.f1dy(x,y)],\n [self.f2dx(x,y), self.f2dy(x,y)]])\n else:\n J = self.numdif(v,h)\n invert = inv(J)\n for i in range(200):\n iterations=iterations+1\n # used for comparison\n vold = v\n x, y = v[0], v[1]\n # computes function matrix at a given point\n F = array([self.f1(x,y), self.f2(x,y)])\n # implements Newton's method\n v = v - invert.dot(F)\n # tolerance check\n if abs(v[0]-vold[0]) < self.tol:\n if abs(v[1]-vold[1]) < self.tol:\n conv = ([v[0], v[1]], i)\n break\n else:\n conv = ((5,5),iterations)\n return conv\n \n def zeroes(self, initial, simplified, exact, h):\n \n \"\"\"\n Takes two values. An initial guess in the shape [x0,y0] and a boolean.\n The boolean determines wheter the simplified method should be used or not.\n If the zero value already is in the list it returns the index where it is.\n Otherwise it appends the zero to the list and returns the index where \n the zero is placed. If the list is empty it appends the zero and returns \n index 0. If the newton method doesn't detect convergence it returns the \n index 10.\n \"\"\"\n \n u=self.newton(initial, simplified, exact, h)[:-1]\n u1=u[0][0]\n u2=u[0][1]\n if u1==5 and u2==5:\n return 5\n if not self.z:\n self.z.append(u)\n return 0\n else:\n for n in range(len(self.z)):\n if abs(self.z[n][0][0]-u1) > self.tol and abs(self.z[n][0][1]-u2) > self.tol:\n self.z.append(u)\n return n+1\n else:\n if abs(self.z[n][0][0]-u1) < self.tol and abs(self.z[n][0][1]-u2) < self.tol:\n return n\n \n \n def plot1(self, N, a, b, c, d, simplified, exact, h):\n \n \"\"\"\n Takes two intervals, a step size and a boolean value. The intervals\n determine the initival values of the newton method and the step size how \n many points the grid will be. The grid contains N*N points. The boolean\n if true makes so that the plot method uses the simplified newtonmethod \n and false the regular newtonmethod. It plots the index of where the zero \n is found in red, green, blue and black.\n \"\"\"\n \n X, Y = meshgrid(linspace(a,b, num=N), linspace(c, d, num=N), indexing='ij')\n A=[]\n for i in range(N):\n for j in range(N):\n p=array([X[i,j],Y[i,j]])\n A.append(self.zeroes(p, simplified, exact, h))\n A=reshape(array(A), (N,N))\n\n \n \n colors=matplotlib.colors.ListedColormap(['red', 'green', 'blue','black'])\n bounds=[0,1,2,3,10]\n norm=matplotlib.colors.BoundaryNorm(bounds,colors.N)\n axis([X.min(),X.max(),Y.min(),Y.max()])\n return pcolormesh(X,Y,A, cmap=colors,norm=norm), colorbar(), savefig('Fractal.png')\n \n def IterPlot(self, N, a,b,c,d,simplified, exact, h):\n xmin= a; xmax= b; dx = (xmax-xmin)/N\n ymin= c; ymax= d; dy= (ymax-ymin)/N\n x,y = meshgrid(linspace(xmin,xmax,N),linspace(ymin,ymax,N))\n I=empty((N,N))\n for r in range(N):\n for k in range(N):\n I[r,k]=self.newton((xmin+k*dx+0.0001,ymin+r*dy+0.0001), simplified, exact, h)[1]\n axis([x.min(),x.max(),y.min(),y.max()])\n return pcolormesh(x,y,I,cmap='rainbow'),colorbar(cmap='rainbow')\n \n def animation(self, N, a,b,c,d, simplified, exact, h):\n \n X, Y = meshgrid(linspace(a,b+1, num=N), linspace(c, d+1, num=N), indexing='ij')\n A=[]\n for i in range(N):\n for j in range(N):\n p=array([X[i,j],Y[i,j]])\n A.append(5*self.zeroes(p, simplified, exact, h))\n A=reshape(array(A), (N,N))\n \n xmin= a; xmax= b; dx = (xmax-xmin)/N\n ymin= c; ymax= d; dy= (ymax-ymin)/N\n x,y = meshgrid(arange(xmin,xmax,dx)-dx/2.,arange(ymin,ymax,dy)-dy/2.)\n I=empty((N,N))\n for r in range(N):\n for k in range(N):\n p=array([x[r,k],y[r,k]])\n I[r,k]=self.newton((xmin+k*dx+0.0001,ymin+r*dy+0.0001), simplified, exact, h)[1]\n B=I\n \n self.fig = figure()\n self.ax = self.fig.add_subplot(1,1,1)\n \n def update(i): #funktion som upprepas varje gång processorn \"tickar\", med ökande i\n C = (A*(1+sin(i*pi/16)) + B*(1-sin(i*pi/16)))/2\n pcolor(C)\n time.sleep(0.25)\n \n self.anim = FuncAnimation(self.fig, update)\n \n \n \n#F = fractal2D(lambda x,y: x**3-3*x*y**2-1, lambda x,y: 3*x**2*y-y**3,\n# lambda x,y: 3*x**2 - 3*y**2, lambda x,y: -6*x*y,\n# lambda x,y: 6*x*y, lambda x,y: 3*x**2 - 3*y**2, 1.e-8, z=[])\n#F.animation(40,-10,10,-10,10, False)","sub_path":"newton - Copy.py","file_name":"newton - Copy.py","file_ext":"py","file_size_in_byte":7635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"1318378","text":"\nfrom enthought.traits.api import \\\n Array, Bool, Enum, Float, HasTraits, \\\n HasStrictTraits, \\\n Instance, Int, Trait, Str, Enum, \\\n Callable, List, TraitDict, Any, Range, \\\n Delegate, Event, on_trait_change, Button, \\\n Interface, Property, cached_property, WeakRef, Dict\n\nfrom enthought.traits.ui.api import \\\n Item, View, HGroup, ListEditor, VGroup, \\\n HSplit, Group, Handler, VSplit\n\nfrom enthought.traits.ui.menu import \\\n NoButtons, OKButton, CancelButton, \\\n Action\n\nfrom numpy import zeros, float_\n\nfrom ibvpy.api import\\\n ISDomain, SDomain, SContext, RTraceMngr, ITStepperEval, TStepperEval, TStepper\n#from sdomain import SDomain\n#from scontext import SContext\n\nfrom mgrid_domain import MeshManager\nfrom dots_eval_enr import DOTSManager\n\nfrom ibvpy.core.bc_mngr import BCondMngr\n#from rtrace_mngr import RTraceMngr\nfrom ibvpy.core.ibv_resource import IBVResource\n#from tstepper_eval import ITStepperEval, TStepperEval\n\nclass TStepper_enr(TStepper):\n \"\"\"\n The TStepper is a spatially bounded TStepperEval.\n\n @TODO update this for the new class names\n \n The binding is done by associating the time-stepper with a spatial\n object. In fact, any TStepper, not only the top-level one must\n be associated with spatial object. For the chained\n sub-time-steppers, this association is done using a parameter sctx\n (see the specification above). This parameters stands for spatial\n context. Note, the distinction between the spatial object and\n spatial context. While the spatial object represents a single\n spatial entity (one of domain, element, layer or material point)\n the spatial context represents a complex reference within the\n spatial object In particular, spatial context of a particular\n material point is represented as tuple containing tuple of\n references to [domain, element, layer, integration cell, material\n point].\n \"\"\"\n\n # service specifiers - used to link the service to this object\n service_class = 'ibvpy.plugins.tstepper_service.TStepperService'\n service_attrib = 'tstepper'\n\n # Sub-time-stepper or integrator.\n #\n tse = Instance( DOTSManager )\n\n # Spatial domain to bind the time-stepper to.\n #\n sdomain = Instance( MeshManager )\n# def _sdomain_default( self ):\n# return SDomain()\n\n state_array = Array\n\n sctx = Instance( SContext )\n \n # Boundary condition manager\n #\n bcond_mngr = Instance( BCondMngr )\n def _bcond_mngr_default( self ):\n return BCondMngr()\n\n # Convenience constructor \n #\n # This property provides the possibility to write\n # tstepper.bcond_list = [BCDof(var='u',dof=5,value=0, ... ]\n # The result gets propageted to the BCondMngr\n #\n bcond_list = Property( List )\n def _set_bcond_list( self, bcond_list ):\n self.bcond_mngr.bcond_list = bcond_list\n\n # Response variable manager\n #\n rtrace_mngr = Instance( RTraceMngr )\n def _rtrace_mngr_default( self ):\n return RTraceMngr( tstepper = self )\n\n # Convenience constructor \n #\n # This property provides the possibility to write\n # tstepper.bcond_list = [RVDof(var='u',dof=5,value=0, ... ]\n # The result gets propageted to the RTraceMngr\n #\n rtrace_list = Property( List )\n def _set_rtrace_list( self, rtrace_list ):\n self.rtrace_mngr.rtrace_list = rtrace_list\n\n # Backward reference to the time-loop in order to accommadate the\n # response-trace-evaluators from the top level. These include\n # bookkeeping data like memory usage or solving time per selected\n # type of operation.\n #\n tloop = WeakRef\n\n rte_dict = Property( Dict, depends_on = 'tse:rte_dict')\n def _get_rte_dict( self ):\n '''\n Gather all the currently applicable evaluators from the sub-ts\n and from the time-loop.\n\n Note the control data (time-loop data) is available within the\n model to construct flexible views (tracers) on the model.\n '''\n _rte_dict = {}\n _rte_dict.update( self.tse.rte_dict )\n if self.tloop:\n _rte_dict.update( self.tloop.rte_dict )\n return _rte_dict\n\n new_cntl_var = Delegate( 'tse' )\n\n new_resp_var = Delegate( 'tse' )\n\n # Vector of external forces\n #\n F_ext = Array\n\n # missing - setup of the time-stepper itself. reacting to changes\n # in the sub time-steppers. bcond_list and rtrace_list must be reset once\n # a change has been performed either in a spatial domain or in\n # tse.\n #\n def setup( self ):\n\n # Put the spatial domain into the spatial context\n #\n self.sctx = sctx = self.sdomain.new_scontext()\n\n # Let the boundary conditions setup themselves within the\n # spatial context\n #\n # TODO - the setup needs the link to the algorithm and to the\n # time-steppers as well.!\n #\n self.bcond_mngr.setup( sctx )\n\n # Let the response variables setup themselves within the\n # spatial context\n #\n self.rtrace_mngr.setup( sctx )\n\n # Get the size of the state state and set it up\n #\n sarr_size = self.tse.get_state_array_size( )\n self.state_array = zeros( sarr_size, float_ )\n sctx.state_array = self.state_array\n\n # Let the time-step-evaluators setup themselves within spatial context\n #\n # This steps includes initialization of state arrays and\n # eventual DOF mappings.\n #\n self.tse.setup( sctx )\n\n # Return the response variable to be used when assembling the\n # boundary conditions. Should the bcond_mngr take care of this? \n # That's the source object, isn't it? BCondMngr is the bounded\n # version of the conditions, it could supply the matrix\n # autonomously.\n #\n self.F_ext = self.new_resp_var()\n \n # Prepare the global update flag\n sctx.update_state_on = False\n\n def eval( self, step_flag, U_k, d_U, t_n, t_n1 ):\n\n # Put the spatial domain into the spatial context\n #\n sctx = self.sctx\n\n # Let the time sub-stepper evaluate its contribution.\n #\n F_int, K = self.tse.get_corr_pred( sctx, U_k, d_U, t_n, t_n1 )\n \n #Switch off the global update flag\n sctx.update_state_on = False\n\n self.F_ext[:] = 0.\n\n # Apply the boundary conditions\n #\n self.bcond_mngr.apply( step_flag, K, F_int, self.F_ext, t_n, t_n1 )\n\n return K, F_int, self.F_ext\n \n def update_state(self, U):\n '''\n spatial context represents a stack with the top object\n representing the current level.\n @param U: \n '''\n #sctx = ( self.sdomain, )\n self.sctx.update_state_on = True\n #self.tse.update_state( sctx, U )\n\n def register_mv_pipelines(self,e):\n '''Register the visualization pipelines in mayavi engine\n '''\n self.tse.register_mv_pipelines(e)\n scene = e.new_scene()\n scene.name = 'Spatial domain'\n self.sdomain.register_mv_pipelines(e)\n self.rtrace_mngr.register_mv_pipelines(e)\n\n traits_view = View( Group( Item('sdomain', style = 'custom', show_label = False),\n label = 'Discretization'),\n Group( Item( 'tse', style = 'custom', show_label = False),\n label = 'Integrator'),\n Group( Item('bcond_mngr', style = 'custom', show_label = False),\n label = 'Boundary conditions'),\n resizable = True,\n height = 0.8,\n width = 0.8,\n buttons = [OKButton,CancelButton],\n kind = 'subpanel',\n )\n","sub_path":"scratch/KRAMS/src/apps/scratch/jakub/multiscale/tstepper_enr.py","file_name":"tstepper_enr.py","file_ext":"py","file_size_in_byte":7848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"523404823","text":"\"\"\"\nA basic emulator of a pySerial connection.\nBased off of code from D. Thiebaut (http://cs.smith.edu/dftwiki/index.php/PySerial_Simulator)\n\"\"\"\n\n\nclass FakeSerial:\n \"\"\"\n Emulate a serial port connection.\n \"\"\"\n def __init__(self, port='/dev/USB0', baudrate=19200, timeout=1,\n bytesize=8, parity='N', stopbits=1, xonxoff=0,\n rtscts=0):\n self.port = port\n self.timeout = timeout\n self.parity = parity\n self.baudrate = baudrate\n self.bytesize = bytesize\n self.stopbits = stopbits\n self.xonxoff = xonxoff\n self.rtscts = rtscts\n self._isOpen = True\n self._buffer = \"\"\n\n def isOpen(self):\n \"\"\"\n Get the status of the serial connection\n\n Return (boolean): True if open, False if closed.\n \"\"\"\n return self._isOpen\n\n def open(self):\n \"\"\"\n Open the serial port.\n \"\"\"\n self._isOpen = True\n\n def close(self):\n \"\"\"\n Close the serial port.\n \"\"\"\n self._isOpen = False\n\n def write(self, string):\n \"\"\"\n Write characters to the buffer.\n \"\"\"\n self._buffer += string\n\n def read(self, n=1):\n \"\"\"\n Read characters from the buffer.\n\n Remove the first n characters from the buffer.\n\n Arguments:\n n (integer): number of characters to read\n\n Returns (string): First n characters in the buffer.\n \"\"\"\n s = self._buffer[0:n]\n self._buffer = self._buffer[n:]\n return s\n\n def readline(self):\n \"\"\"\n Read characters from the buffer until a \\n is found.\n\n Returns (string): First n characters in the buffer preceding a \\n\n \"\"\"\n returnIndex = self._buffer.index(r\"\\n\")\n if returnIndex != -1:\n s = self._buffer[0:returnIndex+1]\n self._buffer = self._buffer[returnIndex+1:]\n return s\n else:\n return \"\"\n\n def __str__(self):\n \"\"\"\n Generate a string representation of the serial object\n \"\"\"\n return \"Serial(port='%s', baudrate=%d,\" \\\n % (str(self._isOpen), self.port, self.baudrate) \\\n + \" bytesize=%d, parity='%s', stopbits=%d, xonxoff=%d, rtscts=%d)\"\\\n % (self.bytesize, self.parity, self.stopbits, self.xonxoff,\n self.rtscts)\n","sub_path":"server/fakeserial.py","file_name":"fakeserial.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"237345348","text":"def setup():\n size(500, 500)\n smooth()\n background(150)\n strokeWeight(1)\n \n\nflug = 1\n\ndef draw():\n global flug\n fill(flug, random(0, 30))\n sizeY2 = random(-10, 10)*20\n sizeX2 = random(-10, 10)*20\n ellipse(mouseX, mouseY, sizeX2, sizeY2)\n\ndef keyPressed():\n global flug\n \n if(key=='w'):\n flug = 255\n \n if(key=='b'):\n flug = 0\n \n if (key == 'a'):\n saveFrame(\"myProcessing.pngwwbbbbbbb\")\n \n","sub_path":"Processing Py_!/task_6_4/task_6_4.pyde","file_name":"task_6_4.pyde","file_ext":"pyde","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"407802378","text":"import torch\nimport gym\nfrom gym_starcraft.simple_battle_env import SimpleBattleEnv,Unit_State\n\n\nfrom copy import deepcopy\nfrom itertools import count\n\nfrom Model_hierarchical import *\nfrom config import *\n\n\nconfig = DefaultConfig()\nnp.random.seed(config.RANDOM_SEED)\ntorch.manual_seed(config.RANDOM_SEED)\nif config.GPU >= 0 :\n torch.cuda.manual_seed(config.RANDOM_SEED)\n\n\n# for debug\n\n# from hyperboard import Agent\n# HBagent = Agent(username='jlb',password='123',address='127.0.0.1',port=5002)\n#\n# hp = deepcopy(config.todict())\n# hp['mode'] = 'train_reward'\n# train_r = HBagent.register(hp, 'reward',overwrite=True)\n# hp['mode'] = 'test_reward'\n# test_r = HBagent.register(hp, 'reward',overwrite=True)\n\nenv = SimpleBattleEnv(config.ip,config.port,config.MYSELF_NUM,config.ENEMY_NUM,config.ACTION_DIM,config.DISTANCE_FACTOR,config.POSITION_RANGE,\n config.SCREEN_BOX,config.DIE_REWARD,config.HEALTH_REWARD_WEIGHT,config.DONE_REWARD_WEIGHT,config.MY_HEALTH_WEIGHT,config.ENEMY_HEALTH_WEIGHT,\n config.FOCUS_WEIGHT,config.FRAME_SKIP,config.MAX_STEP,)\n\nenv.seed(config.RANDOM_SEED)\n\n\nddpg_agent = DDPG(env,config=config)\n\nfor episode in count(1):\n print('\\n',episode,ddpg_agent.epsilon)\n obs = env.reset()\n state = ddpg_agent.extract_state(obs)\n cl_total,al_total,qe_total,qt_total = 0,0,0,0\n rs = []\n for step in range(config.MAX_STEP):\n action,command = ddpg_agent.select_action(state,decay_e=True)\n next_obs,reward,done,info = env.step(action)\n\n rs.append(np.asarray(reward))\n next_state = ddpg_agent.extract_state(next_obs)\n ddpg_agent.append_memory(state,command,action,next_state,reward,not done)\n\n ddpg_agent.train_unit()\n ddpg_agent.train_commander()\n # print(reward)\n\n if done:\n qs = []\n q = np.zeros((config.MYSELF_NUM))\n total_reward = 0\n for r in rs[::-1]:\n q = r + config.GAMMA*q\n total_reward += r.sum()/config.MYSELF_NUM\n qs.append(q)\n qs = np.asarray(qs)\n q_mean = np.mean(qs)\n ddpg_agent.train_record[episode] = total_reward\n print('memory: {}/{}'.format(ddpg_agent.commander_memory.current_index,ddpg_agent.commander_memory.max_len))\n print('q_mean: ',q_mean)\n print('train_reward',total_reward)\n # HBagent.append(train_r,episode,total_reward)\n\n break\n\n state = next_state\n\n\n if episode % config.SAVE_ITERVAL == 0:\n print('\\nsave model\\n')\n ddpg_agent.save(episode)\n\n if episode % config.TEST_ITERVAL == 0:\n test_reward,_,_ = ddpg_agent.test(episode,2)\n # HBagent.append(test_r, episode, test_reward)\n\n\n\n\n\n\n\n\n","sub_path":"sc1_train_hierarchical.py","file_name":"sc1_train_hierarchical.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"570915660","text":"from worker import Worker\nimport threading\nfrom K10CR1.k10cr1 import K10CR1\n\n\nclass WK10CR1(Worker):\n type = 'K10CR1'\n\n def setup(self):\n # setup motor\n self.ser_num = self.config.get('CHANNEL{}'.format(self.channel), 'Address')\n self.motor = K10CR1(self.ser_num)\n # setup thread for actuator since moving rotator can take some time\n self.restart = threading.Event() # make an event for unpausing execution thread\n self.thread = threading.Thread(target=self.loop, name=self.wname)\n self.thread.daemon = True # stop thread on exit of main program\n self.thread.start()\n\n def update_output(self):\n # wake up thread (which will push the new output to the rotator)\n self.restart.set()\n self.restart.clear()\n\n def loop(self):\n while True:\n self.restart.wait() # wait for event from main thread\n msg = '{}: Pushing new output to rotator: {}'\n self.logger.debug(msg.format(self.wname, self.ser_num))\n self.motor.moverel(self.delta)\n self.ready = True # let the controller know it can accept new inputs\n","sub_path":"worker_K10CR1.py","file_name":"worker_K10CR1.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"462577871","text":"from rest_framework import generics, viewsets\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework.reverse import reverse\nfrom rest_framework.response import Response\n\nfrom gastos.models import Gastos\nfrom gastos.serializers import GastosSerializer\n\n\"\"\"\n@api_view(('GET',))\ndef api_root(request, format=None):\n return Response({\n 'snippets': reverse('snippet-list', request=request, format=format)\n })\n\n\"\"\"\n\nclass GastosCentro(viewsets.ViewSet):\n queryset = Gastos.objects.all()\n serializer_class = GastosSerializer\n\n def list(self, request, centro=None, seccion=None, programa=None, capitulo=None, economico=None):\n centro = centro.lower()\n d = {'ayuntamiento': 'AYUNTAMIENTO DE MADRID',\n 'informatica': 'Informatica del Ayuntamiento',\n 'empleo': 'Agencia para el Empleo de Madrid',\n 'tributaria': 'Agencia Tributaria Madrid',\n 'salud':'Madrid Salud',\n 'licencias': 'Agencia Gestion Licencias de Actividades'}\n queryset = self.queryset.filter(centro__icontains=d[centro]).values('desc_seccion').distinct()\n seccion_values = queryset\n if seccion or seccion==0:\n seccion = int(seccion)\n seccion = [e for e in seccion_values[seccion].values()][0]\n queryset = queryset.filter(desc_seccion__icontains=seccion).values('desc_programa').distinct()\n programa_values = queryset\n if programa or programa==0:\n programa = int(programa)\n programa = [e for e in programa_values[programa].values()][0]\n print('ales pain menee ', programa)\n queryset = queryset.filter(desc_programa__icontains=programa).values('desc_capitulo').distinct()\n capitulo_values = queryset\n if capitulo or capitulo==0:\n capitulo = int(capitulo)\n capitulo = [e for e in capitulo_values[capitulo].values()][0]\n print('ales pain menee ', capitulo)\n queryset = queryset.filter(desc_capitulo__icontains=capitulo).values('desc_economico').distinct()\n economico_values = queryset\n if economico or economico ==0:\n economico = int(economico)\n economico = [e for e in economico_values[economico].values()][0]\n queryset = queryset.filter(desc_economico__icontains=economico).values('valor')\n print('query values = ', queryset.values())\n queryset = sum([list(e.values())[0] for e in queryset])\n\n queryset = {'valor-final':queryset}\n #serializer = self.serializer_class(queryset, many=True)\n return Response(queryset)#(serializer.data)","sub_path":"democrapp/gastos/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"70117068","text":"# Copyright 2013 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nDEPS = [\n 'clang_tidy',\n 'fuchsia',\n 'recipe_engine/buildbucket',\n 'recipe_engine/json',\n 'recipe_engine/raw_io',\n 'recipe_engine/step',\n]\n\n\ndef RunSteps(api):\n api.clang_tidy.ensure_clang()\n checkout_dir = api.fuchsia.checkout(\n build_input=api.buildbucket.build.input,\n manifest='manifest/minimal',\n remote='tools',\n ).root_dir\n compile_commands = api.clang_tidy.gen_compile_commands(checkout_dir)\n\n all_checks = api.clang_tidy.run('step one', 'path/to/file', compile_commands)\n one_check = api.clang_tidy.run('step two', 'other/path/to/file',\n compile_commands,\n ['-*', 'fuchsia-default-arguments'])\n\n api.clang_tidy.get_line_from_offset('path/to/file', 12)\n api.clang_tidy.get_line_from_offset('other/path/to/file', 65)\n\n\ndef GenTests(api):\n read_output = '''test\nnewline output\n'''\n\n has_errors = '''- DiagnosticName: 'check'\n Message: 'error'\n FileOffset: 1\n FilePath: 'path/to/file'\n'''\n has_errors_json = [{\n 'FileOffset': 1,\n 'DiagnosticName': 'check',\n 'Message': 'error',\n 'FilePath': 'path/to/file'\n }]\n\n yield (api.test('basic') +\n api.buildbucket.try_build(\n git_repo='https://fuchsia.googlesource.com/tools'\n ) +\n api.step_data(\n 'step one.load yaml', stdout=api.json.output(has_errors_json)) +\n api.step_data('step two.load yaml', stdout=api.json.output(''))\n )\n","sub_path":"recipe_modules/clang_tidy/examples/full.py","file_name":"full.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"363531339","text":"# -*- coding: utf-8 -*-\n\n#!/usr/bin/env python3\n\n\"\"\"\n manage\n ~~~~~~\n\n Manager module\n\"\"\"\n\nfrom flask_script import Manager\nfrom lumbermill.api import create_app\nfrom flask import url_for\n\napp = create_app()\nmanager = Manager(app)\n\n\n@manager.command\ndef list_routes():\n output = []\n for rule in app.url_map.iter_rules():\n\n options = {}\n for arg in rule.arguments:\n options[arg] = \"[{0}]\".format(arg)\n\n methods = ','.join(rule.methods)\n url = url_for(rule.endpoint, **options)\n line = \"%s %s %s\" % (rule.endpoint, methods, url)\n output.append(line)\n \n print(\"\\n=== lumbermill Routes ===\\n\")\n \n for line in sorted(output):\n print(line)\n\n\nif __name__ == \"__main__\":\n manager.run()\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"224470235","text":"import os\nfrom datetime import datetime\nimport pytz\n\nfrom datalabframework import logging\nfrom datalabframework.yaml import yaml\nfrom datalabframework._utils import merge, to_ordered_dict\n\nimport json\nimport jsonschema\n\nfrom dotenv import load_dotenv\nfrom jinja2 import Environment\n\nloaded_md_files = []\nprofiles = {}\n\n# metadata files are cached once read the first time\ndef read(file_paths=None):\n \"\"\"\n Return all profiles, stored in a nested dictionary\n Profiles are merged over the list provided of provided metadata files to read. \n The order in the list of metadata files determines how profile properties are override\n :param file_paths: list of yaml files paths\n :return: dict of profiles\n \"\"\"\n global loaded_md_files, profiles\n \n # empty profiles, before start reading \n profiles = {}\n\n if not file_paths:\n file_paths = []\n \n loaded_md_files = []\n for filename in file_paths:\n if os.path.isfile(filename):\n with open(filename, 'r') as f:\n try:\n docs = list(yaml.load_all(f))\n loaded_md_files.append(filename)\n except yaml.YAMLError as e:\n if hasattr(e, 'problem_mark'):\n mark = e.problem_mark\n logging.error(\"Error loading yml file {} at position: (%s:%s): skipping file\".format(filename, mark.line+1, mark.column+1))\n docs = []\n finally:\n for doc in docs:\n doc['profile'] = doc.get('profile', 'default')\n profiles[doc['profile']] = merge(profiles.get(doc['profile'],{}), doc)\n\n return profiles\n\ndef inherit(profiles):\n \"\"\"\n Profiles inherit from a default profile.\n Inherit merges each profile with the configuration of the default profile.\n :param profiles: dict of profiles\n :return: dict of profiles\n \"\"\"\n\n # inherit from default for all other profiles\n for k in profiles.get('default', {}).keys():\n for p in set(profiles.keys()) - {'default'}:\n profiles[p][k] = merge(profiles['default'][k], profiles[p].get(k))\n\n return profiles\n\ndef render(metadata, max_passes=5):\n \"\"\"\n Renders jinja expressions in the given input metadata.\n jinja templates can refer to the dictionary itself for variable substitution\n\n :param metadata: profile dict, values may contain jinja templates\n :param max_passes: max number of rendering passes\n :return: profile dict, rendered jinja templates if present\n \"\"\"\n\n env = Environment()\n \n def env_func(key, value=None):\n return os.getenv(key, value)\n \n def now_func(tz='UTC', format='%Y-%m-%d %H:%M:%S'):\n dt=datetime.now(pytz.timezone(tz))\n return datetime.strftime(dt, format)\n \n env.globals['env'] = env_func\n env.globals['now'] = now_func\n \n doc = json.dumps(metadata)\n\n rendered = metadata\n\n for i in range(max_passes):\n dictionary = json.loads(doc)\n\n #rendering with jinja\n template = env.from_string(doc)\n doc = template.render(dictionary)\n\n # all done, or more rendering required?\n rendered = json.loads(doc)\n if dictionary == rendered:\n break\n\n return rendered\n\ndef v(d, schema):\n msg_error=None\n try:\n jsonschema.validate(d, schema)\n return\n except jsonschema.exceptions.ValidationError as e:\n msg_error = f'{e.message} \\n\\n## schema path:\\n'\n msg_error += f'\\'{\"/\".join(e.schema_path)}\\'\\n\\n'\n msg_error += f'## metadata schema definition '\n msg_error += f'{\"for \" + str(e.parent) if e.parent else \"\"}:'\n msg_error += f'\\n{yaml.dump(e.schema)}'\n \n if msg_error:\n raiseException(msg_error)\n \ndef validate_schema(md, schema_filename):\n dir_path = os.path.dirname(os.path.realpath(__file__))\n filename = os.path.abspath(os.path.join(dir_path, 'schemas/{}'.format(schema_filename)))\n with open(filename) as f:\n v(md, yaml.load(f))\n\ndef validate(md):\n\n # validate data structure\n validate_schema(md, 'top.yml')\n \n # for d in md['providers']:\n # _validate_schema(d, 'provider.yml')\n #\n # for d in md['resources']:\n # _validate_schema(d, 'resource.yml')\n\n # validate semantics\n providers = md.get('providers', {}).keys()\n for resource_alias, r in md.get('resources',{}).items():\n resource_provider = r.get('provider')\n if resource_provider and resource_provider not in providers:\n print(f'resource {resource_alias}: given provider \"{resource_provider}\" '\n 'does not match any metadata provider')\n\ndef formatted(md):\n keys = (\n 'profile',\n 'variables',\n ('engine',(\n 'type',\n 'master',\n 'jobname',\n 'timezone',\n ('submit',(\n 'detect',\n 'jars',\n 'packages',\n 'py-files',\n )),\n 'config',\n )\n ),\n 'providers',\n 'resources',\n ('loggers',(\n ('root',('severity',)),\n ('datalabframework',(\n 'name',\n ('stream',(\n 'severity',\n 'enable',\n )),\n ('stdout',(\n 'severity',\n 'enable',\n )),\n ('file',(\n 'severity',\n 'enable',\n 'path',\n )),\n ('kafka',(\n 'severity',\n 'enable',\n 'hosts',\n 'topic',\n ))\n ))\n )),\n )\n \n d = to_ordered_dict(md, keys)\n \n if d['variables']:\n d['variables'] = dict(sorted(d['variables'].items()))\n \n return d\n\ndef debugMetadataFiles():\n message = '\\nList of loaded metadata files:\\n'\n if loaded_md_files:\n for f in loaded_md_files:\n message += f' - {f}\\n'\n else:\n message += 'None'\n \n return message\n\ndef debugProfiles():\n message = '\\nList of available profiles:\\n'\n if profiles:\n for f in profiles.keys():\n message += f' - {f}\\n'\n else:\n message += 'None'\n \n return message\n\ndef raiseException(message=''):\n message += '\\n'\n message += debugMetadataFiles()\n message += debugProfiles()\n raise ValueError(message)\n \ndef load(profile='default', metadata_files=None, dotenv_path=None):\n \"\"\"\n Load the profile, given a list of yml files and a .env filename\n profiles inherit from the defaul profile, a profile not found will contain the same elements as the default profile\n\n :param profile: the profile to load (default: 'default')\n :param metadata_files: a list of metadata files to read \n :param dotenv_path: the path of a dotenv file to read\n :return: the loaded metadata profile dict\n \"\"\"\n # get env variables from .env file\n if dotenv_path and os.path.isfile(dotenv_path):\n load_dotenv(dotenv_path)\n \n profiles = read(metadata_files)\n \n # empty profile if profile not found\n if profile not in profiles.keys():\n raiseException(f'Profile \"{profile}\" not found.')\n\n # read metadata, get the profile, if not found get an empty profile\n profiles = inherit(profiles)\n metadata = profiles[profile]\n\n # render any jinja templates in the profile\n md = render(metadata)\n \n # validate\n validate(md)\n \n # format\n md = formatted(md)\n return md\n","sub_path":"datalabframework/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":7862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"53283240","text":"# -*- coding:utf-8 -*-\nimport logging\nlogger = logging.getLogger(__name__)\nfrom functools import partial\nimport pkg_resources\nimport sys\n\n\nPHASE1_CONFIG = -20\nPHASE2_CONFIG = -10\n\n\nclass ConfigurationError(Exception):\n pass\n\n\ndef import_symbol(symbol):\n return pkg_resources.EntryPoint.parse(\"x=%s\" % symbol).load(False)\n\n\ndef caller_module(level=2):\n module_globals = sys._getframe(level).f_globals\n name = module_globals.get(\"__name__\", \"__main__\")\n return sys.modules[name]\n\n\nclass Control(object):\n pass\n\n\nclass ConfiguratorCore(object):\n def __init__(self, settings=None, module=None, queue=None, control=None):\n self.settings = settings or {}\n self.module = module or caller_module()\n self.queue = queue or []\n self.control = control or Control()\n\n def build_import_symbol_string(self, fn_or_string):\n if not fn_or_string.startswith(\".\"):\n return fn_or_string\n\n nodes = self.module.__name__.split(\".\")\n if fn_or_string.endswith(\".\"):\n fn_or_string = fn_or_string[1:]\n\n for i, c in enumerate(fn_or_string):\n if c != \".\":\n break\n nodes.pop()\n if fn_or_string == \"\" or fn_or_string.endswith(\".\"):\n return \".\".join(nodes)\n return \".\".join(nodes) + \".\" + fn_or_string[i:]\n\n def include(self, fn_or_string):\n if callable(fn_or_string):\n includeme = fn_or_string\n module = getattr(fn_or_string, \"__module__\", None)\n else:\n symbol_string = self.build_import_symbol_string(fn_or_string)\n if \":\" in symbol_string:\n module_string, fn_name = symbol_string.split(\":\", 1)\n else:\n module_string, fn_name = symbol_string, \"includeme\"\n module = import_symbol(module_string)\n includeme = getattr(module, fn_name)\n\n config = self.__class__(self.settings,\n module=module,\n queue=self.queue,\n control=self.control)\n return includeme(config)\n\n def action(self, callback, order=0):\n self.queue.append((order, callback))\n\n def commit(self):\n for o, callback in sorted(self.queue, key=lambda xs: xs[0]):\n callback()\n self.queue = []\n\n def maybe_dotted(self, fn_or_string):\n if callable(fn_or_string):\n return fn_or_string\n symbol_string = self.build_import_symbol_string(fn_or_string)\n return import_symbol(symbol_string)\n\n def add_directive(self, name, fn_or_string):\n fn = self.maybe_dotted(fn_or_string)\n setattr(self.control, name, fn)\n\n def __getattr__(self, name):\n attr = getattr(self.control, name)\n if callable(attr):\n return partial(attr, self)\n return attr\n","sub_path":"miniconfig/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"69481009","text":"import os\nimport cv2\nimport matplotlib.pyplot as plt\ndef main():\n \n \n img=cv2.imread('im2.jpg') \n laplacian=cv2.Laplacian(img,cv2.CV_64F)\n sobelx=cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5)\n sobely=cv2.Sobel(img,cv2.CV_64F,0,1,ksize=5)\n edges=cv2.Canny(img,100,100)\n cv2.imshow('edges',edges)\n cv2.imshow('sobelx',sobelx)\n cv2.imshow('sobely',sobely)\n cv2.imshow('img',img)\n cv2.imshow('laplacian',laplacian)\n cv2.waitKey()\n cv2.destroyAllWindows\n \nmain()","sub_path":"EdgeDetection.py","file_name":"EdgeDetection.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"20312899","text":"board = [[' ', ' ', ' '],\r\n [' ', ' ', ' '],\r\n [' ', ' ', ' ']]\r\nplayer1 = True\r\nframeCount = 0\r\nsystemCheck = 0\r\nwwonn = ''\r\n\r\nBLACKTRSP = 0, 0, 0\r\n\r\nHEIGHT = 700\r\nWIDTH = HEIGHT\r\n\r\ndef draw():\r\n screen.draw.filled_rect(Rect((0, 0), (WIDTH, HEIGHT)), BLACKTRSP)\r\n drawLines()\r\n drawBoard()\r\n\r\n screen.draw.text('Please put in an\\nempty square', center=(WIDTH / 2, HEIGHT / 2), fontsize=p5map(100, 0, 700, 0, HEIGHT), color=(0, 255, 255), alpha=systemCheck / 255)\r\n if wwonn != '':\r\n screen.clear()\r\n screen.draw.text(wwonn + \" has won!\\n'Y' to replay,\\n'N' not to\", center=(WIDTH / 2, HEIGHT / 2), fontsize=p5map(100, 0, 700, 0, HEIGHT), color=(255, 0, 255))\r\n\r\ndef on_key_down(key):\r\n global wwonn\r\n if wwonn != '':\r\n if key == keys.Y:\r\n global board\r\n board = [[' ', ' ', ' '],\r\n [' ', ' ', ' '],\r\n [' ', ' ', ' ']]\r\n wwonn = ''\r\n systemCheck = 0\r\n elif key == keys.N:\r\n exit()\r\n\r\ndef on_mouse_down(pos):\r\n x = pos[0]\r\n y = pos[1]\r\n # board[(p5rund(x - (WIDTH / 6)) - 1) + 1][(p5rund(y - (HEIGHT / 6)) - 1) + 1] = 1\r\n x = (p5rund(x - (WIDTH / 6), WIDTH) - 1) + 1\r\n y = (p5rund(y - (HEIGHT / 6), HEIGHT) - 1) + 1\r\n global player1\r\n if board[y][x] == ' ':\r\n if player1 == True:\r\n board[y][x] = 'X'\r\n player1 = False\r\n else:\r\n board[y][x] = 'O'\r\n player1 = True\r\n else:\r\n global systemCheck\r\n systemCheck = 300\r\n\r\n if checkWon() != 'n':\r\n clock.schedule_unique(cch, 0.1)\r\n\r\ndef cch():\r\n global wwonn\r\n wwonn = checkWon()\r\n\r\ndef update():\r\n global frameCount\r\n frameCount += 1\r\n\r\n global systemCheck\r\n systemCheck -= 3\r\n\r\ndef checkWon():\r\n for y in range(0, len(board), 1): # Check rows\r\n if board[y][0] == board[y][1] and board[y][1] == board[y][2] and board[y][0] != ' ':\r\n return board[y][0] # Who won\r\n for x in range(0, len(board), 1): # Check columns\r\n if board[0][x] == board[1][x] and board[1][x] == board[2][x] and board[0][x] != ' ':\r\n return board[0][x]\r\n if board[0][0] == board[1][1] and board[1][1] == board[2][2] and board[0][0] != ' ': # Check diagonals\r\n return board[0][0]\r\n if board[0][2] == board[1][1] and board[1][1] == board[2][0] and board[0][2] != ' ': # Check diagonals\r\n return board[0][0]\r\n return 'n'\r\n\r\ndef drawBoard():\r\n for y in range(0, len(board), 1):\r\n for x in range(0, len(board[0]), 1):\r\n screen.draw.text(board[y][x], center=((x * (WIDTH / 3)) + (WIDTH/6), y * (HEIGHT / 3) + (HEIGHT / 6)), fontsize=HEIGHT / 3)\r\n\r\ndef drawLines():\r\n strk = p5map(10, 0, 600, 0, HEIGHT)\r\n screen.draw.filled_rect(Rect((((WIDTH / 3) - (strk / 2)), 0), (strk, HEIGHT)), (255, 255, 0))\r\n screen.draw.filled_rect(Rect(((((WIDTH / 3) * 2) - (strk / 2)), 0), (strk, HEIGHT)), (255, 255, 0))\r\n screen.draw.filled_rect(Rect((0, ((HEIGHT / 3) - (strk / 2))), (WIDTH, strk)), (255, 255, 0))\r\n screen.draw.filled_rect(Rect((0, (((HEIGHT / 3) * 2) - (strk / 2))), (WIDTH, strk)), (255, 255, 0))\r\n\r\ndef p5rund(n, rw):\r\n return round((n * len(board)) / rw)\r\n\r\ndef p5map(n, start1, stop1, start2, stop2):\r\n return ((n-start1) / (stop1-start1)) * (stop2 - start2) + start2","sub_path":"intro.py","file_name":"intro.py","file_ext":"py","file_size_in_byte":3373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"60999729","text":"from application import database, ps\nfrom typing import List\nfrom uuid import uuid4, UUID\n\n\nasync def add_new_group(new_group: str):\n query = ps.UserGroup.insert()\n values = {\n \"id\": uuid4(),\n \"group\": new_group\n }\n await database.execute(query=query, values=values)\n return values\n\n\nasync def get_all_groups(offset: int = 0, limit: int = 10):\n query = ps.UserGroup.select().offset(offset).limit(limit)\n groups = await database.fetch_all(query)\n return groups\n\n\nasync def get_all_groups_count() -> int:\n query = ps.UserGroup.count()\n count = await database.execute(query)\n return count\n\n\nasync def get_user_group_by_name(group: str):\n query = ps.UserGroup.select().where(ps.UserGroup.columns.group == group)\n group = await database.fetch_one(query)\n return group\n\n\nasync def get_user_group_by_id(group_id: UUID):\n query = ps.UserGroup.select().where(ps.UserGroup.columns.id == group_id)\n group = await database.fetch_one(query)\n return group\n\n\nasync def delete_group_in_db(group_id: UUID) -> bool:\n query = ps.UserGroup.delete().where(ps.UserGroup.columns.id == group_id)\n await database.execute(query)\n exists = await get_user_group_by_id(group_id)\n return True if not exists else False\n","sub_path":"ra_graphql/crud/group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"414201449","text":"import db\n\nclass Recipe(object):\n def __init__(self, name, ingredients):\n self.name = name\n self.ingredients = ingredients\n # you could also check here for properly formatted ingredients\n\n def need_ingredients(self):\n needed = []\n for (generic_type, amount) in self.ingredients:\n matching = db.check_inventory_for_type(generic_type)\n\n max_m = ''\n max_l = ''\n max_amount = 0.0\n\n for (m, l, t) in matching:\n if t > max_amount:\n max_amount = t\n\n amount_needed = db.convert_to_ml(amount)\n\n if max_amount < amount_needed:\n needed.append((generic_type, amount_needed - max_amount))\n\n return needed\n\ndef filter_recipes_by_ingredients(recipe_list):\n x = []\n \n for r in recipe_list:\n if not r.need_ingredients():\n x.append(r)\n\n return x\n","sub_path":"drinkz/recipes.py","file_name":"recipes.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"380122537","text":"from django import forms\nfrom django.contrib.auth import get_user_model\n\nfrom datetimewidget.widgets import DateWidget\n\nfrom .models import Monster, UserMonsterAction, UserMonster\n\n\nclass UserMonsterActionForm(forms.ModelForm):\n class Meta:\n model = UserMonsterAction\n fields = [\n 'timestamp',\n 'monsteraction',\n 'remarks',\n ]\n widgets = {\n 'timestamp': DateWidget(usel10n=True, bootstrap_version=3),\n }\n\n\nclass UserMonsterForm(forms.ModelForm):\n class Meta:\n model = UserMonster\n fields = [\n # 'user',\n # 'monster',\n # 'monster_number',\n ]\n","sub_path":"lalalalife/monsters/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"332268858","text":"import matplotlib.pyplot as plt\nimport Nio, sys, argparse\nimport numpy as np\nfrom scipy import signal\nfrom pprint import pprint\n\ndef SpectralVariance(y):\n c = np.fft.rfft(signal.detrend(y), norm=\"ortho\") # Ortho means normalized by sqrt N\n return abs(c)**2.0\n \nparser = argparse.ArgumentParser()\nparser.add_argument('--input-dir', dest='input_dir')\nparser.add_argument('--output-dir', dest='output_dir')\nparser.add_argument('--casenames', dest='casenames')\nparser.add_argument('--legends')\nparser.add_argument('--data-file', dest='data_file')\nparser.add_argument('--varname', dest='varname')\n\nargs = parser.parse_args()\n\npprint(args)\n\ncasenames = args.casenames.split(\",\")\nlegends = args.legends.split(\",\")\n\nprint(\"Going to compare these models:\")\npprint(casenames)\n\ntss = []\nsps = []\n\nfor i in range(len(casenames)):\n\n f = Nio.open_file(\"%s/%s/%s.nc\" % (args.input_dir, casenames[i], args.data_file), \"r\")\n \n ts = f.variables[args.varname][:]\n ts /= np.std(ts)\n\n sp = SpectralVariance(ts)\n\n tss.append(ts)\n sps.append(sp)\n\n f.close()\n\n\nN = len(tss[0])\nfreq = np.fft.rfftfreq(N, d=1.0/12.0)\ntime = np.arange(N) / 12\nnyears = N / 12.0\nperiod = 1.0 / freq\n\nmarked_periods = np.array([0.5, 1, 2, 3, 4, 5, 10, 20, 30, 40])\n\nfig, ax = plt.subplots(2, 1, figsize=(12, 10))\n\nax[0].set_title(\"%s indices (%d years)\" % (args.varname, nyears, ))\nax[0].set_xlabel(\"Time [years]\")\nax[0].plot([time[0], time[-1]], [0, 0], \"-\", color=\"#cccccc\", linewidth=2)\n\nfor i in range(len(casenames)): \n ax[0].plot(time, tss[i], linewidth=2, label=casenames[i])\n\nax[0].legend()\n\nax[1].set_title(\"Spectrum Analysis\")\nax[1].set_xlabel(\"Period [years]\")\n\nfor i in range(len(casenames)): \n ax[1].loglog(period[1:], sps[i][1:], linewidth=2, label=legends[i])\n #ax[1].plot(period[1:], sps[i][1:], linewidth=2, label=casenames[i])\n\nax[1].legend()\n\nax[1].set_xticks(marked_periods)\nax[1].set_xticklabels([(\"%.1f\" if v<1 else \"%d\") % (v,) for v in marked_periods])\n\nfig.savefig(\"%s/mc_climate_indices_%s.png\" % (args.output_dir, args.varname), dpi=200)\n\n#plt.show()\n","sub_path":"other_src/diagnose_scripts/plot/plot_mc_global_mean_temperature.py","file_name":"plot_mc_global_mean_temperature.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"115977375","text":"class Solution:\n def solve(self, board) -> None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n \"\"\"\n m = len(board)\n if m < 3:\n return\n n = len(board[0])\n if n < 3:\n return\n visited = [[False if board[i][j] == 'O' else True for j in range(n)] for i in range(m)]\n mask, flip = {}, {}\n\n def dfs(r, c, count):\n if r < 0 or r >= m or c < 0 or c >= n or visited[r][c]:\n return\n if board[r][c] == 'O':\n visited[r][c] = True\n mask[(r, c)] = count\n if r == 0 or r == m - 1 or c == 0 or c == n - 1:\n flip[count] = 'O'\n dfs(r - 1, c, count)\n dfs(r + 1, c, count)\n dfs(r, c - 1, count)\n dfs(r, c + 1, count)\n\n count = 0\n for i in range(m):\n for j in range(n):\n if not visited[i][j]:\n count += 1\n flip[count] = 'X'\n dfs(i, j, count)\n for c in mask:\n board[c[0]][c[1]] = flip[mask[c]]\n return\n\n\ns = Solution()\nboard = [[\"X\", \"O\", \"O\", \"X\", \"X\", \"X\", \"O\", \"X\", \"O\", \"O\"],\n [\"X\", \"O\", \"X\", \"X\", \"X\", \"X\", \"X\", \"X\", \"X\", \"X\"],\n [\"X\", \"X\", \"X\", \"X\", \"O\", \"X\", \"X\", \"X\", \"X\", \"X\"],\n [\"X\", \"O\", \"X\", \"X\", \"X\", \"O\", \"X\", \"X\", \"X\", \"O\"],\n [\"O\", \"X\", \"X\", \"X\", \"O\", \"X\", \"O\", \"X\", \"O\", \"X\"],\n [\"X\", \"X\", \"O\", \"X\", \"X\", \"O\", \"O\", \"X\", \"X\", \"X\"],\n [\"O\", \"X\", \"X\", \"O\", \"O\", \"X\", \"O\", \"X\", \"X\", \"O\"],\n [\"O\", \"X\", \"X\", \"X\", \"X\", \"X\", \"O\", \"X\", \"X\", \"X\"],\n [\"X\", \"O\", \"O\", \"X\", \"X\", \"O\", \"X\", \"X\", \"O\", \"O\"],\n [\"X\", \"X\", \"X\", \"O\", \"O\", \"X\", \"O\", \"X\", \"X\", \"O\"]]\ns.solve(board)\nprint(board)\n","sub_path":"leetcode/2020/SurroundRegion.py","file_name":"SurroundRegion.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"189084662","text":"#!/usr/bin/env python3\n\nimport os\nimport glob\nimport tornado.template\nimport urllib.request\nfrom urllib.parse import urljoin\n\nfrom pkg_resources import parse_version\n\nfrom lilaclib import *\n\ndebug = False\n_version = '1.16.0'\n_version_date = '2016-12-23'\n\nSTDS = [\n 'arm-unknown-linux-gnueabihf',\n 'armv7-unknown-linux-gnueabihf',\n 'x86_64-unknown-linux-gnu',\n 'i686-unknown-linux-gnu',\n 'i686-pc-windows-gnu', # need libgcc_s_dw2-1.dll\n 'x86_64-pc-windows-gnu',\n 'asmjs-unknown-emscripten',\n 'wasm32-unknown-emscripten',\n 'wasm32-unknown-unknown',\n 'aarch64-linux-android',\n]\n\ndist_url = 'https://static.rust-lang.org/dist/index.html'\n\nbuild_prefix = 'extra-x86_64'\n\ntoolchain = {\n 'x86_64-pc-windows-gnu': ['mingw-w64-gcc'],\n 'i686-pc-windows-gnu': ['mingw-w64-gcc'],\n 'i686-unknown-linux-gnu': ['gcc-multilib'],\n 'asmjs-unknown-emscripten': ['emsdk', 'emscripten'],\n 'wasm32-unknown-emscripten': ['emsdk', 'emscripten'],\n 'wasm32-unknown-unknown': [],\n 'aarch64-linux-android': ['android-ndk'],\n}\n\ndef get_latest_version():\n if not debug:\n res = urllib.request.urlopen(dist_url)\n page = res.read().decode('utf-8')\n version_date = re.findall(r'(\\d{4}-\\d{2}-\\d{2})/', page)[-1]\n stable = sorted(set(re.findall(r'\\d+\\.\\d+\\.\\d+', page)), key=parse_version)[-1]\n major, minor, patchlevel = stable.split('.')\n version = '%s.%s.%s' % (major, int(minor) + 2, patchlevel)\n return version, version_date\n else:\n return _version, _version_date\n\nclass Std:\n def __init__(self, platform, date):\n self.name = 'rust-std-nightly-' + platform\n self.url = urljoin(dist_url, date + '/' + self.name + '.tar.xz')\n self.platform = platform\n self.optdepends = toolchain.get(platform)\n\ndef pre_build():\n version, version_date = get_latest_version()\n if not debug:\n oldfiles = glob.glob('*.xz') + glob.glob('*.xz.asc') + glob.glob('*.part')\n for f in oldfiles:\n os.unlink(f)\n\n stds = [Std(x, version_date) for x in STDS]\n\n loader = tornado.template.Loader('.')\n content = loader.load('PKGBUILD.tmpl').generate(\n stds = stds,\n version = version,\n version_date = version_date.replace('-', ''),\n version_date_raw = version_date,\n )\n with open('PKGBUILD', 'wb') as output:\n output.write(content)\n\ndef post_build():\n git_add_files(['PKGBUILD'])\n git_commit()\n\nif __name__ == '__main__':\n single_main()\n","sub_path":"rust-nightly/lilac.py","file_name":"lilac.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"198305489","text":"import sys\nfrom collections import deque\n\nDIRS = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n\nH, W = map(int, input().split())\na = {}\nsecs = {}\nwarps = {}\nfor i in range(H):\n l = input()\n for j in range(len(l)):\n c = l[j]\n\n p = (i, j)\n a[p] = c\n\n if c == '#':\n secs[p] = -1\n elif c == 'S':\n S = p\n secs[p] = 0\n elif c == 'G':\n G = p\n elif c.islower():\n if c not in warps:\n warps[c] = [p]\n else:\n warps[c].append(p)\n\nqueue = deque()\nqueue.append(S)\n\nwhile len(queue):\n p = queue.popleft()\n c = a[p]\n s = secs[p]\n ns = s + 1\n\n for dir in DIRS:\n np = (p[0] + dir[0], p[1] + dir[1])\n if np[0] < 0 or np[0] >= H or np[1] < 0 or np[1] >= W:\n continue\n\n nc = a[np]\n\n if np in secs:\n continue\n if nc == '#':\n continue\n if nc == 'G':\n print(ns)\n sys.exit(0)\n \n secs[np] = ns\n queue.append(np)\n\n if c.islower():\n for wp in [wp for wp in warps[c] if wp != p and wp not in secs]:\n secs[wp] = ns\n queue.append(wp)\n\nprint(-1)","sub_path":"tasks/abc184/abc184_e.py","file_name":"abc184_e.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"523634245","text":"#Full credit to https://raw.githubusercontent.com/pcfens/RaspberryPi-AS3935 (or who ever\n#originally wrote this)\n\n#This is a mod for micropython on a NodeMCU v3.0\nfrom time import sleep, sleep_ms\nfrom machine import reset\n\n# AS3935 default address.\nAS3935_I2CADDR = 0x03\n\nclass ESP_AS3935:\n \"\"\"A basic class used for interacting with the AS3935 lightning\n sensor from a esp8266 over I2C\"\"\"\n\n def __init__(self,\n i2c_address=AS3935_I2CADDR,\n i2c=None,\n indoors=True,\n noise_floor=2,\n min_strikes=1,\n on_init=True):\n self.i2c_address = i2c_address\n if i2c is None:\n raise ValueError('An I2C object is required.')\n self.i2c = i2c\n # temporary data holders which stay allocated\n self._1_barray = bytearray(1)\n self._3_barray = bytearray(3)\n #sleep(0.5)\n #self.reset()\n if on_init == True:\n print('init AS3935')\n self.reset()\n sleep(0.5)\n self.set_indoors(indoors)\n self.set_noise_floor(noise_floor)\n #self.set_min_strikes(min_strikes)\n sleep(0.5)\n self.calibrate(tun_cap=0x02)\n\n def calibrate(self, tun_cap=None): #check\n \"\"\"Calibrate the lightning sensor - this takes up to half a second\n and is blocking.\n The value of tun_cap should be between 0 and 15, and is used to set\n the internal tuning capacitors (0-120pF in steps of 8pF)\n \"\"\"\n sleep(0.08)\n if tun_cap is not None:\n if tun_cap < 0x10 and tun_cap > -1:\n self.i2c.readfrom_mem_into(self.i2c_address, 0x08, self._1_barray)\n self._1_barray[0] = (self._1_barray[0] & 0xF0) | tun_cap\n self.i2c.writeto_mem(self.i2c_address, 0x08, self._1_barray)\n #write_value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x08,1))) & 0xF0) | tun_cap\n #self.i2c.writeto_mem(self.i2c_address, 0x08, bytes(int_to_bytes(write_value,1)))\n sleep_ms(2)\n else:\n raise Exception(\"Value of TUN_CAP must be between 0 and 15\")\n\n self._1_barray[0] = 0x96\n self.i2c.writeto_mem(self.i2c_address, 0x3D, self._1_barray)\n\n sleep_ms(2)\n self.i2c.readfrom_mem_into(self.i2c_address, 0x08, self._1_barray)\n self._1_barray[0] = self._1_barray[0] | 0x20\n self.i2c.writeto_mem(self.i2c_address, 0x08, self._1_barray)\n #write_value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x08,1))) | 0x20)\n #self.i2c.writeto_mem(self.i2c_address, 0x08, bytes(int_to_bytes(write_value,1)))\n sleep_ms(2)\n self.i2c.readfrom_mem_into(self.i2c_address, 0x08, self._1_barray)\n self._1_barray[0] = self._1_barray[0] & 0xDF\n self.i2c.writeto_mem(self.i2c_address, 0x08, self._1_barray)\n #write_value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x08,1))) & 0xDF)\n #self.i2c.writeto_mem(self.i2c_address, 0x08, bytes(int_to_bytes(write_value,1)))\n sleep_ms(2)\n\n def reset(self):\n \"\"\"Reset all registers to their default power on values\n \"\"\"\n self._1_barray[0] = 0x96\n self.i2c.writeto_mem(self.i2c_address, 0x3C, self._1_barray)\n #self.i2c.writeto_mem(self.i2c_address, 0x3C, bytes(int_to_bytes(0x96,1)))\n\n def get_interrupt(self):\n \"\"\"Get the value of the interrupt register\n 0x01 - Too much noise\n 0x04 - Disturber\n 0x08 - Lightning\n \"\"\"\n try:\n self.i2c.readfrom_mem_into(self.i2c_address, 0x03, self._1_barray)\n except OSError:\n reset()\n return self._1_barray[0] & 0x0F\n #return (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x03,1))) & 0x0F)\n\n def get_distance(self):\n \"\"\"Get the estimated distance of the most recent lightning event\n \"\"\"\n self.i2c.readfrom_mem_into(self.i2c_address, 0x07, self._1_barray)\n if (self._1_barray[0] & 0x3F) == 0x3F:\n return False\n else:\n return self._1_barray[0] & 0x3F\n\n #if (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x07,1))) & 0x3F) == 0x3F:\n # return False\n #else:\n # return (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x07,1))) & 0x3F)\n\n def get_energy(self):\n \"\"\"Get the calculated energy of the most recent lightning event (3 bytes)\n \"\"\"\n self.i2c.readfrom_mem_into(self.i2c_address, 0x04, self._3_barray)\n return ((self._3_barray[2] & 0x1F) << 16 | self._3_barray[1] << 8 | self._3_barray[0])\n\n def get_noise_floor(self):\n \"\"\"Get the noise floor value.\n\n Actual voltage levels used in the sensor are located in Table 16\n of the data sheet.\n \"\"\"\n self.i2c.readfrom_mem_into(self.i2c_address, 0x01, self._1_barray)\n return (self._1_barray[0] & 0x70) >> 4\n\n #return (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x01,1))) & 0x70) >> 4\n\n def set_noise_floor(self, noisefloor):\n \"\"\"Set the noise floor value.\n\n Actual voltage levels used in the sensor are located in Table 16\n of the data sheet.\n \"\"\"\n noisefloor = (noisefloor & 0x07) << 4\n self.i2c.readfrom_mem_into(self.i2c_address, 0x01, self._1_barray)\n self._1_barray[0] = (self._1_barray[0] & 0x8F) + noisefloor\n self.i2c.writeto_mem(self.i2c_address, 0x01, self._1_barray)\n\n #write_value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x01,1))) & 0x8F) + noisefloor\n #self.i2c.writeto_mem(self.i2c_address, 0x01, bytes(int_to_bytes(write_value,1)))\n\n def lower_noise_floor(self, min_noise=0):\n \"\"\"Lower the noise floor by one step.\n\n min_noise is the minimum step that the noise_floor should be\n lowered to.\n \"\"\"\n floor = self.get_noise_floor()\n if floor > min_noise:\n floor = floor - 1\n self.set_noise_floor(floor)\n return floor\n\n def raise_noise_floor(self, max_noise=7):\n \"\"\"Raise the noise floor by one step\n\n max_noise is the maximum step that the noise_floor should be\n raised to.\n \"\"\"\n floor = self.get_noise_floor()\n if floor < max_noise:\n floor = floor + 1\n self.set_noise_floor(floor)\n return floor\n\n def get_min_strikes(self):\n \"\"\"Get the number of lightning detections required before an\n interrupt is raised.\n \"\"\"\n self.i2c.readfrom_mem_into(self.i2c_address, 0x02, self._1_barray)\n value = (self._1_barray[0] >> 4 ) & 0x03\n #value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x02,1))) >> 4) & 0x03\n if value == 0:\n return 1\n elif value == 1:\n return 5\n elif value == 2:\n return 9\n elif value == 3:\n return 16\n\n def set_min_strikes(self, minstrikes):\n \"\"\"Set the number of lightning detections required before an\n interrupt is raised.\n\n Valid values are 1, 5, 9, and 16, any other raises an exception.\n \"\"\"\n if minstrikes == 1:\n minstrikes = 0\n elif minstrikes == 5:\n minstrikes = 1\n elif minstrikes == 9:\n minstrikes = 2\n elif minstrikes == 16:\n minstrikes = 3\n else:\n raise Exception(\"Value must be 1, 5, 9, or 16\")\n\n minstrikes = (minstrikes & 0x03) << 4\n self.i2c.readfrom_mem_into(self.i2c_address, 0x02, self._1_barray)\n self._1_barray[0] = (self._1_barray[0] & 0xCF) + minstrikes\n self.i2c.writeto_mem(self.i2c_address, 0x02, self._1_barray)\n\n #write_value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x02,1))) & 0xCF) + minstrikes\n #self.i2c.writeto_mem(self.i2c_address, 0x02, bytes(int_to_bytes(write_value,1)))\n\n def get_indoors(self):\n \"\"\"Determine whether or not the sensor is configured for indoor\n use or not.\n Returns True if configured to be indoors, otherwise False.\n \"\"\"\n self.i2c.readfrom_mem_into(self.i2c_address, 0x0, self._1_barray)\n if ((self._1_barray[0] & 0x20) == 0x20):\n #if int(ord(self.i2c.readfrom_mem(self.i2c_address,0x0,1))) & 0x20 == 0x20:\n return True\n else:\n return False\n\n def set_indoors(self, indoors):\n \"\"\"Set whether or not the sensor should use an indoor configuration.\n \"\"\"\n self.i2c.readfrom_mem_into(self.i2c_address, 0x0, self._1_barray)\n if indoors:\n self._1_barray[0] = (self._1_barray[0] & 0xC1) | 0x24\n #write_value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x0,1))) & 0xc1) | 0x24\n else:\n self._1_barray[0] = (self._1_barray[0] & 0xC1) | 0x1C\n #write_value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x0,1))) & 0xc1) | 0x1C\n self.i2c.writeto_mem(self.i2c_address, 0x0, self._1_barray)\n\n def set_mask_disturber(self, mask_dist):\n \"\"\"Set whether or not disturbers should be masked (no interrupts for\n what the sensor determines are man-made events)\n \"\"\"\n self.i2c.readfrom_mem_into(self.i2c_address, 0x3, self._1_barray)\n if mask_dist:\n self._1_barray[0] = (self._1_barray[0] | 0x20)\n #write_value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x3,1))) | 0x20)\n else:\n self._1_barray[0] = (self._1_barray[0] & 0xDF)\n #write_value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x3,1))) & 0xDF)\n self.i2c.writeto_mem(self.i2c_address, 0x03, self._1_barray)\n\n def get_mask_disturber(self):\n \"\"\"Get whether or not disturbers are masked or not.\n Returns True if interrupts are masked, false otherwise\n \"\"\"\n self.i2c.readfrom_mem_into(self.i2c_address, 0x3, self._1_barray)\n if ((self._1_barray[0] & 0x20) == 0x20):\n #if (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x3,1))) & 0x20) == 0x20:\n return True\n else:\n return False\n'''\n def set_disp_lco(self, display_lco):\n \"\"\"Have the internal LC oscillator signal displayed on the interrupt pin for\n measurement.\n\n Passing display_lco=True enables the output, False disables it.\n \"\"\"\n self.i2c.readfrom_mem_into(self.i2c_address, 0x08, self._1_barray)\n if display_lco:\n self._1_barray[0] = (self._1_barray[0] & 0x80)\n #write_value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x08,1))) | 0x80)\n #self.i2c.writeto_mem(self.i2c_address, 0x08, bytes(int_to_bytes(write_value,1)))\n else:\n self._1_barray[0] = (self._1_barray[0] & 0x7F)\n #write_value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x08,1))) & 0x7F)\n #self.i2c.writeto_mem(self.i2c_address, 0x08, bytes(int_to_bytes(write_value,1)))\n self.i2c.writeto_mem(self.i2c_address, 0x08, self._1_barray)\n sleep(0.002)\n\n def get_disp_lco(self):\n \"\"\"Determine whether or not the internal LC oscillator is displayed on the\n interrupt pin.\n\n Returns True if the LC oscillator is being displayed on the interrupt pin,\n False otherwise\n \"\"\"\n self.i2c.readfrom_mem_into(self.i2c_address, 0x08, self._1_barray)\n if ((self._1_barray[0] & 0x80) == 0x80):\n #if (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x08,1))) & 0x80) == 0x80:\n return True\n else:\n return False\n'''\n","sub_path":"MicroPython/esp8266/esp8266-AS3935/AS3935.py","file_name":"AS3935.py","file_ext":"py","file_size_in_byte":11597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"596477142","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport django.contrib.postgres.fields\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('feeds', '0002_auto_20150404_1501'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='feed',\n name='tags',\n ),\n migrations.AddField(\n model_name='feed',\n name='tags',\n field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=150), verbose_name='keywords', null=True, size=None, blank=True),\n ),\n migrations.RemoveField(\n model_name='subscription',\n name='tags',\n ),\n migrations.AddField(\n model_name='subscription',\n name='tags',\n field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=150), verbose_name='keywords', null=True, size=None, blank=True),\n ),\n migrations.DeleteModel(\n name='Tag',\n ),\n ]\n","sub_path":"feedpocket/feeds/migrations/0003_auto_20150408_0651.py","file_name":"0003_auto_20150408_0651.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"289497073","text":"\"\"\"\nSomewhat hacky solution to create conda lock files.\n\"\"\"\n\nimport datetime\nimport logging\nimport os\nimport pathlib\nimport posixpath\nimport re\nimport subprocess\nimport sys\nimport tempfile\n\nfrom contextlib import contextmanager\nfrom functools import partial\nfrom types import TracebackType\nfrom typing import (\n AbstractSet,\n Any,\n Dict,\n Iterator,\n List,\n Optional,\n Sequence,\n Set,\n Tuple,\n Type,\n Union,\n)\nfrom urllib.parse import urlsplit\n\nimport click\nimport pkg_resources\nimport yaml\n\nfrom ensureconda import ensureconda\nfrom typing_extensions import Literal\n\nfrom conda_lock.click_helpers import OrderedGroup\nfrom conda_lock.common import (\n read_file,\n read_json,\n relative_path,\n temporary_file_with_contents,\n write_file,\n)\nfrom conda_lock.conda_solver import solve_conda\nfrom conda_lock.errors import MissingEnvVarError, PlatformValidationError\nfrom conda_lock.invoke_conda import (\n PathLike,\n _invoke_conda,\n determine_conda_executable,\n is_micromamba,\n)\nfrom conda_lock.models.channel import Channel\n\n\ntry:\n from conda_lock.pypi_solver import solve_pypi\n\n PIP_SUPPORT = True\nexcept ImportError:\n PIP_SUPPORT = False\nfrom conda_lock.src_parser import (\n Dependency,\n LockedDependency,\n Lockfile,\n LockMeta,\n LockSpecification,\n UpdateSpecification,\n aggregate_lock_specs,\n)\nfrom conda_lock.src_parser.environment_yaml import parse_environment_file\nfrom conda_lock.src_parser.lockfile import parse_conda_lock_file, write_conda_lock_file\nfrom conda_lock.src_parser.meta_yaml import parse_meta_yaml_file\nfrom conda_lock.src_parser.pyproject_toml import parse_pyproject_toml\nfrom conda_lock.virtual_package import (\n FakeRepoData,\n default_virtual_package_repodata,\n virtual_package_repo_from_specification,\n)\n\n\nlogger = logging.getLogger(__name__)\nDEFAULT_FILES = [pathlib.Path(\"environment.yml\")]\n\n# Captures basic auth credentials, if they exists, in the second capture group.\nAUTH_PATTERN = re.compile(r\"^(https?:\\/\\/)(.*:.*@)?(.*)\")\n\n# Captures the domain in the second group.\nDOMAIN_PATTERN = re.compile(r\"^(https?:\\/\\/)?([^\\/]+)(.*)\")\n\n# Captures the platform in the first group.\nPLATFORM_PATTERN = re.compile(r\"^# platform: (.*)$\")\nINPUT_HASH_PATTERN = re.compile(r\"^# input_hash: (.*)$\")\n\n\nHAVE_MAMBA = (\n ensureconda(\n mamba=True, micromamba=False, conda=False, conda_exe=False, no_install=True\n )\n is not None\n)\n\n\nif not (sys.version_info.major >= 3 and sys.version_info.minor >= 6):\n print(\"conda_lock needs to run under python >=3.6\")\n sys.exit(1)\n\n\nDEFAULT_PLATFORMS = [\"osx-64\", \"linux-64\", \"win-64\"]\n\nKIND_EXPLICIT: Literal[\"explicit\"] = \"explicit\"\nKIND_LOCK: Literal[\"lock\"] = \"lock\"\nKIND_ENV: Literal[\"env\"] = \"env\"\nTKindAll = Union[Literal[\"explicit\"], Literal[\"lock\"], Literal[\"env\"]]\nTKindRendarable = Union[Literal[\"explicit\"], Literal[\"lock\"], Literal[\"env\"]]\n\n\nDEFAULT_KINDS: List[Union[Literal[\"explicit\"], Literal[\"lock\"]]] = [\n KIND_EXPLICIT,\n KIND_LOCK,\n]\nDEFAULT_LOCKFILE_NAME = \"conda-lock.yml\"\nKIND_FILE_EXT = {\n KIND_EXPLICIT: \"\",\n KIND_ENV: \".yml\",\n KIND_LOCK: \".\" + DEFAULT_LOCKFILE_NAME,\n}\nKIND_USE_TEXT = {\n KIND_EXPLICIT: \"conda create --name YOURENV --file {lockfile}\",\n KIND_ENV: \"conda env create --name YOURENV --file {lockfile}\",\n KIND_LOCK: \"conda-lock install --name YOURENV {lockfile}\",\n}\n\n\ndef _extract_platform(line: str) -> Optional[str]:\n search = PLATFORM_PATTERN.search(line)\n if search:\n return search.group(1)\n return None\n\n\ndef _extract_spec_hash(line: str) -> Optional[str]:\n search = INPUT_HASH_PATTERN.search(line)\n if search:\n return search.group(1)\n return None\n\n\ndef extract_platform(lockfile: str) -> str:\n for line in lockfile.strip().split(\"\\n\"):\n platform = _extract_platform(line)\n if platform:\n return platform\n raise RuntimeError(\"Cannot find platform in lockfile.\")\n\n\ndef extract_input_hash(lockfile_contents: str) -> Optional[str]:\n for line in lockfile_contents.strip().split(\"\\n\"):\n platform = _extract_spec_hash(line)\n if platform:\n return platform\n return None\n\n\ndef _do_validate_platform(platform: str) -> Tuple[bool, str]:\n from ensureconda.resolve import platform_subdir\n\n determined_subdir = platform_subdir()\n return platform == determined_subdir, determined_subdir\n\n\ndef do_validate_platform(lockfile: str) -> None:\n platform_lockfile = extract_platform(lockfile)\n try:\n success, platform_sys = _do_validate_platform(platform_lockfile)\n except KeyError:\n raise RuntimeError(f\"Unknown platform type in lockfile '{platform_lockfile}'.\")\n if not success:\n raise PlatformValidationError(\n f\"Platform in lockfile '{platform_lockfile}' is not compatible with system platform '{platform_sys}'.\"\n )\n\n\ndef do_conda_install(\n conda: PathLike, prefix: str, name: str, file: pathlib.Path\n) -> None:\n\n _conda = partial(_invoke_conda, conda, prefix, name, check_call=True)\n\n kind = \"env\" if file.name.endswith(\".yml\") else \"explicit\"\n\n if kind == \"explicit\":\n with open(file) as explicit_env:\n pip_requirements = [\n line.split(\"# pip \")[1]\n for line in explicit_env\n if line.startswith(\"# pip \")\n ]\n else:\n pip_requirements = []\n\n _conda(\n [\n *([\"env\"] if kind == \"env\" and not is_micromamba(conda) else []),\n \"create\",\n \"--file\",\n str(file),\n *([] if kind == \"env\" else [\"--yes\"]),\n ],\n )\n\n if not pip_requirements:\n return\n\n with temporary_file_with_contents(\"\\n\".join(pip_requirements)) as requirements_path:\n _conda([\"run\"], [\"pip\", \"install\", \"--no-deps\", \"-r\", str(requirements_path)])\n\n\ndef fn_to_dist_name(fn: str) -> str:\n if fn.endswith(\".conda\"):\n fn, _, _ = fn.partition(\".conda\")\n elif fn.endswith(\".tar.bz2\"):\n fn, _, _ = fn.partition(\".tar.bz2\")\n else:\n raise RuntimeError(f\"unexpected file type {fn}\", fn)\n return fn\n\n\ndef make_lock_spec(\n *,\n src_files: List[pathlib.Path],\n virtual_package_repo: FakeRepoData,\n channel_overrides: Optional[Sequence[str]] = None,\n platform_overrides: Optional[Sequence[str]] = None,\n required_categories: Optional[AbstractSet[str]] = None,\n) -> LockSpecification:\n \"\"\"Generate the lockfile specs from a set of input src_files. If required_categories is set filter out specs that do not match those\"\"\"\n lock_specs = parse_source_files(\n src_files=src_files, platform_overrides=platform_overrides or DEFAULT_PLATFORMS\n )\n\n lock_spec = aggregate_lock_specs(lock_specs)\n lock_spec.virtual_package_repo = virtual_package_repo\n lock_spec.channels = (\n [Channel.from_string(co) for co in channel_overrides]\n if channel_overrides\n else lock_spec.channels\n )\n lock_spec.platforms = (\n list(platform_overrides) if platform_overrides else lock_spec.platforms\n ) or list(DEFAULT_PLATFORMS)\n\n if required_categories is not None:\n\n def dep_has_category(d: Dependency, categories: AbstractSet[str]) -> bool:\n return d.category in categories\n\n lock_spec.dependencies = [\n d\n for d in lock_spec.dependencies\n if dep_has_category(d, categories=required_categories)\n ]\n\n return lock_spec\n\n\ndef make_lock_files(\n *,\n conda: PathLike,\n src_files: List[pathlib.Path],\n kinds: Sequence[TKindAll],\n lockfile_path: pathlib.Path = pathlib.Path(DEFAULT_LOCKFILE_NAME),\n platform_overrides: Optional[Sequence[str]] = None,\n channel_overrides: Optional[Sequence[str]] = None,\n virtual_package_spec: Optional[pathlib.Path] = None,\n update: Optional[List[str]] = None,\n include_dev_dependencies: bool = True,\n filename_template: Optional[str] = None,\n filter_categories: bool = True,\n extras: Optional[AbstractSet[str]] = None,\n check_input_hash: bool = False,\n) -> None:\n \"\"\"\n Generate a lock file from the src files provided\n\n Parameters\n ----------\n conda :\n Path to conda, mamba, or micromamba\n src_files :\n Files to parse requirements from\n kinds :\n Lockfile formats to output\n lockfile_path :\n Path to a conda-lock.yml to create or update\n platform_overrides :\n Platforms to solve for. Takes precedence over platforms found in src_files.\n channel_overrides :\n Channels to use. Takes precedence over channels found in src_files.\n virtual_package_spec :\n Path to a virtual package repository that defines each platform.\n update :\n Names of dependencies to update to their latest versions, regardless\n of whether the constraint in src_files has changed.\n include_dev_dependencies :\n Include development dependencies in explicit or env output\n filename_template :\n Format for names of rendered explicit or env files. Must include {platform}.\n extras :\n Include the given extras in explicit or env output\n filter_categories :\n Filter out unused categories prior to solving\n check_input_hash :\n Do not re-solve for each target platform for which specifications are unchanged\n \"\"\"\n\n # initialize virtual package fake\n if virtual_package_spec and virtual_package_spec.exists():\n virtual_package_repo = virtual_package_repo_from_specification(\n virtual_package_spec\n )\n else:\n virtual_package_repo = default_virtual_package_repodata()\n\n required_categories = {\"main\"}\n if include_dev_dependencies:\n required_categories.add(\"dev\")\n if extras is not None:\n required_categories.update(extras)\n\n with virtual_package_repo:\n lock_spec = make_lock_spec(\n src_files=src_files,\n channel_overrides=channel_overrides,\n platform_overrides=platform_overrides,\n virtual_package_repo=virtual_package_repo,\n required_categories=required_categories if filter_categories else None,\n )\n lock_content: Optional[Lockfile] = None\n\n platforms_to_lock: List[str] = []\n platforms_already_locked: List[str] = []\n if lockfile_path.exists():\n import yaml\n\n try:\n lock_content = parse_conda_lock_file(lockfile_path)\n except (yaml.error.YAMLError, FileNotFoundError):\n logger.warning(\n \"Failed to parse existing lock. Regenerating from scratch\"\n )\n lock_content = None\n else:\n lock_content = None\n\n if lock_content is not None:\n platforms_already_locked = list(lock_content.metadata.platforms)\n update_spec = UpdateSpecification(\n locked=lock_content.package, update=update\n )\n for platform in lock_spec.platforms:\n if (\n update\n or platform not in lock_content.metadata.platforms\n or not check_input_hash\n or lock_spec.content_hash_for_platform(platform)\n != lock_content.metadata.content_hash[platform]\n ):\n platforms_to_lock.append(platform)\n if platform in platforms_already_locked:\n platforms_already_locked.remove(platform)\n else:\n platforms_to_lock = lock_spec.platforms\n update_spec = UpdateSpecification()\n\n if platforms_already_locked:\n print(\n f\"Spec hash already locked for {sorted(platforms_already_locked)}. Skipping solve.\",\n file=sys.stderr,\n )\n platforms_to_lock = sorted(set(platforms_to_lock))\n\n if platforms_to_lock:\n print(f\"Locking dependencies for {platforms_to_lock}...\", file=sys.stderr)\n lock_content = lock_content | create_lockfile_from_spec(\n conda=conda,\n spec=lock_spec,\n platforms=platforms_to_lock,\n lockfile_path=lockfile_path,\n update_spec=update_spec,\n )\n\n if \"lock\" in kinds:\n write_conda_lock_file(lock_content, lockfile_path)\n print(\n \" - Install lock using:\",\n KIND_USE_TEXT[\"lock\"].format(lockfile=str(lockfile_path)),\n file=sys.stderr,\n )\n\n assert lock_content is not None\n\n do_render(\n lock_content,\n kinds=[k for k in kinds if k != \"lock\"],\n include_dev_dependencies=include_dev_dependencies,\n filename_template=filename_template,\n extras=extras,\n check_input_hash=check_input_hash,\n )\n\n\ndef do_render(\n lockfile: Lockfile,\n kinds: Sequence[Union[Literal[\"env\"], Literal[\"explicit\"]]],\n include_dev_dependencies: bool = True,\n filename_template: Optional[str] = None,\n extras: Optional[AbstractSet[str]] = None,\n check_input_hash: bool = False,\n override_platform: Optional[Sequence[str]] = None,\n) -> None:\n \"\"\"Render the lock content for each platform in lockfile\n\n Parameters\n ----------\n lockfile :\n Lock content\n kinds :\n Lockfile formats to render\n include_dev_dependencies :\n Include development dependencies in output\n filename_template :\n Format for the lock file names. Must include {platform}.\n extras :\n Include the given extras in output\n check_input_hash :\n Do not re-render if specifications are unchanged\n override_platform :\n Generate only this subset of the platform files\n \"\"\"\n platforms = lockfile.metadata.platforms\n if override_platform is not None and len(override_platform) > 0:\n platforms = list(sorted(set(platforms) & set(override_platform)))\n\n if filename_template:\n if \"{platform}\" not in filename_template and len(platforms) > 1:\n print(\n \"{platform} must be in filename template when locking\"\n f\" more than one platform: {', '.join(platforms)}\",\n file=sys.stderr,\n )\n sys.exit(1)\n for kind, file_ext in KIND_FILE_EXT.items():\n if file_ext and filename_template.endswith(file_ext):\n print(\n f\"Filename template must not end with '{file_ext}', as this \"\n f\"is reserved for '{kind}' lock files, in which case it is \"\n f\"automatically added.\"\n )\n sys.exit(1)\n\n for plat in platforms:\n for kind in kinds:\n if filename_template:\n context = {\n \"platform\": plat,\n \"dev-dependencies\": str(include_dev_dependencies).lower(),\n \"input-hash\": lockfile.metadata.content_hash,\n \"version\": pkg_resources.get_distribution(\"conda_lock\").version,\n \"timestamp\": datetime.datetime.utcnow().strftime(\"%Y%m%dT%H%M%SZ\"),\n }\n\n filename = filename_template.format(**context)\n else:\n filename = f\"conda-{plat}.lock\"\n\n if pathlib.Path(filename).exists() and check_input_hash:\n with open(filename) as f:\n previous_hash = extract_input_hash(f.read())\n if previous_hash == lockfile.metadata.content_hash.get(plat):\n print(\n f\"Lock content already rendered for {plat}. Skipping render of {filename}.\",\n file=sys.stderr,\n )\n continue\n\n print(f\"Rendering lockfile(s) for {plat}...\", file=sys.stderr)\n lockfile_contents = render_lockfile_for_platform(\n lockfile=lockfile,\n include_dev_dependencies=include_dev_dependencies,\n extras=extras,\n kind=kind,\n platform=plat,\n )\n\n filename += KIND_FILE_EXT[kind]\n with open(filename, \"w\") as fo:\n fo.write(\"\\n\".join(lockfile_contents) + \"\\n\")\n\n print(\n f\" - Install lock using {'(see warning below)' if kind == 'env' else ''}:\",\n KIND_USE_TEXT[kind].format(lockfile=filename),\n file=sys.stderr,\n )\n\n if \"env\" in kinds:\n print(\n \"\\nWARNING: Using environment lock files (*.yml) does NOT guarantee \"\n \"that generated environments will be identical over time, since the \"\n \"dependency resolver is re-run every time and changes in repository \"\n \"metadata or resolver logic may cause variation. Conversely, since \"\n \"the resolver is run every time, the resulting packages ARE \"\n \"guaranteed to be seen by conda as being in a consistent state. This \"\n \"makes them useful when updating existing environments.\",\n file=sys.stderr,\n )\n\n\ndef render_lockfile_for_platform( # noqa: C901\n *,\n lockfile: Lockfile,\n include_dev_dependencies: bool,\n extras: Optional[AbstractSet[str]],\n kind: Union[Literal[\"env\"], Literal[\"explicit\"]],\n platform: str,\n) -> List[str]:\n \"\"\"\n Render lock content into a single-platform lockfile that can be installed\n with conda.\n\n Parameters\n ----------\n lockfile :\n Locked package versions\n include_dev_dependencies :\n Include development dependencies in output\n extras :\n Optional dependency groups to include in output\n kind :\n Lockfile format (explicit or env)\n platform :\n Target platform\n\n \"\"\"\n lockfile_contents = [\n \"# Generated by conda-lock.\",\n f\"# platform: {platform}\",\n f\"# input_hash: {lockfile.metadata.content_hash.get(platform)}\\n\",\n ]\n\n categories = {\n \"main\",\n *(extras or []),\n *([\"dev\"] if include_dev_dependencies else []),\n }\n\n conda_deps: List[LockedDependency] = []\n pip_deps: List[LockedDependency] = []\n\n # ensure consistent ordering of generated file\n lockfile.toposort_inplace()\n\n for p in lockfile.package:\n if p.platform == platform and ((not p.optional) or (p.category in categories)):\n if p.manager == \"pip\":\n pip_deps.append(p)\n elif p.manager == \"conda\":\n # exclude virtual packages\n if not p.name.startswith(\"__\"):\n conda_deps.append(p)\n\n def format_pip_requirement(\n spec: LockedDependency, platform: str, direct: bool = False\n ) -> str:\n if spec.source and spec.source.type == \"url\":\n return f\"{spec.name} @ {spec.source.url}\"\n elif direct:\n s = f\"{spec.name} @ {spec.url}\"\n if spec.hash.sha256:\n s += f\"#sha256={spec.hash.sha256}\"\n return s\n else:\n s = f\"{spec.name} === {spec.version}\"\n if spec.hash.sha256:\n s += f\" --hash=sha256:{spec.hash.sha256}\"\n return s\n\n def format_conda_requirement(\n spec: LockedDependency, platform: str, direct: bool = False\n ) -> str:\n if direct:\n # inject the environment variables in here\n return posixpath.expandvars(f\"{spec.url}#{spec.hash.md5}\")\n else:\n path = pathlib.Path(urlsplit(spec.url).path)\n while path.suffix in {\".tar\", \".bz2\", \".gz\", \".conda\"}:\n path = path.with_suffix(\"\")\n build_string = path.name.split(\"-\")[-1]\n return f\"{spec.name}={spec.version}={build_string}\"\n\n if kind == \"env\":\n lockfile_contents.extend(\n [\n \"channels:\",\n *(\n f\" - {channel.env_replaced_url()}\"\n for channel in lockfile.metadata.channels\n ),\n \"dependencies:\",\n *(\n f\" - {format_conda_requirement(dep, platform, direct=False)}\"\n for dep in conda_deps\n ),\n ]\n )\n lockfile_contents.extend(\n [\n \" - pip:\",\n *(\n f\" - {format_pip_requirement(dep, platform, direct=False)}\"\n for dep in pip_deps\n ),\n ]\n if pip_deps\n else []\n )\n elif kind == \"explicit\":\n lockfile_contents.append(\"@EXPLICIT\\n\")\n\n lockfile_contents.extend(\n [format_conda_requirement(dep, platform, direct=True) for dep in conda_deps]\n )\n\n def sanitize_lockfile_line(line: str) -> str:\n line = line.strip()\n if line == \"\":\n return \"#\"\n else:\n return line\n\n lockfile_contents = [sanitize_lockfile_line(line) for line in lockfile_contents]\n\n # emit an explicit requirements.txt, prefixed with '# pip '\n lockfile_contents.extend(\n [\n f\"# pip {format_pip_requirement(dep, platform, direct=True)}\"\n for dep in pip_deps\n ]\n )\n else:\n raise ValueError(f\"Unrecognised lock kind {kind}.\")\n\n logging.debug(\"lockfile_contents:\\n%s\\n\", lockfile_contents)\n return lockfile_contents\n\n\ndef _solve_for_arch(\n conda: PathLike,\n spec: LockSpecification,\n platform: str,\n channels: List[Channel],\n update_spec: Optional[UpdateSpecification] = None,\n) -> List[LockedDependency]:\n \"\"\"\n Solve specification for a single platform\n \"\"\"\n if update_spec is None:\n update_spec = UpdateSpecification()\n # filter requested and locked dependencies to the current platform\n dependencies = [\n dep\n for dep in spec.dependencies\n if (not dep.selectors.platform) or platform in dep.selectors.platform\n ]\n locked = [dep for dep in update_spec.locked if dep.platform == platform]\n requested_deps_by_name = {\n manager: {dep.name: dep for dep in dependencies if dep.manager == manager}\n for manager in (\"conda\", \"pip\")\n }\n locked_deps_by_name = {\n manager: {dep.name: dep for dep in locked if dep.manager == manager}\n for manager in (\"conda\", \"pip\")\n }\n\n conda_deps = solve_conda(\n conda,\n specs=requested_deps_by_name[\"conda\"],\n locked=locked_deps_by_name[\"conda\"],\n update=update_spec.update,\n platform=platform,\n channels=channels,\n )\n\n if requested_deps_by_name[\"pip\"]:\n if not PIP_SUPPORT:\n raise ValueError(\"pip support is not enabled\")\n if \"python\" not in conda_deps:\n raise ValueError(\"Got pip specs without Python\")\n pip_deps = solve_pypi(\n requested_deps_by_name[\"pip\"],\n use_latest=update_spec.update,\n pip_locked={\n dep.name: dep for dep in update_spec.locked if dep.manager == \"pip\"\n },\n conda_locked={dep.name: dep for dep in conda_deps.values()},\n python_version=conda_deps[\"python\"].version,\n platform=platform,\n )\n else:\n pip_deps = {}\n\n return list(conda_deps.values()) + list(pip_deps.values())\n\n\ndef create_lockfile_from_spec(\n *,\n conda: PathLike,\n spec: LockSpecification,\n platforms: List[str] = [],\n lockfile_path: pathlib.Path,\n update_spec: Optional[UpdateSpecification] = None,\n) -> Lockfile:\n \"\"\"\n Solve or update specification\n \"\"\"\n assert spec.virtual_package_repo is not None\n virtual_package_channel = spec.virtual_package_repo.channel\n\n locked: Dict[Tuple[str, str, str], LockedDependency] = {}\n\n for platform in platforms or spec.platforms:\n\n deps = _solve_for_arch(\n conda=conda,\n spec=spec,\n platform=platform,\n channels=[*spec.channels, virtual_package_channel],\n update_spec=update_spec,\n )\n\n for dep in deps:\n locked[(dep.manager, dep.name, dep.platform)] = dep\n\n return Lockfile(\n package=[locked[k] for k in locked],\n metadata=LockMeta(\n content_hash=spec.content_hash(),\n channels=[c for c in spec.channels],\n platforms=spec.platforms,\n sources=[str(source.resolve()) for source in spec.sources],\n ),\n )\n\n\ndef parse_source_files(\n src_files: List[pathlib.Path],\n platform_overrides: Sequence[str],\n) -> List[LockSpecification]:\n \"\"\"\n Parse a sequence of dependency specifications from source files\n\n Parameters\n ----------\n src_files :\n Files to parse for dependencies\n platform_overrides :\n Target platforms to render meta.yaml files for\n \"\"\"\n desired_envs: List[LockSpecification] = []\n for src_file in src_files:\n if src_file.name == \"meta.yaml\":\n desired_envs.append(\n parse_meta_yaml_file(src_file, list(platform_overrides))\n )\n elif src_file.name == \"pyproject.toml\":\n desired_envs.append(parse_pyproject_toml(src_file))\n else:\n desired_envs.append(\n parse_environment_file(src_file, pip_support=PIP_SUPPORT)\n )\n return desired_envs\n\n\ndef _add_auth_to_line(line: str, auth: Dict[str, str]) -> str:\n matching_auths = [a for a in auth if a in line]\n if not matching_auths:\n return line\n # If we have multiple matching auths, we choose the longest one.\n matching_auth = max(matching_auths, key=len)\n replacement = f\"{auth[matching_auth]}@{matching_auth}\"\n return line.replace(matching_auth, replacement)\n\n\ndef _add_auth_to_lockfile(lockfile: str, auth: Dict[str, str]) -> str:\n lockfile_with_auth = \"\\n\".join(\n _add_auth_to_line(line, auth) if line[0] not in (\"#\", \"@\") else line\n for line in lockfile.strip().split(\"\\n\")\n )\n if lockfile.endswith(\"\\n\"):\n return lockfile_with_auth + \"\\n\"\n return lockfile_with_auth\n\n\n@contextmanager\ndef _add_auth(lockfile: str, auth: Dict[str, str]) -> Iterator[pathlib.Path]:\n lockfile_with_auth = _add_auth_to_lockfile(lockfile, auth)\n with temporary_file_with_contents(lockfile_with_auth) as path:\n yield path\n\n\ndef _strip_auth_from_line(line: str) -> str:\n return AUTH_PATTERN.sub(r\"\\1\\3\", line)\n\n\ndef _extract_domain(line: str) -> str:\n return DOMAIN_PATTERN.sub(r\"\\2\", line)\n\n\ndef _strip_auth_from_lockfile(lockfile: str) -> str:\n lockfile_lines = lockfile.strip().split(\"\\n\")\n stripped_lockfile_lines = tuple(\n _strip_auth_from_line(line) if line[0] not in (\"#\", \"@\") else line\n for line in lockfile_lines\n )\n stripped_domains = sorted(\n {\n _extract_domain(stripped_line)\n for line, stripped_line in zip(lockfile_lines, stripped_lockfile_lines)\n if line != stripped_line\n }\n )\n stripped_lockfile = \"\\n\".join(stripped_lockfile_lines)\n if lockfile.endswith(\"\\n\"):\n stripped_lockfile += \"\\n\"\n if stripped_domains:\n stripped_domains_doc = \"\\n\".join(f\"# - {domain}\" for domain in stripped_domains)\n return f\"# The following domains require authentication:\\n{stripped_domains_doc}\\n{stripped_lockfile}\"\n return stripped_lockfile\n\n\n@contextmanager\ndef _render_lockfile_for_install(\n filename: pathlib.Path,\n include_dev_dependencies: bool = True,\n extras: Optional[AbstractSet[str]] = None,\n) -> Iterator[pathlib.Path]:\n \"\"\"\n Render lock content into a temporary, explicit lockfile for the current platform\n\n Parameters\n ----------\n filename :\n Path to conda-lock.yml\n include_dev_dependencies :\n Include development dependencies in output\n extras :\n Optional dependency groups to include in output\n\n \"\"\"\n\n if not filename.name.endswith(DEFAULT_LOCKFILE_NAME):\n yield filename\n return\n\n from ensureconda.resolve import platform_subdir\n\n lock_content = parse_conda_lock_file(pathlib.Path(filename))\n\n platform = platform_subdir()\n if platform not in lock_content.metadata.platforms:\n raise PlatformValidationError(\n f\"Dependencies are not locked for the current platform ({platform})\"\n )\n\n # TODO: Move to LockFile\n required_env_vars: Set[str] = set()\n for channel in lock_content.metadata.channels:\n required_env_vars.update(channel.used_env_vars)\n existing_env_vars = {k for k, v in os.environ.items() if v}\n missing_env_vars = required_env_vars - existing_env_vars\n if missing_env_vars:\n msg = \", \".join(sorted(missing_env_vars))\n raise MissingEnvVarError(\n f\"Cannot run render lockfile. Missing environment variables: {msg}\"\n )\n\n content = render_lockfile_for_platform(\n lockfile=lock_content,\n kind=\"explicit\",\n platform=platform,\n include_dev_dependencies=include_dev_dependencies,\n extras=extras,\n )\n with temporary_file_with_contents(\"\\n\".join(content) + \"\\n\") as path:\n yield path\n\n\ndef run_lock(\n environment_files: List[pathlib.Path],\n *,\n conda_exe: Optional[str],\n platforms: Optional[List[str]] = None,\n mamba: bool = False,\n micromamba: bool = False,\n include_dev_dependencies: bool = True,\n channel_overrides: Optional[Sequence[str]] = None,\n filename_template: Optional[str] = None,\n kinds: Optional[Sequence[TKindAll]] = None,\n lockfile_path: pathlib.Path = pathlib.Path(DEFAULT_LOCKFILE_NAME),\n check_input_hash: bool = False,\n extras: Optional[AbstractSet[str]] = None,\n virtual_package_spec: Optional[pathlib.Path] = None,\n update: Optional[List[str]] = None,\n filter_categories: bool = False,\n) -> None:\n if environment_files == DEFAULT_FILES:\n if lockfile_path.exists():\n lock_content = parse_conda_lock_file(lockfile_path)\n # reconstruct native paths\n locked_environment_files = [\n pathlib.Path(\n pathlib.PurePosixPath(lockfile_path).parent\n / pathlib.PurePosixPath(p)\n )\n for p in lock_content.metadata.sources\n ]\n if all(p.exists() for p in locked_environment_files):\n environment_files = locked_environment_files\n else:\n missing = [p for p in locked_environment_files if not p.exists()]\n print(\n f\"{lockfile_path} was created from {[str(p) for p in locked_environment_files]},\"\n f\" but some files ({[str(p) for p in missing]}) do not exist. Falling back to\"\n f\" {[str(p) for p in environment_files]}.\",\n file=sys.stderr,\n )\n else:\n long_ext_file = pathlib.Path(\"environment.yaml\")\n if long_ext_file.exists() and not environment_files[0].exists():\n environment_files = [long_ext_file]\n\n _conda_exe = determine_conda_executable(\n conda_exe, mamba=mamba, micromamba=micromamba\n )\n make_lock_files(\n conda=_conda_exe,\n src_files=environment_files,\n platform_overrides=platforms,\n channel_overrides=channel_overrides,\n virtual_package_spec=virtual_package_spec,\n update=update,\n kinds=kinds or DEFAULT_KINDS,\n lockfile_path=lockfile_path,\n filename_template=filename_template,\n include_dev_dependencies=include_dev_dependencies,\n extras=extras,\n check_input_hash=check_input_hash,\n filter_categories=filter_categories,\n )\n\n\n@click.group(cls=OrderedGroup, default=\"lock\", default_if_no_args=True)\ndef main() -> None:\n \"\"\"To get help for subcommands, use the conda-lock --help\"\"\"\n pass\n\n\nTLogLevel = Union[\n Literal[\"DEBUG\"],\n Literal[\"INFO\"],\n Literal[\"WARNING\"],\n Literal[\"ERROR\"],\n Literal[\"CRITICAL\"],\n]\n\n\n@main.command(\"lock\")\n@click.option(\n \"--conda\", default=None, help=\"path (or name) of the conda/mamba executable to use.\"\n)\n@click.option(\n \"--mamba/--no-mamba\",\n default=HAVE_MAMBA,\n help=\"don't attempt to use or install mamba.\",\n)\n@click.option(\n \"--micromamba/--no-micromamba\",\n default=False,\n help=\"don't attempt to use or install micromamba.\",\n)\n@click.option(\n \"-p\",\n \"--platform\",\n multiple=True,\n help=\"generate lock files for the following platforms\",\n)\n@click.option(\n \"-c\",\n \"--channel\",\n \"channel_overrides\",\n multiple=True,\n help=\"\"\"Override the channels to use when solving the environment. These will replace the channels as listed in the various source files.\"\"\",\n)\n@click.option(\n \"--dev-dependencies/--no-dev-dependencies\",\n is_flag=True,\n default=True,\n help=\"include dev dependencies in the lockfile (where applicable)\",\n)\n@click.option(\n \"-f\",\n \"--file\",\n \"files\",\n default=DEFAULT_FILES,\n type=click.Path(),\n multiple=True,\n help=\"path to a conda environment specification(s)\",\n)\n@click.option(\n \"-k\",\n \"--kind\",\n default=[\"lock\"],\n type=str,\n multiple=True,\n help=\"Kind of lock file(s) to generate [should be one of 'lock', 'explicit', or 'env'].\",\n)\n@click.option(\n \"--filename-template\",\n default=\"conda-{platform}.lock\",\n help=\"Template for single-platform (explicit, env) lock file names. Filename must include {platform} token, and must not end in '.yml'. For a full list and description of available tokens, see the command help text.\",\n)\n@click.option(\n \"--lockfile\",\n default=DEFAULT_LOCKFILE_NAME,\n help=\"Path to a conda-lock.yml to create or update\",\n)\n@click.option(\n \"--strip-auth\",\n is_flag=True,\n default=False,\n help=\"Strip the basic auth credentials from the lockfile.\",\n)\n@click.option(\n \"-e\",\n \"--extras\",\n \"--category\",\n default=[],\n type=str,\n multiple=True,\n help=\"When used in conjunction with input sources that support extras/categories (pyproject.toml) will add the deps from those extras to the render specification\",\n)\n@click.option(\n \"--filter-categories\",\n \"--filter-extras\",\n is_flag=True,\n default=False,\n help=\"In conjunction with extras this will prune out dependencies that do not have the extras specified when loading files.\",\n)\n@click.option(\n \"--check-input-hash\",\n is_flag=True,\n default=False,\n help=\"Check existing input hashes in lockfiles before regenerating lock files. If no files were updated exit with exit code 4. Incompatible with --strip-auth\",\n)\n@click.option(\n \"--log-level\",\n help=\"Log level.\",\n default=\"INFO\",\n type=click.Choice([\"DEBUG\", \"INFO\", \"WARNING\", \"ERROR\", \"CRITICAL\"]),\n)\n@click.option(\n \"--pdb\", is_flag=True, help=\"Drop into a postmortem debugger if conda-lock crashes\"\n)\n@click.option(\n \"--virtual-package-spec\",\n type=click.Path(),\n help=\"Specify a set of virtual packages to use.\",\n)\n@click.option(\n \"--update\",\n multiple=True,\n help=\"Packages to update to their latest versions. If empty, update all.\",\n)\n@click.pass_context\ndef lock(\n ctx: click.Context,\n conda: Optional[PathLike],\n mamba: bool,\n micromamba: bool,\n platform: List[str],\n channel_overrides: List[str],\n dev_dependencies: bool,\n files: List[pathlib.Path],\n kind: List[Union[Literal[\"lock\"], Literal[\"env\"], Literal[\"explicit\"]]],\n filename_template: str,\n lockfile: PathLike,\n strip_auth: bool,\n extras: List[str],\n filter_categories: bool,\n check_input_hash: bool,\n log_level: TLogLevel,\n pdb: bool,\n virtual_package_spec: Optional[PathLike],\n update: Optional[List[str]] = None,\n) -> None:\n \"\"\"Generate fully reproducible lock files for conda environments.\n\n By default, the lock files are written to conda-{platform}.lock. These filenames can be customized using the\n --filename-template argument. The following tokens are available:\n\n \\b\n platform: The platform this lock file was generated for (conda subdir).\n dev-dependencies: Whether or not dev dependencies are included in this lock file.\n input-hash: A sha256 hash of the lock file input specification.\n version: The version of conda-lock used to generate this lock file.\n timestamp: The approximate timestamp of the output file in ISO8601 basic format.\n \"\"\"\n logging.basicConfig(level=log_level)\n\n # bail out if we do not encounter the default file if no files were passed\n if ctx.get_parameter_source(\"files\") == click.core.ParameterSource.DEFAULT:\n candidates = list(files)\n candidates += [f.with_name(f.name.replace(\".yml\", \".yaml\")) for f in candidates]\n for f in candidates:\n if f.exists():\n break\n else:\n print(ctx.get_help())\n sys.exit(1)\n\n if pdb:\n sys.excepthook = _handle_exception_post_mortem\n\n if not virtual_package_spec:\n candidates = [\n pathlib.Path(\"virtual-packages.yml\"),\n pathlib.Path(\"virtual-packages.yaml\"),\n ]\n for c in candidates:\n if c.exists():\n logger.info(\"Using virtual packages from %s\", c)\n virtual_package_spec = c\n break\n else:\n virtual_package_spec = pathlib.Path(virtual_package_spec)\n\n files = [pathlib.Path(file) for file in files]\n extras_ = set(extras)\n lock_func = partial(\n run_lock,\n environment_files=files,\n conda_exe=conda,\n platforms=platform,\n mamba=mamba,\n micromamba=micromamba,\n include_dev_dependencies=dev_dependencies,\n channel_overrides=channel_overrides,\n kinds=kind,\n lockfile_path=pathlib.Path(lockfile),\n extras=extras_,\n virtual_package_spec=virtual_package_spec,\n update=update,\n filter_categories=filter_categories,\n )\n if strip_auth:\n with tempfile.TemporaryDirectory() as tempdir:\n filename_template_temp = f\"{tempdir}/{filename_template.split('/')[-1]}\"\n lock_func(filename_template=filename_template_temp)\n filename_template_dir = \"/\".join(filename_template.split(\"/\")[:-1])\n for file in os.listdir(tempdir):\n lockfile = read_file(os.path.join(tempdir, file))\n lockfile = _strip_auth_from_lockfile(lockfile)\n write_file(lockfile, os.path.join(filename_template_dir, file))\n else:\n lock_func(\n filename_template=filename_template, check_input_hash=check_input_hash\n )\n\n\n@main.command(\"install\")\n@click.option(\n \"--conda\", default=None, help=\"path (or name) of the conda/mamba executable to use.\"\n)\n@click.option(\n \"--mamba/--no-mamba\",\n default=HAVE_MAMBA,\n help=\"don't attempt to use or install mamba.\",\n)\n@click.option(\n \"--micromamba/--no-micromamba\",\n default=False,\n help=\"don't attempt to use or install micromamba.\",\n)\n@click.option(\"-p\", \"--prefix\", help=\"Full path to environment location (i.e. prefix).\")\n@click.option(\"-n\", \"--name\", help=\"Name of environment.\")\n@click.option(\n \"--auth\",\n help=\"The auth file provided as string. Has precedence over `--auth-file`.\",\n default=\"\",\n)\n@click.option(\"--auth-file\", help=\"Path to the authentication file.\", default=\"\")\n@click.option(\n \"--validate-platform/--no-validate-platform\",\n default=True,\n help=\"Whether the platform compatibility between your lockfile and the host system should be validated.\",\n)\n@click.option(\n \"--log-level\",\n help=\"Log level.\",\n default=\"INFO\",\n type=click.Choice([\"DEBUG\", \"INFO\", \"WARNING\", \"ERROR\", \"CRITICAL\"]),\n)\n@click.option(\n \"--dev/--no-dev\",\n is_flag=True,\n default=True,\n help=\"install dev dependencies from the lockfile (where applicable)\",\n)\n@click.option(\n \"-E\",\n \"--extras\",\n multiple=True,\n default=[],\n help=\"include extra dependencies from the lockfile (where applicable)\",\n)\n@click.argument(\n \"lock-file\", default=pathlib.Path(DEFAULT_LOCKFILE_NAME), type=click.Path()\n)\n@click.pass_context\ndef install(\n ctx: click.Context,\n conda: Optional[str],\n mamba: bool,\n micromamba: bool,\n prefix: Optional[str],\n name: Optional[str],\n lock_file: pathlib.Path,\n auth: Optional[str],\n auth_file: Optional[PathLike],\n validate_platform: bool,\n log_level: TLogLevel,\n dev: bool,\n extras: List[str],\n) -> None:\n # bail out if we do not encounter the lockfile\n lock_file = pathlib.Path(lock_file)\n if not lock_file.exists():\n print(ctx.get_help())\n sys.exit(1)\n\n \"\"\"Perform a conda install\"\"\"\n logging.basicConfig(level=log_level)\n _auth = (\n yaml.safe_load(auth) if auth else read_json(auth_file) if auth_file else None\n )\n _conda_exe = determine_conda_executable(conda, mamba=mamba, micromamba=micromamba)\n install_func = partial(do_conda_install, conda=_conda_exe, prefix=prefix, name=name)\n if validate_platform and not lock_file.name.endswith(DEFAULT_LOCKFILE_NAME):\n lockfile_contents = read_file(lock_file)\n try:\n do_validate_platform(lockfile_contents)\n except PlatformValidationError as error:\n raise PlatformValidationError(\n error.args[0] + \" Disable validation with `--no-validate-platform`.\"\n )\n with _render_lockfile_for_install(\n lock_file, include_dev_dependencies=dev, extras=set(extras)\n ) as lockfile:\n if auth:\n with _add_auth(read_file(lockfile), _auth) as lockfile_with_auth:\n install_func(file=lockfile_with_auth)\n else:\n install_func(file=lockfile)\n\n\n@main.command(\"render\")\n@click.option(\n \"--dev-dependencies/--no-dev-dependencies\",\n is_flag=True,\n default=True,\n help=\"include dev dependencies in the lockfile (where applicable)\",\n)\n@click.option(\n \"-k\",\n \"--kind\",\n default=[\"explicit\"],\n type=click.Choice([\"explicit\", \"env\"]),\n multiple=True,\n help=\"Kind of lock file(s) to generate.\",\n)\n@click.option(\n \"--filename-template\",\n default=\"conda-{platform}.lock\",\n help=\"Template for the lock file names. Filename must include {platform} token, and must not end in '.yml'. For a full list and description of available tokens, see the command help text.\",\n)\n@click.option(\n \"-e\",\n \"--extras\",\n default=[],\n type=str,\n multiple=True,\n help=\"When used in conjunction with input sources that support extras (pyproject.toml) will add the deps from those extras to the input specification\",\n)\n@click.option(\n \"--log-level\",\n help=\"Log level.\",\n default=\"INFO\",\n type=click.Choice([\"DEBUG\", \"INFO\", \"WARNING\", \"ERROR\", \"CRITICAL\"]),\n)\n@click.option(\n \"--pdb\", is_flag=True, help=\"Drop into a postmortem debugger if conda-lock crashes\"\n)\n@click.option(\n \"-p\",\n \"--platform\",\n multiple=True,\n help=\"render lock files for the following platforms\",\n)\n@click.argument(\"lock-file\", default=DEFAULT_LOCKFILE_NAME)\n@click.pass_context\ndef render(\n ctx: click.Context,\n dev_dependencies: bool,\n kind: Sequence[Union[Literal[\"env\"], Literal[\"explicit\"]]],\n filename_template: str,\n extras: List[str],\n log_level: TLogLevel,\n lock_file: PathLike,\n pdb: bool,\n platform: Sequence[str],\n) -> None:\n \"\"\"Render multi-platform lockfile into single-platform env or explicit file\"\"\"\n logging.basicConfig(level=log_level)\n\n if pdb:\n sys.excepthook = _handle_exception_post_mortem\n\n # bail out if we do not encounter the lockfile\n lock_file = pathlib.Path(lock_file)\n if not lock_file.exists():\n print(ctx.get_help())\n sys.exit(1)\n\n lock_content = parse_conda_lock_file(lock_file)\n\n do_render(\n lock_content,\n filename_template=filename_template,\n kinds=kind,\n include_dev_dependencies=dev_dependencies,\n extras=set(extras),\n override_platform=platform,\n )\n\n\ndef _handle_exception_post_mortem(\n exc_type: Type[BaseException],\n exc_value: BaseException,\n exc_traceback: Optional[TracebackType],\n) -> Any:\n import pdb\n\n pdb.post_mortem(exc_traceback)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"conda_lock/conda_lock.py","file_name":"conda_lock.py","file_ext":"py","file_size_in_byte":44368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"265473155","text":"import networkx as nx\nimport matplotlib.pyplot as pb\n\nclass Move:\n\n def __init__(self):\n self.end_search = False\n self.visited = []\n\n def greedy(self, graph, start, destination):\n queue = []\n queue.append(start)\n self.visited.append(start)\n print(f'Starting point -> {start}')\n\n while len(queue) > 0 and not self.end_search:\n min_stld = 99999\n min_child = {}\n\n current_node = queue.pop(0)\n\n for child in list(graph.adj[current_node]):\n if child is destination:\n print(f'Destination -> {child}')\n self.end_search = True\n self.visited.append(child)\n break\n else:\n if hlsd_mapping[child] < min_stld:\n min_stld = hlsd_mapping[child]\n min_child = child\n self.visited.append(child)\n \n\n if(not self.end_search): \n queue.append(min_child)\n print(f'Next item -> {min_child}')\n return self.visited\n \n \n def ucs(self, G, start, destination): \n queue = []\n queue.append(start)\n\n self.visited = []\n self.end_search = False\n \n self.visited.append(start)\n\n print(f'Starting point -> {start}')\n\n while len(queue) > 0 and not self.end_search:\n current_node = queue.pop(0)\n max_dist = 99999\n min_child = \"\"\n\n if current_node is destination:\n print(f'Destination -> {current_node}')\n self.end_search = True\n self.visited.append(current_node)\n break\n \n for child in list(G.adj[current_node]):\n if current_node + child and child + current_node not in self.visited:\n w = G[current_node][child][\"weight\"]\n if w < max_dist:\n max_dist = w\n min_child = child\n self.visited.append(current_node + child) \n if(not self.end_search): \n queue.append(min_child)\n print(f'Next item -> {min_child}')\n return self.visited\n\nG = nx.Graph()\n\nE = [(\"Sports Complex\", \"Siwaka\", {\"weight\": 450}), (\"Siwaka\", \"Phase 1B\", {\"weight\" : 230}), (\"Siwaka\", \"Phase 1A\", {\"weight\" : 10}), (\"Phase 1B\", \"Phase 2\", {\"weight\": 112}), (\"Phase 1A\", \"Phase 1B\", {\"weight\": 100}), (\"Phase 1B\", \"STC\", {\"weight\" : 50}), (\"Phase 1A\", \"Phase 1B\", {\"weight\" : 100}), (\"Phase 1A\", \"Madaraka\", {\"weight\": 850}), (\"STC\", \"Parking Lot\", {\"weight\": 250}), (\"STC\", \"Phase 2\", {\"weight\": 50}), (\"Phase 2\", \"J1\", {\"weight\": 600}), (\"Phase 2\", \"Phase 3\", {\"weight\": 500}), (\"J1\", \"Madaraka\", {\"weight\": 200}), (\"Madaraka\", \"Parking Lot\", {\"weight\": 700 }), (\"Phase 3\", \"Parking Lot\", {\"weight\": 350})]\n\n\nN = [\"Sports Complex\", \"Siwaka\", \"Phase 1A\", \"Phase 1B\", \"STC\", \"Phase 2\", \"Parking Lot\", \"Phase 3\", \"J1\", \"Madaraka\"]\n\n\nC = [(0, 10), (10, 10), (20, 10), (10, 5), (10, 2), (20, 5), (30, 0), (30, 3), (30, 5), (40, 5)]\n\nhlsd = [730, 405, 380, 280, 213, 210, 0, 160, 500, 630]\n\nP = { N[i] : v for i, v in enumerate(C) }\nhlsd_mapping = { N[i] : v for i, v in enumerate(hlsd) }\n\nG.add_nodes_from(N)\nG.add_edges_from(E)\n\nfor k, l in P.items():\n G.nodes[k]['position'] = l\n\nprint(G[\"Sports Complex\"][\"Siwaka\"][\"weight\"])\n\nt1 = Move()\nprint('Greedy Breadth First Search:')\nprint(t1.greedy(G, \"Sports Complex\", \"Parking Lot\"))\nprint('\\nEnd')\n\n\nt2 = Move()\nprint('Uniform Cost Search:')\nprint(t2.ucs(G, \"Sports Complex\", \"Parking Lot\"))\nprint('\\nEnd')\n\n\npositions = nx.get_node_attributes(G, 'position')\nlabels = nx.get_edge_attributes(G, 'weight')\n\n\nnx.draw_networkx(G, positions, node_size = 350)\nnx.draw_networkx_edges(G, positions)\nnx.draw_networkx_edge_labels(G, positions, edge_labels = labels)\npb.axis('off')\npb.show()","sub_path":"walk_rob.py","file_name":"walk_rob.py","file_ext":"py","file_size_in_byte":4065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"651841289","text":"# -*- coding: utf-8 -*-\nfrom numpy import modf\n\nfrom color import Color\nfrom component import Component\nfrom componenttypes import TYPE_SIM_CONTINUOUS\nfrom lib.pseqt import * # @UnusedWildImport\nfrom terminal import TERM\n\n\nclass GenConst(Component):\n \"\"\"!\n @if English\n\n @endif\n\n @if Slovak\n\n Zdroj konštantnej hodnoty typu INT alebo FLOAT.\n\n @endif\n \"\"\"\n\n def __init__(self, name, pos):\n Component.__init__(self, name, pos)\n\n self.compType = TYPE_SIM_CONTINUOUS\n self.box = QRectF(-30, -15, 60, 30)\n self.shapeColor = Color.black\n self.addTerminal('OUT', 1, TERM.OUT, QPointF(30, 0), TERM.DIR_EAST, TERM.OUT_ARROW_SMALL_FILL, TERM.OUT_ARROW_SMALL)\n\n self.addParameter('Value', 1.0)\n\n def drawShape(self, gc):\n grad = QLinearGradient(0, -10, 0, 20)\n grad.setColorAt(0, Color.white)\n grad.setColorAt(1, Color.green)\n gc.setBrush(QBrush(grad))\n\n gc.setPen(QPen(self.shapeColor, 1))\n gc.drawRoundedRect(-25, -10, 50, 20, 5, 5)\n\n value = self.parameter['Value'].value\n # uprava zobrazenia celocisenych udajov bez desatinnej casti\n if type(value) == float:\n if modf(value)[0] == 0.0:\n s = str(int(value))\n else:\n s = str(value)\n\n self.font = QFont('Decorative', 10)\n fm = QFontMetrics(self.font)\n # urcenie rozmerov textu a centrovanie vzhladom\n # tw = fm.width(s)\t # k zadanej polohe referencneho bodu\n th = fm.height()\n\n qr = QRectF(-25, -th / 2, 50, th)\n gc.drawText(qr, Qt.AlignCenter, s)\n\n def sim(self, flag, value, time, step):\n self.terminal[1].value = self.parameter['Value'].value\n","sub_path":"src/lib/sources/gen_const.py","file_name":"gen_const.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"447979549","text":"import numpy as np\nimport math\nimport json\nimport cv2\n\ndef openposeCoG(jsonFilePath):\n #傾き\n def inclination(x1,y1,x2,y2):\n return (y2-y1)/(x2-x1)\n #切片\n def intercept(d,x,y):\n return y-d*x\n #2直線の交点x座標\n def intersection(d1,b1,d2,b2):\n return (b2-b1)/(d1-d2)\n\n #重心座標\n cogs = list()\n #json読み取り\n j = open(jsonFilePath, 'r')\n json_dict = json.load(j)\n\n\n\n #関節位置配列\n #対応位置はopenpose.pngを参照\n #[x座標,y座標,信頼度]\n P = list()\n\n #必要なデータを抜き取る\n for i, kpt in enumerate(json_dict['keypoint']):\n P.append([kpt[0],kpt[1]])\n #信頼度を追加\n P[i].append(kpt[2])\n # #値チェック\n # for i, p in enumerate(P):\n # print(i,p)\n #足元----------\n #足先2点の中点\n f0 = [(P[13][0]+P[10][0])/2, (P[13][1]+P[10][1])/2]\n\n #足先2点の直線f0\n #傾き\n d0 = inclination(P[10][0],P[10][1],P[13][0],P[13][1])\n #切片\n b0 = intercept(d0,P[13][0],P[13][1])\n\n #fに直交する傾き\n dd0 = -1*(1/d0)\n\n #膝2点の中点を通りfに直行する直線f1\n #切片\n b1 = intercept(dd0, (P[12][0]+P[9][0])/2, (P[12][1]+P[9][1])/2)\n #fとの交点f1\n f1 = [intersection(d0,b0,dd0,b1)]\n f1.append(dd0*f1[0]+b1)\n\n #腰2点の中点を通りfに直行する直線f2\n #切片\n b2 = intercept(dd0, (P[11][0]+P[8][0])/2, (P[11][1]+P[8][1])/2)\n #fとの交点f2\n f2 = [intersection(d0,b0,dd0,b2)]\n f2.append(dd0*f2[0]+b2)\n\n #f,f1,f2の重心点under\n under = [(f0[0]+f1[0]+f2[0])/3, (f0[1]+f1[1]+f2[1])/3]\n # if math.isnan(under[0]) or math.isnan(under[1]):\n # continue;\n #足元---------\n\n #頭----------\n centerID = 0\n if not (P[16][0] == 0 or P[16][1] == 0 or P[17][0] == 0 or P[17][1] == 0):\n #右耳と左耳の中点\n center = [(P[16][0]+P[17][0])/2, (P[16][1]+P[17][1])/2]\n centerID = 1\n else:\n # 鼻と首の中点\n center = [(P[0][0]+P[1][0])/2, (P[0][1]+P[1][1])/2]\n centerID = 2\n #underからcenterへの直線f3\n #傾き\n d3 = inclination(center[0],center[1],under[0],under[1])\n #切片\n b3 = intercept(d3,center[0],center[1])\n\n #f3に直交する傾き\n dd3 = -1*(1/d3)\n\n #首を通りf3に直交する直線f4\n #切片\n b4 = intercept(dd3, P[1][0], P[1][1])\n #f3との交点\n f4 = [intersection(d3, b3, dd3, b4)]\n f4.append(dd3*f4[0]+b4)\n #ベクトルを生成\n f4v = np.array([f4[0], f4[1]])\n\n if centerID == 1:\n #f3とf4の交点とcenterの距離\n l = np.linalg.norm(center-f4v)\n else:\n #鼻を通りf3に直交する直線f5\n #切片\n b5 = intercept(dd3, P[0][0], P[0][1])\n #f3との交点\n f5 = [intersection(d3, b3, dd3, b5)]\n f5.append(dd3 * f5[0] + b5)\n #ベクトルを生成\n f5v = np.array([f5[0], f5[1]])\n\n #f3とf4の交点とf3とf5の交点の距離\n l = np.linalg.norm(f5v-f4v)\n\n #underからcenterへの単位ベクトルuを生成\n #underからcenterへのベクトルv\n v = np.array([center[0]-under[0],center[1]-under[1]])\n #正規化\n u = v / np.linalg.norm(v)\n\n #f3とf4の交点からベクトルuの向きにlを2倍伸ばした座標の点top\n top = [f4[0] + u[0]*l*2, f4[1] + u[1]*l*2]\n # if math.isnan(top[0]) or math.isnan(top[1]):\n # continue;\n #頭----------\n\n #underからtopへのベクトル\n utvec = np.array([top[0]-under[0],top[1]-under[1]])\n #重心点\n cog__ = [under[0] + utvec[0]*0.6, under[1] + utvec[1]*0.6]\n\n cog_ = list()\n #重心の座標をappend\n cog_.append(cog__[0])\n cog_.append(cog__[1])\n #足元基準点の座標をappend\n cog_.append(under[0])\n cog_.append(under[1])\n #頭部基準点の座標をappend\n cog_.append(top[0])\n cog_.append(top[1])\n #右手の座標をappend\n cog_.append(P[4][0])\n cog_.append(P[4][1])\n #左手の座標をappend\n cog_.append(P[7][0])\n cog_.append(P[7][1])\n #首の座標をappend\n cog_.append(P[1][0])\n cog_.append(P[1][1])\n #信頼度の合計をappend\n cog_.append(np.sum(P,0)[2])\n cogs.append(cog_)\n\n\n # #要点確認\n # img = cv2.imread('./resource/wally000024_resize_rendered.png')\n # img = cv2.circle(img, (int(center[0]), int(center[1])), 10, (0,0,255), -1)\n # img = cv2.circle(img, (int(top[0]), int(top[1])), 10, (0,100,100), -1)\n # img = cv2.circle(img, (int(under[0]), int(under[1])), 10, (100,100,0), -1)\n # img = cv2.circle(img, (int(cog_[0]), int(cog_[1])), 10, (100,100,100), -1)\n # cv2.imshow('test', img)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n #\n # #画像出力\n # print(\"save this image?\")\n # save = input(\"0,1 or n >> \")\n # if save == '0' or save == '1':\n # cv2.imwrite(\"./output/024_\"+save+\".png\", img)\n\n # #値の確認\n # print(\"under:\",under[0], under[1])\n # print(\"top:\",top[0], top[1])\n # print(\"cog\", cog[0], cog[1])\n # print(cogs)\n cog = cogs[np.argmax(cogs, 0)[2]]\n return cog\n\nif __name__ == '__main__':\n print('view', openposeCoG('./resource/re18_keypoints.json'))\n","sub_path":"programs/test/cog/cog.py","file_name":"cog.py","file_ext":"py","file_size_in_byte":5235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"301788579","text":"from dolfin import *\nimport numpy as np\n\nmesh_file = UnitSquareMesh(10, 10)\n#mesh_file = refine(mesh_file)\n#Parameters for each numerical case\ncommon = {\"mesh\": mesh_file,\n \"v_deg\": 2, #Velocity degree\n \"p_deg\": 1, #Pressure degree\n \"d_deg\": 2, #Deformation degree\n \"T\": 1E-4, # End time\n \"dt\": 1E-5, # Time step\n \"rho_f\": 1.0, #\n \"mu_f\": 1.,\n \"rho_s\" : Constant(1.0),\n \"mu_s\" : Constant(1.0),\n \"nu_s\" : Constant(1.0)\n }\n\nvars().update(common)\nlamda_s = nu_s*2*mu_s/(1 - 2.*nu_s)\nnu = mu_f/rho_f\n#plot(mesh, interactive=True)\n\n\n#Allboundaries = DomainBoundary()\nFluid_area = AutoSubDomain(lambda x, on_bnd: (x[0] <= 0.5) and on_bnd)\nboundaries = FacetFunction(\"size_t\", mesh_file)\nboundaries.set_all(0)\nDomainBoundary().mark(boundaries, 2)\nFluid_area.mark(boundaries, 1)\n\nplot(boundaries,interactive=True)\n\nds = Measure(\"ds\", subdomain_data = boundaries)\ndS = Measure(\"dS\", subdomain_data = boundaries)\nn = FacetNormal(mesh_file)\n\nFluid_area = AutoSubDomain(lambda x: (x[0] <= 0.5))\ndomains = CellFunction(\"size_t\", mesh_file)\ndomains.set_all(2)\nFluid_area.mark(domains, 1)\ndx = Measure(\"dx\", subdomain_data = domains)\n\n#plot(domains,interactive = True)\n\ndx_f = dx(1, subdomain_data = domains)\ndx_s = dx(2, subdomain_data = domains)\n\ndef initiate(DVP, dvp_, mesh_file, t, rho_f, rho_s, mu_f, mu_s, nu, \\\n dx_f, dx_s, F_fluid_linear, F_solid_linear, phi, psi, **monolithic):\n t_ = Constant(0)\n x = SpatialCoordinate(mesh_file)\n\n def sigma_f(p_, u_, mu_f):\n return -p_*Identity(2) + 2.*mu_f*sym(grad(u_))\n\n def F_(U):\n \treturn Identity(len(U)) + grad(U)\n\n def J_(U):\n \treturn det(F_(U))\n\n def E(U):\n \treturn 0.5*(F_(U).T*F_(U) - Identity(len(U)))\n\n def S(U,lamda_s,mu_s):\n I = Identity(len(U))\n return 2*mu_s*E(U) + lamda_s*tr(E(U))*I\n\n def Piola1(U,lamda_s,mu_s):\n \treturn F_(U)*S(U,lamda_s,mu_s)\n\n d_x = \"0\"\n d_y = \"t_*(x[0] - 0.5)\"\n u_x = \"0\"\n u_y = \"(x[0] - 0.5)\"\n p_c = \"2\"\n\n p_e = Expression(p_c, nu=nu, t_=0.0, degree=6)\n\n u_e = Expression((u_x,\\\n u_y), nu=nu, t_=0.0, degree=6)\n\n d_e = Expression((d_x,\\\n d_y), nu=nu, t_=0.0, degree=6)\n\n assign(dvp_[\"n-1\"].sub(0), interpolate(d_e, DVP.sub(0).collapse()))\n assign(dvp_[\"n-1\"].sub(1), interpolate(u_e, DVP.sub(1).collapse()))\n assign(dvp_[\"n-1\"].sub(2), interpolate(p_e, DVP.sub(2).collapse()))\n\n #For a non-zero initial guess on first newtoniteration\n assign(dvp_[\"n\"].sub(0), interpolate(d_e, DVP.sub(0).collapse()))\n assign(dvp_[\"n\"].sub(1), interpolate(u_e, DVP.sub(1).collapse()))\n assign(dvp_[\"n\"].sub(2), interpolate(p_e, DVP.sub(2).collapse()))\n\n t_ = Constant(0)\n d_x = 0\n d_y = t_*(x[0] - 0.5)\n u_x = 0\n u_y = (x[0] - 0.5)\n p_c = 2\n\n #exec(\"d_x = %s\" % d_x) in locals(), globals()\n #exec(\"d_y = %s\" % d_y) in locals(), globals()\n #exec(\"u_x = %s\" % u_x) in locals(), globals()\n #exec(\"u_y = %s\" % u_y) in locals(), globals()\n #exec(\"p_c = %s\" % p_c) in locals(), globals()\n\n d_vec = as_vector([d_x, d_y])\n u_vec = as_vector([u_x, u_y])\n\n f_fluid = rho_f*diff(u_vec, t_) + rho_f*dot(grad(u_vec), u_vec - diff(d_vec, t_)) - div(sigma_f(p_c, u_vec, mu_f))\n #f_fluid = rho_f*diff(u_vec, t_) + rho_f*dot(u_vec - diff(d_vec, t_), grad(u_vec)) - div(sigma_f(p_c, u_vec, mu_f))\n\n f_solid = rho_s*diff(d_vec, t_) - div(Piola1(d_vec, lamda_s, mu_s))\n\n F_fluid_linear -= inner(Constant((10,0)), phi)*dx_f\n #F_fluid_linear -= inner(J_(d_vec)*f_fluid, phi)*dx_f\n F_solid_linear -= inner(f_solid, psi)*dx_s\n\n return dict(t_=t_, d_e=d_e, u_e=u_e, p_e=p_e)\n\ndef create_bcs(DVP, dvp_, u_e, p_e, d_e, boundaries, **semimp_namespace):\n #displacement conditions:\n d_bc = DirichletBC(DVP.sub(0), d_e, \"on_boundary\")\n\n #Fluid velocity conditions\n u_bc = DirichletBC(DVP.sub(1), u_e, \"on_boundary\")\n\n #Pressure Conditions\n p_bc = DirichletBC(DVP.sub(2), p_e, boundaries, 1)\n\n #Assemble boundary conditions\n bcs = [d_bc, u_bc, p_bc]\n\n return dict(bcs = bcs)\n\ndef pre_solve(t, t_, p_e, d_e, u_e, **semimp_namespace):\n t_.assign(t)\n p_e.t_ = t\n u_e.t_ = t\n d_e.t_ = t\n return {}\n\n\ndef after_solve(**semimp_namespace):\n\n\n return {}\n\ndef post_process(E_u, u_e, d_e, dvp_, mu_f, lamda_s, mu_s, mesh_file, boundaries, **semimp_namespace):\n def F_(U):\n \treturn (Identity(len(U)) + grad(U))\n\n def J_(U):\n \treturn det(F_(U))\n\n def E(U):\n \treturn 0.5*(F_(U).T*F_(U) - Identity(len(U)))\n\n def S(U,lamda_s,mu_s):\n I = Identity(len(U))\n return 2*mu_s*E(U) + lamda_s*tr(E(U))*I\n\n def Piola1(U,lamda_s,mu_s):\n \treturn F_(U)*S(U,lamda_s,mu_s)\n\n def sigma_f_new(v, p, d, mu_f):\n \treturn -p*Identity(len(v)) + mu_f*(grad(v)*inv(F_(d)) + inv(F_(d)).T*grad(v).T)\n\n d, v, p = dvp_[\"n\"].split(True)\n\n F_Dr = -assemble((sigma_f_new(v(\"-\"),p(\"-\"),d(\"-\"),mu_f)*n(\"-\"))[0]*dS(5))\n F_Li = -assemble((sigma_f_new(v(\"-\"),p(\"-\"),d(\"-\"),mu_f)*n(\"-\"))[1]*dS(5))\n\n S_Dr = -assemble((Piola1(d(\"-\"),lamda_s, mu_s)*n(\"-\"))[0]*dS(5))\n S_Li = -assemble((Piola1(d(\"-\"),lamda_s, mu_s)*n(\"-\"))[0]*dS(5))\n\n\n #To evaluate error on fluid and structure\n submesh_fluid = SubMesh(mesh, boundaries, 1)\n submesh_struc = SubMesh(mesh, boundaries, 2)\n\n #E_d = errornorm(d_e, d_s, norm_type=\"l2\", degree_rise=2, mesh=submesh_struc)\n E_u.append(errornorm(u_e, v_s, norm_type=\"l2\", degree_rise=2, mesh=submesh_fluid))\n h_ = mesh_file.hmin()\n #print \"E_u=%g, E_d=%g\" % (E_u, E_d)\n return {}\n","sub_path":"FSIVerification/ALE_Fresh/Problems/mms.py","file_name":"mms.py","file_ext":"py","file_size_in_byte":5644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"318759211","text":"def add(a, b):\n print(f\"ADDING {a} + {b}\")\n return a + b\n\ndef subtract(a, b):\n print(f\"SUBTRACTING {a} - {b}\")\n return a - b\n\ndef multiply(a, b):\n print(f\"MULTIPLYING {a} * {b}\")\n return a * b\n\ndef divide(a, b):\n print(f\"DIVIDING {a} / {b}\")\n return a / b\n\nprint(\"Let's do some math with just functions!\")\n\nage = add(30, 5)\nheight = subtract(78, 4)\nweight = multiply(90, 2)\niq = divide(100, 2)\n\nprint(f\"Age: {age}, Height: {height}, Weight: {weight}, IQ: {iq}\")\n\n# A puzzle for the extra credit, type it in anyway.\nprint(\"Here is a puzzle.\")\n\nwhat = subtract(add(divide(3, 3), multiply(300, 25)), 1200)\n\nprint(\"That becomes: \", what, \"Can you do it by hand?\")\n\ndef pet(name):\n print(\"That's a nice name.\")\n return name\n\ndef pet_age(age):\n print(\"Wow.\")\n return age\n\ndog_name = pet(\"King\")\ndog_age = pet_age(102)\n\nprint(f\"Your pet, {dog_name} is {dog_age} years old.\")","sub_path":"ex21.py","file_name":"ex21.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"613886697","text":"import copy\n\nfrom django.contrib import admin, messages\nfrom django.core.urlresolvers import reverse\nfrom django.db import models\nfrom django.http import HttpResponseRedirect\nfrom django.utils import timezone\nfrom django.utils.encoding import force_text\n\nfrom watson.search import default_search_engine\n\nfrom ...attachments.admin import DocumentAdminInline\nfrom ...utils.admin import ConfigurableModelAdmin, remove_from_fieldsets\nfrom ...utils.base import update_url_params\nfrom ..models import Article, ArticleDocument, BaseArticle, Category, SampleArticle, Subscriber, Tag\nfrom ..watson_adapters import ArticleAdapter\nfrom .forms import ArticleAdminForm\n\n\nclass ArticleDocumentInline(DocumentAdminInline):\n model = ArticleDocument\n\n\nclass BaseArticleAdmin(ConfigurableModelAdmin):\n form = ArticleAdminForm\n change_form_template = 'admin/custom_change_form.html'\n\n fieldsets = (\n (None, {'fields': ['title', 'slug', 'status', 'published_at']}),\n (None, {'fields': ['cover_image', 'short_description', 'content']}),\n )\n\n _status_colors = {\n BaseArticle.STATUS_PUBLISHED: '#008000',\n BaseArticle.STATUS_READY_FOR_PUBLISH: '#0079FF',\n BaseArticle.STATUS_DRAFT: '#717171',\n }\n\n def change_status(self, request, queryset, status):\n model = queryset.model\n opts = model._meta\n\n status_display = force_text(dict(opts.get_field('status').flatchoices).get(status, status), strings_only=True)\n objects_count = queryset.count()\n\n update_fields = {'status': status}\n if status == model.STATUS_PUBLISHED:\n update_fields['published_at'] = models.Case(models.When(~models.Q(status=model.STATUS_PUBLISHED),\n then=timezone.now()),\n default=models.F('published_at'))\n queryset.update(**update_fields)\n messages.success(request, 'Status set to \"%s\" in %s %s.' % (\n status_display, objects_count, opts.verbose_name if objects_count == 1 else opts.verbose_name_plural\n ))\n change_status.short_description = 'Mark as \"%(status_name)s\"'\n\n def colorized_status(self, obj):\n color = self._status_colors[obj.status]\n return '%s' % (color, obj.get_status_display()\n .replace(' ', ' '))\n colorized_status.short_description = 'Status'\n colorized_status.admin_order_field = 'status'\n colorized_status.allow_tags = True\n\n def make_action(self, action, kwargs, context):\n if callable(action):\n func = action\n action = action.__name__\n\n elif hasattr(self.__class__, action):\n func = getattr(self.__class__, action)\n\n description = func.short_description % context\n action += '__' + '__'.join(map(lambda x: '%s__%s' % x, kwargs.items()))\n return lambda s, r, q: func(s, r, q, **kwargs), action, description\n\n def get_actions(self, request):\n actions = super(BaseArticleAdmin, self).get_actions(request)\n\n for value, name in BaseArticle.CHOICES_STATUS:\n action = self.make_action('change_status', {'status': value}, {'status_name': name})\n actions[action[1]] = action\n\n return actions\n\n def list_display_hits(self, request):\n return request.user.has_perm('blog.view_article_hits')\n\n def get_readonly_fields(self, request, obj=None):\n readonly_fields = super(BaseArticleAdmin, self).get_readonly_fields(request, obj=obj)[:]\n if obj:\n readonly_fields += ('slug', )\n return readonly_fields\n\n def get_fieldsets(self, request, obj=None):\n fieldsets = copy.deepcopy(super(BaseArticleAdmin, self).get_fieldsets(request, obj=obj))\n if not obj:\n remove_from_fieldsets(fieldsets, 'published_at')\n return fieldsets\n\n\n@admin.register(Article)\nclass ArticleAdmin(BaseArticleAdmin):\n list_display = [\n 'title', 'categories_list', 'tags_list', 'short_description',\n 'published_at', 'is_featured', 'colorized_status', 'hits', 'words_count'\n ]\n list_filter = ['is_featured', 'status', 'categories', 'published_at']\n\n fieldsets = copy.deepcopy(BaseArticleAdmin.fieldsets)\n fieldsets[0][1]['fields'].insert(2, 'tags')\n fieldsets[0][1]['fields'].insert(2, 'categories')\n fieldsets[0][1]['fields'] += ['is_featured']\n\n search_adapter_cls = ArticleAdapter\n search_engine = default_search_engine\n # Dirty hack for displaying search input\n search_fields = [None]\n\n inlines = (ArticleDocumentInline,)\n\n actions = ['mark_featured', 'unmark_featured']\n\n def mark_featured(self, request, queryset):\n model = queryset.model\n opts = model._meta\n\n objects_count = queryset.count()\n\n queryset.update(is_featured=True)\n messages.success(request, '%s %s marked as featured.' % (\n objects_count, opts.verbose_name if objects_count == 1 else opts.verbose_name_plural\n ))\n mark_featured.short_description = 'Mark as featured'\n\n def unmark_featured(self, request, queryset):\n model = queryset.model\n opts = model._meta\n\n objects_count = queryset.count()\n\n queryset.update(is_featured=False)\n messages.success(request, 'Featured flag removed from %s %s.' % (\n objects_count, opts.verbose_name if objects_count == 1 else opts.verbose_name_plural\n ))\n unmark_featured.short_description = 'Remove featured flag'\n\n def get_queryset(self, request):\n return super(ArticleAdmin, self).get_queryset(request).prefetch_related('tags', 'categories')\n\n def get_search_results(self, request, queryset, search_term):\n if not search_term:\n return queryset, False\n\n return self.search_engine.filter(queryset, search_term, ranking=False), False\n\n def changelist_view(self, request, extra_context=None):\n # Dirty hack for tags\n self.request = request\n return super(ArticleAdmin, self).changelist_view(request, extra_context=extra_context)\n\n def get_form(self, request, obj=None, **kwargs):\n form = super(ArticleAdmin, self).get_form(request, obj, **kwargs)\n form.base_fields['tags'].widget.can_add_related = False\n return form\n\n def tags_list(self, obj):\n return ', '.join([\n u'%s' % (\n update_url_params(self.request.get_full_path(), {'tags__id__exact': tag.id}), tag\n ) for tag in obj.tags.all()\n ])\n tags_list.short_description = 'Tags'\n tags_list.allow_tags = True\n\n def categories_list(self, obj):\n return ', '.join(obj.categories.values_list('name', flat=True))\n categories_list.short_description = 'Categories'\n\n\n@admin.register(SampleArticle)\nclass SampleArticleAdmin(ArticleAdmin):\n new_article_action_name = '_create_article'\n\n list_display = [\n 'title', 'tags_list', 'short_description', 'words_count'\n ]\n list_filter = ['categories']\n actions = []\n\n def render_change_form(self, request, context, **kwargs):\n if kwargs.get('obj'):\n context = context or {}\n context.update({\n 'additional_actions': [\n {'text': 'Create new article from sample', 'name': self.new_article_action_name}\n ]\n })\n return super(SampleArticleAdmin, self).render_change_form(request, context, **kwargs)\n\n def response_change(self, request, obj):\n if self.new_article_action_name in request.POST:\n article = Article(sample=obj)\n article.save()\n article.tags.add(*obj.tags.all())\n\n msg = 'New article was created from \"%(obj)s\" successfully.' % {'obj': force_text(obj)}\n self.message_user(request, msg, messages.SUCCESS)\n redirect_url = reverse('admin:%s_%s_change' % (self.model._meta.app_label, 'article'),\n current_app=self.admin_site.name, args=[article.pk])\n return HttpResponseRedirect(redirect_url)\n\n else:\n return super(SampleArticleAdmin, self).response_change(request, obj)\n\n def get_fieldsets(self, request, obj=None):\n fieldsets = super(SampleArticleAdmin, self).get_fieldsets(request, obj)\n remove_from_fieldsets(fieldsets, ['status', 'published_at', 'is_featured'])\n return fieldsets\n\n\n@admin.register(Category)\nclass CategoryAdmin(admin.ModelAdmin):\n list_display = ('name', )\n\n\n@admin.register(Tag)\nclass TagAdmin(admin.ModelAdmin):\n search_fields = ('name', )\n list_display = ('name', 'article_count')\n\n def get_queryset(self, request):\n return super(TagAdmin, self).get_queryset(request) \\\n .extra(select={'article_count': \"\"\"\n SELECT COUNT(1)\n FROM blog_article_tags as ET1\n INNER JOIN blog_article as ET2\n ON ET1.article_id = ET2.id AND ET2.is_sample = false\n WHERE ET1.tag_id = blog_tag.id\n \"\"\"})\n\n def article_count(self, obj):\n return obj.article_count\n article_count.short_description = 'Articles'\n article_count.admin_order_field = 'article_count'\n\n\n@admin.register(Subscriber)\nclass SubscriberAdmin(admin.ModelAdmin):\n list_display = ('email', 'send_email')\n\n\n\n\n","sub_path":"iwg_blog/blog/admin/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":9514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"490758728","text":"import requests\nfrom geocode import geocode\n\ndef bolder(address):\n \"\"\" координаты объекта по его адресу\n обращаемся к функции geocode из файла geocode.py\"\"\"\n toponym = geocode(address)\n if toponym:\n # Рамка вокруг объекта:\n envelope = toponym[\"boundedBy\"][\"Envelope\"]\n\n # левая, нижняя, правая и верхняя границы из координат углов:\n l, b = envelope[\"lowerCorner\"].split(\" \")\n r, t = envelope[\"upperCorner\"].split(\" \")\n\n # Вычисляем полуразмеры по вертикали и горизонтали\n dx = abs(float(l) - float(r)) / 2.0\n dy = abs(float(t) - float(b)) / 2.0\n\n return str(max(dx, dy))\n return None\n\n\n# print(bolder('Москва, ул. Ак. Королева, 12'))\n","sub_path":"Maps API/bolder.py","file_name":"bolder.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"511599102","text":"import pymysql\nimport json\nimport requests\nimport threading\n\n#connect to DB\ndef getweather():\n smart_mirror_db = pymysql.connect(\n user = 'root',\n passwd = '3695812tF!@',\n host = '127.0.0.1',\n db = 'smartmirrordb',\n charset='utf8'\n )\n cursor = smart_mirror_db.cursor()\n\n # get licence information\n lic = open(\"AppFiles\\weatherWidget\\APIlicence.txt\", 'r')\n licStr = ''\n while True:\n line = lic.readline()\n if not line:\n break\n licStr = line\n lic.close()\n\n #get weather information from api\n\n #get locaion info(city)\n citySQL = \"select lat, lon from geolocation\"\n cursor.execute(citySQL)\n\n cityStr = cursor.fetchone()\n\n #Access API\n apiurl = \"https://api.openweathermap.org/data/2.5/weather?lat=\"+str(cityStr[0])+\"&lon=\"+str(cityStr[1])+\"&appid=\"+licStr\n\n #receive json\n text = (requests.get(apiurl)).text\n data = json.loads(text)\n\n #extrack data\n currentTemp = round(data['main']['temp'] - 273.15)\n currentWthId = data['weather'][0]['id']\n currentWeather = data['weather'][0]['main']\n humidity = data['main']['humidity']\n windspd =round(data['wind']['speed'])\n wind_dict = data['wind']['deg']\n\n print(\"-----------------------------------------------------------\")\n print(\"< Data from API >\")\n print(data)\n print()\n \n #update to database\n param1 = \"currentTemp=\"+str(currentTemp)+\",currentWthId=\"+str(currentWthId)+\",currentWeather=\"+'\"'+str(currentWeather)+'\"'+\",humidity=\"+str(humidity)+\",windspd=\"+str(windspd)+\",wind_dict=\"+str(wind_dict)\n\n updateSQL = \"update weatherinfo set \"+ param1\n cursor.execute(updateSQL)\n\n smart_mirror_db.commit()\n smart_mirror_db.close()\n\n print(\"weather information update complete\")\n\n threading.Timer(600, getweather).start()\n\n\nif __name__ == '__main__':\n getweather()","sub_path":"AppFiles/weatherWidget/wthInfomain.py","file_name":"wthInfomain.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"53234380","text":"a=float(input('Введите число '))\r\na1=a//10\r\na2=a%10\r\nif ((a1==3)or(a1==7))and((a2==3)or(a2==7)):\r\n print('Да, в это число входят цифры 3 и 7')\r\nelse:\r\n print('Нет, в это число не входят цифры 3 и 7')\r\n\r\nif ((a1==4)or(a1==8))and((a2==4)or(a2==8))or((a1==9)or(a2==9)):\r\n print('Да, в это число входят цифры (4 и 8) или цифра 9')\r\nelse:\r\n print('Нет, в это число не входят цифры (4 и 8) или цифра 9')\r\n\r\n","sub_path":"Lab2/lab2.6.py","file_name":"lab2.6.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"329150045","text":"# coding=utf-8\n\"\"\"根据搜索词下载百度图片\"\"\"\nimport re\nimport sys\nimport urllib\nimport io\nimport requests\nfrom PIL import Image\nimport os\nimport time\n\ndef getPage(keyword, page, n):\n page = page * n\n\n keyword = urllib.parse.quote(keyword, safe='/')\n url_begin = \"http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=\"\n url = url_begin + keyword + \"&pn=\" + str(page) + \"&gsm=\" + str(hex(page)) + \"&ct=&ic=0&lm=-1&width=0&height=0\"\n return url\n\n\ndef get_onepage_urls(onepageurl):\n headers = {\n 'Connection': 'close',\n }\n try:\n html = requests.get(onepageurl,headers=headers ,allow_redirects=False).text\n except Exception as e:\n # print('getOnepage_url-------'+e)\n pic_urls = []\n return pic_urls\n pic_urls = re.findall('\"objURL\":\"(.*?)\",', html, re.S)\n return pic_urls\n\n\ndef down_pic(pic_urls ,name ):\n \"\"\"给出图片链接列表, 下载所有图片\"\"\"\n for i, pic_url in enumerate(pic_urls):\n try:\n pic = requests.get(pic_url, timeout=15)\n # iofile = io.BytesIO(pic.content)\n # im =Image.open(iofile)\n\n # /home/ec2-user/tensorflow-for-poets-2/tf_files/anim/\n dirString = 'C:/Users/hanwenmao/Desktop/tensorflow/Album classification/' +name + '/one/'\n dirConvertString = 'C:/Users/hanwenmao/Desktop/tensorflow/Album classification/'+name +'/'\n string = 'C:/Users/hanwenmao/Desktop/tensorflow/Album classification/' +name + '/one/' + str(time.time()) + '.jpg'\n stringConvert = 'C:/Users/hanwenmao/Desktop/tensorflow/Album classification/'+name +'/' +str(time.time()) +'convert'+ '.jpg'\n\n if not os.path.exists(dirString):\n os.makedirs(dirString)\n if not os.path.exists(dirConvertString):\n os.makedirs(dirConvertString)\n\n with open(string, 'wb') as f:\n try:\n f.write(pic.content)\n im = Image.open(string)\n im.convert(\"RGB\")\n im.save(stringConvert)\n except Exception as e :\n if os.path.exists(stringConvert):\n os.remove(stringConvert)\n print('写入失败----------' ,str(e))\n\n print('成功下载第%s张图片: %s' % (str(i + 1), str(pic_url)))\n except Exception as e:\n print('下载第%s张图片时失败: %s' % (str(i + 1), str(pic_url)))\n print('all exception---------'+str(e))\n continue\n\ndef start( index ,name ) :\n\n keyword = index # 关键词, 改为你想输入的词即可, 相当于在百度图片里搜索一样\n page_begin = 11 #0-3 / 4-10\n page_number = 80\n image_number = 13\n all_pic_urls = []\n while 1:\n if page_begin > image_number:\n break\n print(\"第%d次请求数据\", [page_begin])\n url = getPage(keyword, page_begin, page_number)\n onepage_urls = get_onepage_urls(url)\n page_begin += 1\n\n all_pic_urls.extend(onepage_urls)\n\n down_pic(list(set(all_pic_urls)) , name)\n\n\nif __name__ == '__main__':\n # 个人自拍 ,证件照 ,动物 ,美食 ,风景,多人合照 ,手机截图\n items = {'个人自拍': 'Personal selfie', '证件照': 'Document photo', '动物': 'animal'\n , '美食': 'Food', '风景': 'landscape', '多人合照': 'Multi-personphoto', '手机截图': 'Phone-screenshot'}\n\n for item in items:\n start(item , str(items[item]))","sub_path":"downPage/downImage2.py","file_name":"downImage2.py","file_ext":"py","file_size_in_byte":3540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"138016159","text":"\"\"\"\nProblem: 890. Find and Replace Pattern\nUrl: https://leetcode.com/problems/find-and-replace-pattern/\nAuthor: David Wang\nDate: 10/29/2018\n\"\"\"\n\nclass Solution:\n def findAndReplacePattern(self, words, pattern):\n \"\"\"\n :type words: List[str]\n :type pattern: str\n :rtype: List[str]\n \"\"\"\n matches = []\n for word in words:\n if self.is_match(word, pattern):\n matches.append(word)\n return matches\n\n def is_match(self, word, pattern):\n p2w = {}\n w2p = {}\n for w, p in zip(word, pattern):\n if p not in p2w: p2w[p] = w\n if w not in w2p: w2p[w] = p\n if p2w[p] != w or w2p[w] != p:\n return False\n\n return True\n\nif __name__ == '__main__':\n words = [\"abc\",\"deq\",\"mee\",\"aqq\",\"dkd\",\"ccc\"]\n pattern = 'abb'\n s = Solution()\n print(s.findAndReplacePattern(words, pattern))\n","sub_path":"890_Find_and_Replace_Pattern/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"10053520","text":"import tkinter as tk\nfrom tkinter import *\nfrom PIL import Image, ImageTk # for windows is this option , ImageGrab\n# for windows is this option\n#from PIL import ImageGrab\n#for linux\nimport pyscreenshot as ImageGrab\nfrom math import sqrt,ceil\nfrom tkinter import filedialog\nimport os\nfrom tkinter import messagebox\n\nclass Gui():\n\tdef __init__(self, root):\n\t\tself.root=root\n \n\t\tframeCanvas=Frame(self.root)\n\t\tframeCanvas.grid(row=0,column=0,pady=20,sticky=\"n\")\n\t\tself.canvas=tk.Canvas(frameCanvas, width=450, height=500,borderwidth=2, relief=\"groove\",cursor=\"cross\")\n\t\tself.canvas.grid(row=0,column=0, pady=0, padx=10)\n\t\tbuttonNext = tk.Button(frameCanvas, text=\"Next\", command=self.ImageNext).grid(row=1,column=0,pady=5,sticky=\"n\")\n\t\n\t\tself.x = self.y = 0\n\n\t#Image Loaded or not\n\t\tself.ImageLoaded=0\n\t\t\n\t\t#variables to be able to erase elements on the canvas\n\t\tself.rec_id=list()\n\t\tself.text_id_DM=list()\n\t\tself.text_id_ST=list()\n\t\tself.erase=0\n\t\tself.recErase=\"a\"\n\n\t#Image Canvas\n\t\tself.canvas.bind(\"\", self.on_button_press)\n\t\tself.canvas.bind(\"\", self.on_move_press)\n\t\tself.canvas.bind(\"\", self.on_button_release)\n\n\t \n\t#variables necesary to draw rectangles on the canvas\n\t\tself.rect = None\n\t\tself.start_x = None\n\t\tself.start_y = None\n\n\t#don't ask for Output.txt again\n\t\tself.Out=0\n\n\t# add a File Save menu\n\t\tmenu=Menu(root)\n\t\troot.config(menu=menu)\n\t\tfilemenu = Menu(menu)\n\t\tmenu.add_cascade(label=\"File\", menu=filemenu)\n\t\tfilemenu.add_command(label=\"Open the Original Image of the File you want to Review...\", command=self.open_file)\n\t\t#filemenu.add_command(label=\"Open All files in folder...\", command=self.open_folder)\n\t\tfilemenu.add_command(label=\"Select Output folder...\", command=self.out_folder)\n\t\tfilemenu.add_command(label=\"Enter Loc of File with labels\", command=self.open_fileText)\n\t\tfilemenu.add_separator()\n\t\tfilemenu.add_command(label=\"Exit\", command=root.quit)\n\n\t\thelpmenu = Menu(menu)\n\t\tmenu.add_cascade(label=\"Help\", menu=helpmenu)\n\t\thelpmenu.add_command(label=\"Instructions...\", command=self.help)\n\t\thelpmenu.add_command(label=\"About C.I.T.T ...\", command=self.about)\n\t\tself.path_out=\"/Out\"\n\t\tself.path=\"/images\"\n\n\t\t#list for names of images ina a folder\n\t\tself.ImageList=[]\n\t\tself.ImageListIndex=1\n\t\t\n\t\tself.pathText=\"/Out\" #labels path Output.txt\"\n\t\tself.pathAnnotations=\"/annotations\" #path where xml for each file is saved by default\t\n\t\t\n\t\t#delete labels two buttons\n\t\tframeM=Frame(root)\n\t\tframeM.grid(row=0,column=1,pady=20, padx=10,sticky=\"n\")\n\t\t\n\t\t#buttonOutFile=tk.Button(frameM, width=25,text=\"Enter Loc of File with labels\", command=self.open_fileText).grid(row=2,column=1,sticky=\"n\")\n\t\tself.reviewLabel=tk.Label(frameM,width=25,borderwidth=2, relief=\"groove\", text=\"REVIEW IMAGE\")\n\t\tself.reviewLabel.grid(row=2,column=1,sticky=\"n\")\n\t\t\n\t\tl4=tk.Label(frameM,borderwidth=2, relief=\"groove\",text=\"Delete Options\").grid(row=11,column=1,pady=10,sticky=\"n\")\n\t\tbuttonDeleteStart=tk.Button(frameM, width=25,text=\"Start Deleting\", command=self.deleteStart).grid(row=12,column=1,sticky=\"n\")\n\t\tbuttonDeleteStop=tk.Button(frameM, width=25,text=\"Stop Deleting\", command=self.deleteEnd).grid(row=13,column=1,sticky=\"n\")\n\t\t\n\t\t#console\n\t\tself.consoleLabel=tk.Label(frameM,width=25,borderwidth=2, relief=\"groove\", text=\"Current Labels\")\n\t\tself.consoleLabel.grid(row=7,column=1,pady=5,sticky=\"n\")\n\t\t#Console History\n\t\tself.consoleHist=tk.Listbox(frameM,background=\"light gray\", width=50, height=15)\n\t\tself.consoleHist.grid(row=8,column=1,padx=10,sticky=\"n\")\n\t\tself.scrollbar2=tk.Scrollbar(frameM,orient=VERTICAL)\n\t\tself.scrollbar2.grid(row=8,column=2,sticky=N+S)\n\t\tself.consoleHist.config(yscrollcommand=self.scrollbar2.set)\n\t\tself.scrollbar2.config(command=self.consoleHist.yview)\n\n\n\t\t#add the new labels also\n\t\tframeD=Frame(self.root)\n\t\tframeD.grid(row=0,column=2,pady=20,sticky=\"n\")\n\t\t#Damages\n\t\tDAMAGES = [\n\t\t\t(\"Shear cracking\", \"Scrack\"),\n\t\t\t\t(\"Flexural cracking\", \"Fcrack\"),\n\t\t\t\t(\"Concrete spalling\", \"spal\"),\n\t\t\t\t(\"Concrete core crushing\", \"contcrush\"),\n\t\t\t(\"Longitudinal bar buckling\", \"LbarB\"),\n\t\t\t(\"Longitudinal bar fracture\", \"LbarF\"),\n\t\t\t(\"Failure of confining hoops/ties\", \"FailHopp\"),\n\t\t\t(\"Anchorage/connection failure\", \"AnchFail\"),\n\t\t\t(\"Lap splice failure\", \"LapSFail\"),\n\t\t\t(\"Distributed plastic hinging\", \"DistPlas\"),\n\t\t\t(\"Concentrated flexural cracking\", \"ConcFlex\"),\n\t\t\t(\"Global buckling/instability\", \"GlobalBuck\"),\n\t\t\t(\"Shear/diagonal failure\", \"ShearFail\"),\n\t\t\t(\"Shear/compression failure\", \"ShearCompFail\"),\n\t\t\t(\"Interface sliding\", \"IntSlid\"),\n\t\t\t(\"Interaction b/w infill and frame\", \"Interac\"),\n\t\t\t(\"Slab fracture\", \"SlabFrac\"),\n\t\t\t(\"Punching shear failure\", \"PunchShearFrac\"),\n\t\t\t(\"Unseating/collapse of stairs\", \"Unseating\"),\n\t\t\t(\"Pounding\", \"Pounding\"),\n\t\t\t(\"Differential settlement\", \"DiffSett\"),\n\t\t\t(\"Residual displacement\", \"ResidualDisp\"),\n\t\t\t(\"soft story fail\", \"SoftStoryFail\"),\n\t\t\t(\"Partial/full collapse\", \"Collapse\"),\n\t\t\t]\n\t\t#VARIABLE FOR DAMAGE SELECTION\n\t\tself.DamageStr=tk.StringVar()\n\t\tself.DamageStr.set(\"Damage Label\") # initialize\n\t\tl = tk.Label(frameD,borderwidth=2, relief=\"groove\", text=\"Type of Damage\").grid(row=0,column=2,sticky=\"nw\")\n\t\tr=1\n\t\tfor text, mode in DAMAGES:\n\t\t\tself.panelB = tk.Radiobutton(frameD, text=text, variable=self.DamageStr, value=text,command=self.DamageSel)\n\t\t\tself.panelB.grid(row=r,column=2,pady=2,sticky=\"w\")\n\t\t\tr=r+1\n\t\t\t\n\n\t\t\n\t\tframeS=Frame(root)\n\t\tframeS.grid(row=0,column=3,pady=20, padx=10,sticky=\"n\")\n\t\t#Structures\n\t\tSTRUCTURES = [\n\t\t\t\t(\"short/captive column\", \"Scrack\"),\n\t\t\t\t(\"slender column\", \"Fcrack\"),\n\t\t\t\t(\"structural wall\", \"spal\"),\n\t\t\t\t(\"infill wall\", \"contcrush\"),\n\t\t\t(\"tilt-up precast panel\", \"LbarB\"),\n\t\t\t(\"joint-column connection\", \"LbarF\"),\n\t\t\t(\"beam\", \"FailHopp\"),\n\t\t\t(\"coupling beam\", \"AnchFail\"),\n\t\t\t(\"foundation beam\", \"LapSFail\"),\n\t\t\t(\"floor diaphragm/slab\", \"DistPlas\"),\n\t\t\t(\"frame\", \"ConcFlex\"),\n\t\t\t(\"scissor stairs\", \"GlobalBuck\"),\n\t\t\t(\"corbel/support\", \"ShearFail\"),\n\t\t\t(\"cantilevered balcony\", \"ShearCompFail\"),\n\t\t\t(\"construction joint\", \"IntSlid\"),\n\t\t\t(\"full Story\", \"Interac\"),\n\t\t\t(\"full/partial building\", \"SlabFrac\"),\n\t\t\t(\"unknow\", \"PunchShearFrac\"),\n\t\t] \t\t\n\t\t#VARIABLE FOR STRUCTURES\n\t\tself.StructureStr=tk.StringVar()\n\t\tself.StructureStr.set(\"Structure Label\") # initialize\n\t\tl1 = tk.Label(frameS,borderwidth=2, relief=\"groove\", text=\"Type of Structure\").grid(row=0,column=3,sticky=\"nw\")\n\t\tr=1\n\t\tfor text, mode in STRUCTURES:\n\t\t\tself.panelC = tk.Radiobutton(frameS, text=text, variable=self.StructureStr, value=text,command=self.StructureSel)\n\t\t\tself.panelC.grid(row=r,column=3,pady=4,sticky=\"w\")\n\t\t\tr=r+1\n\t\t\n\n\t\t#Add the delete New Label and Delete Label to screen\n\t\tl2 = tk.Label(frameM,borderwidth=2, relief=\"groove\", text=\"Create a New Label\").grid(row=14,column=1,sticky=\"n\")\n\t\tself.newST=tk.StringVar(frameM, value=self.StructureStr.get())\n\t\tself.newDM=tk.StringVar(frameM, value=self.DamageStr.get())\n\t\tself.textST=tk.Entry(frameM, width=25, textvariable=self.newST).grid(row=15,column=1,sticky=\"n\")\n\t\tself.textDM=tk.Entry(frameM, width=25, textvariable=self.newDM).grid(row=16,column=1,sticky=\"n\")\n\n\t\t#label History\n\t\tself.labelHist=tk.Listbox(frameM, width=50, height=5)\n\t\tself.labelHist.grid(row=17,column=1,pady=5,sticky=\"ns\")\n\t\tself.scrollbar=Scrollbar(frameM,orient=VERTICAL)\n\t\tself.scrollbar.grid(row=17, column=2,sticky=N+S)\n\t\tself.labelHist.config(yscrollcommand=self.scrollbar.set)\n\t\tself.scrollbar.config(command=self.labelHist.yview)\n\n\t\tself.labelHist.insert(10,\"New Label History list:\")\n\t\t#read This from a file\n\t\tfileHistLabel=open(\"histlabel.txt\",\"r\")\n\t\tfor item in fileHistLabel:\n\t\t\titem=item[:-1] #erases the stupid /0 end of string char\n\t\t\tself.labelHist.insert(20,item)\n\t\tfileHistLabel.close()\n\t\t#button that creates label once you are done entering values Necesary???\n\t\tdoneButton=tk.Button(frameM,text=\"Done Creating Label\", command= self.create_new_label)\n\t\tdoneButton.grid(row=18,column=1,pady=10,sticky=\"n\")\n\n\t\t#add the save Image/ Exit\n\t\tl4=tk.Label(frameM,borderwidth=2, relief=\"groove\",text=\"Save/exit Options\").grid(row=19,column=1,pady=15,sticky=\"n\")\n\t\t\n\t\tbuttonE = tk.Button(frameM, text=\"Save and Exit\", command=self.save_exit).grid(row=20,column=1,sticky=\"n\")\n\t\tbuttonC = tk.Button(frameM, text=\"Cancel (DO NO SAVE)\", command=self.exit).grid(row=21,column=1,sticky=\"n\")\n\n\t#selects the Damage Label\n\tdef DamageSel(self):\n\t\tpass\n \n\t#select the structure label\n\tdef StructureSel(self):\n\t\tpass\n\n\tdef _draw_image(self, path):\n\t\t#write to console hist name of file\n\t\tself.consoleHist.insert(20,os.path.basename(path)+\"\\n\")\n\t\tself.im = Image.open(path)\n\t\tself.tk_im = ImageTk.PhotoImage(self.im)\n\t\tself.canvas.create_image(0,0,anchor=\"nw\",image=self.tk_im)\n\t\tself.ImageSize=self.im.size \n\t\t#make size of canvas same as image\n\t\tself.canvas.config(width=self.ImageSize[0], height=self.ImageSize[1])\n\t\tself.ImageLoaded=1\n\t\t\n\n\tdef ImageNext(self):\n\t#save stuff from Image first, than load the new Image\n\t\tself.save()\n\t\t#erase stuff on the console\n\t\tself.consoleHist.delete(0,END)\n\t\tif self.ImageListIndex < len(self.ImageList):\n\t\t\t\n\t\t\tpathNext= self.ImageList[self.ImageListIndex]\n\t\t\tdirpath=os.path.dirname(self.path)\n\t\t\tself._draw_image(dirpath+'/'+pathNext)\n\t\t\t#make the new picture the path\n\t\t\tself.path=dirpath+'/'+pathNext\n\t\t\t#draw the labels\n\t\t\tself.pathText=os.getcwd()+\"/Out/Output.txt\"\n\t\t\tself.open_fileText()\n\t\t\tself.ImageListIndex=self.ImageListIndex+1\n\t\telse:\n\t\t\troot.quit()\n\t\n\tdef on_button_press(self, event):\n\t\t# save mouse drag start position\n\t\tself.start_x = event.x\n\t\tself.start_y = event.y\n\n\t\t# create rectangle, initial dot if not erasing it but only if there is an image already loaded\n\t\tif self.ImageLoaded==1:\n\t\t\tif self.erase == 0:\n\t\t\t\t\tself.rect = self.canvas.create_rectangle(self.x, self.y, 1, 1, outline=\"red\")\n\t\t\t\t\tself.testDM=self.canvas.create_text(self.start_x,self.start_y-10,fill=\"red\", font=\"Times 10\", text=self.DamageStr.get())\n\t\t\t\t\tself.testST=self.canvas.create_text(self.start_x,self.start_y,fill=\"red\", font=\"Times 10\", text=self.StructureStr.get())\n\t\t\t\t\t#add recId to a list so then it can be erased\n\t\t\t\t\tself.rec_id.append(self.rect)\n\t\t\t\t\tself.text_id_DM.append(self.testDM)\n\t\t\t\t\tself.text_id_ST.append(self.testST)\n\t\t\telse:\n\t\t\t\t#if delete rec pressed than check if there is a rectangle to be erased\n\t\t\t\tself.collision(self.start_x,self.start_y)\n\n\tdef on_move_press(self, event):\n\t\tif self.ImageLoaded==1:\n\t\t\tcurX, curY = (event.x, event.y)\n\t\t\t# expand rectangle as you drag the mouse if not erasing\n\t\t\tif self.erase == 0:\n\t\t\t\tself.canvas.coords(self.rect, self.start_x, self.start_y, curX, curY)\n\n\tdef on_button_release(self, event):\n\t#show rec coord and labels on console self.consoleHist.insert(20,self.DamageStr.get())\n\t#save rect to out\n\t\tif self.ImageLoaded==1:\n\t\t\tif self.erase==0:\n\t\t\t\t#erase label if less than 3 pixel width or height\n\t\t\t\tif abs(self.start_x - event.x) <=3 or abs(self.start_y - event.y) <=3 :\n\t\t\t\t\tlast=len(self.rec_id) -1\n\t\t\t\t\t#delete rectangle and labels\n\t\t\t\t\tself.canvas.delete(self.rec_id[last])\n\t\t\t\t\tdel self.rec_id[last]\n\t\t\t\t\tself.canvas.delete(self.text_id_DM[last])\n\t\t\t\t\tdel self.text_id_DM[last]\n\t\t\t\t\tself.canvas.delete(self.text_id_ST[last])\n\t\t\t\t\tdel self.text_id_ST[last]\n\t\t\t\telse:\t \n\t\t\t\t\ttext=\"rect:\" + str(self.start_x)+\" \"+str(self.start_y)+\" \"+str(event.x)+\" \"+str(event.y)+\" \"+ self.DamageStr.get()+ \" \"+ self.StructureStr.get()+\"\\n\"\n\t\t\t\t\t#write to console history\n\t\t\t\t\tself.consoleHist.insert(20,text)\n\t#check this function\t\n\tdef collision(self,x,y):\n\t\tprint (len(self.rec_id))\n\t\t\n\t\tfor rec in range(len(self.rec_id)):\n\t\t\t#print rec\n\t\t\tpt=self.canvas.coords(self.rec_id[rec])\n\t\t\tdistance= sqrt((pt[0]-x)**2+(pt[1]-y)**2)\n\t\t\tif distance< 5:\n\t\t\t#create a text to search on the \n\t\t\t\tself.recErase=\"rect:\" + str(int(ceil(pt[0])))+\" \"+str(int(ceil(pt[1])))+\" \"+str(int(ceil(pt[2])))+\" \"+str(int(ceil(pt[3])))+\" \"+ \"\\n\"\n\t\t#self.recErase=\"rect:\" + str(pt[0])+\" \"+str(pt[1])+\" \"+str(pt[2])+\" \"+str(pt[3])+\" \"+ \"\\n\" \n\t\t#delete rectangle and labels\n\t\tself.canvas.delete(self.rec_id[rec])\n\t\tdel self.rec_id[rec]\n\t\tself.canvas.delete(self.text_id_DM[rec])\n\t\tdel self.text_id_DM[rec]\n\t\tself.canvas.delete(self.text_id_ST[rec])\n\t\tdel self.text_id_ST[rec]\n\t\t\n\t\t#erase from list\n\t\t# get a list of listbox lines\n\t\ti=0\n\t\ttemp_list = list(self.consoleHist.get(0, tk.END))\n\t\tfor item in temp_list:\n\t\t\tprint (item[0:20])\n\t\t\tprint (self.recErase[0:20])\n\t\t\tif item[0:20] == self.recErase[0:20]:\n\t\t\t\tdel temp_list[i]\n\t\t\ti=i+1\n\t\t#write the temp list back to consoleHist\n\t\tself.consoleHist.delete(0,END)\n\t\tfor item in temp_list:\n\t\t\tself.consoleHist.insert(20,item)\n\t\t\t\n\t#delete last label/rectangle entered\n\tdef deleteStart(self):\n\t\tself.erase=1\n\t\n\tdef deleteEnd(self):\n\t\tself.erase=0\n\t\n\t#Create the new Structure+Damage Label\n\t#allows to select name from the radio button just in case one one of the entries needs to change\n\tdef create_new_label(self):\n\t#set label to the new one created\n\t\tself.DamageStr.set(self.newDM.get())\n\t\tself.StructureStr.set(self.newST.get())\n\t\twith open(\"histlabel.txt\", \"a+\") as text_file:\n\t\t\t\ttext_file.write(self.newDM.get()+\"\\n\")\n\t\t\t\ttext_file.write(self.newST.get()+\"\\n\")\n\n\t\t#add to history\n\t\tself.labelHist.insert(20, self.StructureStr.get()+\" \"+self.DamageStr.get())\n\n\t#function to save the annotations for the PASCAL VOC FORM so the tags can be used in Tensorflow \n\tdef create_xml(self):\n\t# get a list of listbox lines from the console\n\t\ttemp_list = list(self.consoleHist.get(0, tk.END))\n\t\n\t#save label Annotations\n\t\tdirpath=os.path.dirname(self.path)\n\t\tImagefolder=os.path.basename(dirpath)\n\t\tImagefilename=os.path.basename(self.path)\n\t\t#change filename to xml\n\t\tindex=Imagefilename.index('.')\n\t\txmlfilename=Imagefilename[0:index]+\".xml\"\n\t\tp=\"annotations/\"+xmlfilename\n\t\twith open(p, \"w\") as text_file:\n\t\t\ttext_file.write(\"\\n\")\n\t\t\t\n\t\t\ttext_file.write(\"\\t\")\n\t\t\ttext_file.write(Imagefolder) #filename no path\n\t\t\ttext_file.write(\"\\n\")\n\t\t\t\n\t\t\ttext_file.write(\"\\t\")\n\t\t\ttext_file.write(Imagefilename) #filename no path\n\t\t\ttext_file.write(\"\\n\")\n\t\t\t\n\t\t\ttext_file.write(\"\\t\\n\")\n\t\t\ttext_file.write(\"\\t\\t\")\n\t\t\ttext_file.write(str(self.ImageSize[0])) \n\t\t\ttext_file.write(\"\\n\")\n\t\t\t\n\t\t\ttext_file.write(\"\\t\\t\")\n\t\t\ttext_file.write(str(self.ImageSize[1])) \n\t\t\ttext_file.write(\"\\n\")\n\n\t\t\ttext_file.write(\"\\t\\t\")\n\t\t\ttext_file.write(\"3\") \n\t\t\ttext_file.write(\"\\n\")\n\t\t\ttext_file.write(\"\\t\\n\")\n\t\t\ttext_file.write(\"\\t\")\n\t\t\ttext_file.write(\"0\") \n\t\t\ttext_file.write(\"\\n\")\n\t\t\t\n\t\t\t\t\n\t\t\tfor line in temp_list:\n\t\t\t\t#if line statrt with rec than is a rectangles and create an obj\n\t\t\t\t#create the xml bound box\n\t\t\t\tif 'rect'==line[0:4]:\n\t\t\t\t\t#ERASE THE WORD RECT: FIRST from line\t\n\t\t\t\t\twords=line[5:].split()\n\t\t\t\t\n\t\t\t\t\t#numElem=(len(words)-4)/2\n\t\t\t\t\t#strDM=' '.join(words[4:(4+numElem)])\n\t\t\t\t\t#strST=' '.join(words[4+numElem:])\n\t\t\t\t\t\n\t\t\t\t\ttext_file.write(\"\\t\\n\")\n\t\t\t\t\ttext_file.write(\"\\t\\t\")\n\t\t\t\t\ttext_file.write(' '.join(words[4:]))\n\t\t\t\t\ttext_file.write(\"\\n\")\n\t\t\t\t\ttext_file.write(\"\\t\\t\\n\")\n\t\t\t\t\ttext_file.write(\"\\t\\t\\t\")\n\t\t\t\t\ttext_file.write(str(words[0]))\n\t\t\t\t\ttext_file.write(\"\\n\")\n\t\t\t\t\ttext_file.write(\"\\t\\t\\t\")\n\t\t\t\t\ttext_file.write(str(words[1]))\n\t\t\t\t\ttext_file.write(\"\\n\")\n\t\t\t\t\ttext_file.write(\"\\t\\t\\t\")\n\t\t\t\t\ttext_file.write(str(words[2]))\n\t\t\t\t\ttext_file.write(\"\\n\")\n\t\t\t\t\ttext_file.write(\"\\t\\t\\t\")\n\t\t\t\t\ttext_file.write(str(words[3]))\n\t\t\t\t\ttext_file.write(\"\\n\")\n\t\t\t\t\ttext_file.write(\"\\t\\t\\n\")\n\t\t\t\t\ttext_file.write(\"\\t\\n\")\n\n\n\t\t\ttext_file.write(\"\\n\")\n \n\t\n\t#save image and exit progrma\n\tdef save(self):\n\t# get a list of listbox lines\n\t\ttemp_list = list(self.consoleHist.get(0, tk.END))\n\t\t# add a trailing newline char to each line, no need\n\t\t#temp_list = [chem + '\\n' for chem in temp_list]\n\t\t# save to file use path_out\n\t\tindex=self.path.index('.')\n\t\toutfilename=self.path[0:index]+\"-out.jpeg\"\n\n\t\tif self.path_out==\"a\":\n\t\t\tp=\"Output.txt\"\n\t\t\tp1=outfilename\n\t\telse:\n\t\t\tp=os.path.join(os.getcwd(),self.path_out, \"Output.txt\")\n\t\t\t#print p\n\t\t\tfilename=os.path.basename(self.path)\n\t\t\tindex2=filename.index('.')\n\t\t\tfilename=filename[0:index2]+\"-out.jpeg\"\n\t\t\tp1=os.path.join(self.path_out,filename)\n\t\t\t#print p1\n\t\ttemp_list = list(self.consoleHist.get(0, tk.END))\n\t\twith open(p, \"a+\") as text_file:\n\t\t\ttext_file.writelines(temp_list)\n\t\t#for WINDOWS ImageGrab(0,0,self.width,self.height).save(\"out.jpeg\")\n\t\twidget=self.canvas \n\t\tx=root.winfo_rootx()+widget.winfo_x()\n\t\ty=root.winfo_rooty()+widget.winfo_y()\n\t\tx1=x+widget.winfo_width()\n\t\ty1=y+widget.winfo_height() \n\t\tImageGrab.grab(bbox=(x,y,x1,y1)).save(p1)\n\t\tself.create_xml()\n\n\t#save image and exit program\n\tdef save_exit(self):\n\t\t#call save\n\t\tself.save()\n\t\t#create xml file\n\t\tself.create_xml()\n\t\t#exit\n\t\tsys.exit()\n\n\t#exit without saving changes\n\tdef exit(self):\n\t\tsys.exit()\n\n\tdef open_file(self):\n\t# open a file chooser dialog and allow the user to select an input\n\t\topts = {}\n\t\topts['filetypes'] = [('Supported types',('.jpeg','.jpg','.JPG','.JPEG')),\n\t\t\t\t\t\t\t\t ('EEG files','.eeg'),('all files','.*')]\n\t\t\t\n\t\tself.path = filedialog.askopenfilename(title='Enter Input File',**opts)\n\t\tif self.path == '': return\n\t\t\t\n\t\tself._draw_image(self.path) \n\n\t#open file with tags and redraw them on the original image, now they are erasable\n\tdef open_fileText(self):\n\t# open a file chooser dialog and allow the user to select an input\n\t\topts = {}\n\t\topts['filetypes'] = [('Supported types',('.txt'))]\n\t\t\t\n\t\tif self.Out==0:\n\t\t\tself.pathText = filedialog.askopenfilename(title='Enter File with labels for Image',**opts)\n\t\t\tif self.pathText == '': return\n\t\t\t\n\t\t\t#create a list qith all images names on the directory the file is selected \n\t\t\tdirpath=os.path.dirname(self.path)\n\t\t\tlistin=os.listdir(dirpath)\n\t\t\tfor file in listin:\n\t\t\t\t#enter the name of the file into a list\n\t\t\t\t#the next element of the list will be loaded when Next button is clicked \n\t\t\t\tself.ImageList.append(file) \n\t\t\tself.Out=1 \n\t\t\t\n\t\t#Fill Console History with labels for Image\n\t\tfin = open(self.pathText, 'r')\n\t\tftemp=open(os.path.dirname(self.pathText)+'/temp.txt' ,'w')\n\n\t\tmarkerStart=-1\n\t\tfor line in fin:\n\t\t\tif markerStart==0:\n\t\t\t\tif 'rect'==line[0:4]:\n\t\t\t\t\t#erase all rectangles from file we will write them all together at end with save\n\t\t\t\t\tself.consoleHist.insert(20,line)\n\t\t\t\t\t#recreate the rectangle again\n\t\t\t\t\t#ERASE THE WORD RECT: FIRST\t\n\t\t\t\t\twords=line[5:].split()\n\t\t\t\t\t#paint a rectangle\n\t\t\t\t\tself.rect = self.canvas.create_rectangle(words[0], words[1], words[2], words[3], outline=\"red\")\n\t\t\t\t\t#add recId to a list so then it can be erased later\n\t\t\t\t\tself.rec_id.append(self.rect)\n\t\t\t\t\t#Add the labels\n\t\t\t\t\t#since more than two words can belong to label first calculate how many strings add them to label divided in two\n\t\t\t\t\tnumElem=(len(words)-4)/2\n\t\t\t\t\tstrDM=' '.join(words[4:(4+numElem)])\n\t\t\t\t\tstrST=' '.join(words[4+numElem:])\n\t\t\t\t\tself.testDM=self.canvas.create_text(words[0],int(words[1])-10,fill=\"red\", font=\"Times 10\", text=strDM)\t\t\t\t\n\t\t\t\t\tself.testST=self.canvas.create_text(words[0],words[1],fill=\"red\", font=\"Times 10\", text=strST)\n\t\t\t\t\tself.text_id_DM.append(self.testDM)\n\t\t\t\t\tself.text_id_ST.append(self.testST)\n\t\t\t\t\t\n\t\t\t\t\t#erase info from file we will add all together at the end\n\t\t\t\t\tline=line.replace(line,\"\")\n\t\t\t\telse:\n\t\t\t\t\t# we are done no more labels for the image needs to be displayed\n\t\t\t\t\tmarkerStart=-1 \t\t\n\t\t\t#if self.path in line:\n\t\t\tif os.path.basename(self.path) in line: #search for filename (no fullpath) on file\n\t\t\t\t#erase title\n\t\t\t\tline=line.replace(line,\"\")\n\t\t\t\tmarkerStart=0\t\n\t\t\tftemp.write(line) #probably better to not replace line and only write when necessary\n\t\tfin.close()\n\t\tftemp.close()\n\t\t#rename the old with the new file, this is an OS system call\n\t\t#erase file so it can be renamed\n\t\tos.remove(self.pathText)\n\t\tos.rename(os.path.dirname(self.pathText)+'/temp.txt' ,self.pathText)\n\t\t\t\n\t#select where to save all outputs\t\n\tdef out_folder(self):\n\t#output folder by default is same as the input images folder\n\t#out.txt file contains all labels and by default will be on the same folder as the \n\t\tself.path_out = filedialog.askdirectory(title='Enter Output Directory')\n\t\n\t\t\n\tdef help(self):\n\t\tmessagebox.showinfo(\"Help\",\"For Instructions of how to use CITT:\\nhttps://github.com/mpantoja314/Image\")\n\tdef about(self):\n\t\tmessagebox.showinfo(\"Information\",\"C.I.T.T Civil Infrastructure Tagging Tool: \\nVersion 1.0. \\nUpdated October 2017. \\nDeveloped by:\\nMaria Pantoja and Anahid Behrouzi \\nCalPoly SLO\")\n \n#MAIN LOOP\nif __name__== '__main__':\n\troot=tk.Tk()\n\tgui=Gui(root)\n\troot.title(\"C.I.T.T. Civil Infrastructure Tagging Tool\");\n\t#root.geometry(\"1000x1500+0+0\")\n\timgicon = ImageTk.PhotoImage(file=os.path.join(os.getcwd(),'logo.ico'))\n\troot.tk.call('wm', 'iconphoto', root._w, imgicon)\n\troot.configure(background='blue')\n\troot.mainloop()\n\t\n\t\n","sub_path":"ReviewTag.py","file_name":"ReviewTag.py","file_ext":"py","file_size_in_byte":20841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"177388207","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\nimport collections\nimport logging\nlogger = logging.getLogger(__name__)\n\nfrom django.core.exceptions import ValidationError\n\n\nclass BaseImporter:\n \"\"\"\n Importer users Retriever to get FileLike object with raw data and pass it to the Parser.\n When parser returns arguments for models, Importer creates models\n \"\"\"\n parser_class = None\n retriever = None\n model = None\n\n def __init__(self, model=None, parser_class=None, retriever=None):\n if model:\n self.model = model\n if parser_class:\n self.parser_class = parser_class\n self.parser = self.parser_class(self.model)\n if retriever:\n self.retriever = retriever\n\n def import_data(self):\n \"\"\"\n Main method for importing data\n \"\"\"\n data_obj = self.retriever.get_raw_data()\n parsed_data = self.parser.parse(data_obj)\n if isinstance(parsed_data, collections.Iterable):\n for item in parsed_data:\n self.create_model(item)\n elif isinstance(parsed_data, dict):\n self.create_model(parsed_data)\n\n def create_model(self, item_data):\n \"\"\"\n\n :param item_data: dictionary, where:\n - keys are model fields\n - values are a data for that fields. If field is Foreign key or ManyToMany field,\n value should contain only id of relation.\n All exceptions are handled and logged\n :return:\n \"\"\"\n try:\n self.model.objects.create(**item_data)\n except ValidationError as exc:\n logger.error(\"Error during import model: {0}\".format(exc))\n","sub_path":"django_importer/importers/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"628674546","text":"import numpy\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom losses.focal import criterion_margin_focal_binary_cross_entropy\n\nclass DiceLoss(nn.Module):\n def __init__(self, weight=None, size_average=True, smooth=1):\n super(DiceLoss, self).__init__()\n self.smooth = smooth\n\n def forward(self, inputs, targets):\n \n #comment out if your model contains a sigmoid or equivalent activation layer\n inputs = torch.sigmoid(inputs) \n \n #flatten label and prediction tensors\n inputs = inputs.view(-1)\n targets = targets.view(-1)\n \n intersection = (inputs * targets).sum() \n dice = (2.*intersection + self.smooth)/(inputs.sum() + targets.sum() + self.smooth) \n \n return 1 - dice\n \nclass HybridLoss(nn.Module):\n def __init__(self, alpha=1, beta=1, weight=None, size_average=True, smooth=1):\n super(HybridLoss, self).__init__()\n self.smooth = smooth\n self.alpha = alpha\n self.beta = beta\n self.focal = criterion_margin_focal_binary_cross_entropy\n self.dice = DiceLoss(weight=weight, size_average=size_average)\n\n def forward(self, inputs, targets):\n \n focal_loss = self.focal(inputs, targets)\n dice_loss = self.dice(inputs, targets)\n\n \n return self.alpha*focal_loss + self.beta*dice_loss","sub_path":"losses/dice.py","file_name":"dice.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"501011191","text":"from keras.models import load_model\r\nfrom PIL import Image\r\nimport numpy as np\r\nimport os\r\n\r\n### CHECK IT BEFORE RUNNING ###\r\n\r\ndataset_way = 'partirnated_dataset/' ### way of dataset folder\r\nmodel_name = 'good_model.hdf5'\r\n###############################\r\n\r\n\r\ndef get_names():\r\n names = os.listdir('./' + dataset_way)\r\n names.sort()\r\n return names\r\n\r\n\r\ndef Test_model(model, w, h):\r\n X = load_image(w, h)\r\n y = model.predict_classes(X)\r\n print(y)\r\n\r\n\r\ndef load_image(w, h):\r\n names = get_names()\r\n pict_count = len(names)\r\n pixels = np.zeros(pict_count * w * h * 3).reshape(pict_count, w, h, 3)\r\n\r\n for pict in range(len(names)):\r\n name = dataset_way + names[pict]\r\n img_start = Image.open(name)\r\n img = Image.new(\"RGBA\", img_start.size)\r\n img.paste(img_start)\r\n img = img.resize((w, h))\r\n pix = img.load()\r\n for line in range(h):\r\n for column in range(w):\r\n pixels[pict, line, column, 0] = np.array(pix[line, column][0])\r\n pixels[pict, line, column, 1] = np.array(pix[line, column][1])\r\n pixels[pict, line, column, 2] = np.array(pix[line, column][2])\r\n\r\n pixels = pixels.astype('float32')\r\n pixels = pixels / 255.0\r\n return pixels\r\n\r\n\r\nmodel = load_model(model_name)\r\nTest_model(model, 32, 32)","sub_path":"Test_model.py","file_name":"Test_model.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"5487529","text":"#pressure test for maxium number of balls\n\nimport pygame\npygame.init()\nimport math, random, sys\n\n\n#consts\ngame_fps = 60\ngame_res = screen_width, screen_height = 1280, 720\nbkg_color = 0xFFFFFF\nmax_speed = 5\nnum_faces = 2000\n\n#handles\nscreen = pygame.display.set_mode((screen_width, screen_height))\nmain_clk = pygame.time.Clock()\n\n\n#house cleaning\nscreen.fill(bkg_color)\nballs = []\npygame.display.set_caption('TITLE')\n\n#class\nclass Balls(object):\n ball_img = pygame.image.load(\"face_1.gif\").convert()\n def __init__(self, index, max_speed):\n self.index = index\n self.image = self.ball_img\n self.dx = random.randint(1,max_speed)\n self.dy = random.randint(1,max_speed)\n self.pos = self.image.get_rect()\n self.pos.x = random.randint(0, screen_width - self.pos.width)\n self.pos.y = random.randint(0, screen_height - self.pos.height)\n \n def update(self):\n #move\n self.pos.move_ip(self.dx, self.dy)\n #collision\n if self.pos.left < 0 or self.pos.right > screen_width:\n self.dx = -self.dx\n\n if self.pos.top < 0 or self.pos.bottom > screen_height:\n self.dy = -self.dy\n\n def draw(self, screen):\n screen.blit(self.image, self.pos)\n\n def debug_print(self):\n print(self.index, self.dx, \\\n self.dy, self.pos.x, self.pos.y)\n\n#construct balls\nfor i in range(num_faces):\n balls.append(Balls(i, max_speed))\n\n#main loop\nwhile 1:\n #events\n for event in pygame.event.get():\n if event.type == pygame.QUIT: sys.exit()\n\n #draw\n screen.fill(bkg_color)\n for b in balls:\n b.update()\n b.draw(screen)\n #render\n pygame.display.flip()\n main_clk.tick(game_fps)\n print(main_clk.get_fps())","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"82727486","text":"import os\r\nimport time\r\n \r\ndef WaitForDownload(fileName,timer=150):\r\n counter = 0\r\n oldFileSize = -1\r\n while counter < timer:\r\n fileSize = int(os.stat(fileName).st_size)\r\n if fileSize == oldFileSize and oldFileSize != 0:\r\n counter += 1\r\n else:\r\n counter = 0\r\n oldFileSize = fileSize\r\n time.sleep(0.01)\r\n return True\r\n","sub_path":"sizecheck.py","file_name":"sizecheck.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"388346093","text":"import psycopg2\nfrom flask import Flask, request, jsonify,json\nfrom config import config\n\napp = Flask(__name__)\n\nconn = None\ncur=None\nresponse=None\n\ndef connect():\n \"\"\" Connect to the PostgreSQL database server \"\"\"\n \n try:\n # read connection parameters\n params = config()\n\n # connect to the PostgreSQL server\n print('Connecting to the PostgreSQL database...')\n conn = psycopg2.connect(**params)\n\n # create a cursor\n cur = conn.cursor()\n\n # execute a statement\n print('PostgreSQL database version:')\n cur.execute('SELECT version()')\n\n # display the PostgreSQL database server version\n db_version = cur.fetchone()\n print(db_version)\n\n \n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n \n\n\n@app.route('/login', methods=[\"POST\"])\ndef login():\n connect()\n data = request.json\n \n cur.execute('SELECT name, phone, pass FROM public.users WHERE phone =? AND pass =?',data['phone'],data['pass'])\n columns = ('name', 'phone', 'pass')\n rows=cur.fetchone()\n\n if cur == None:\n results = []\n for row in rows:\n results.append(dict(zip(columns, row)))\n \n response = app.response_class(\n response=json.dumps(results),\n status=200,\n mimetype='application/json'\n )\n else:\n response = app.response_class(\n response=json.dumps(\"{'status':'0'}\"),\n status=200,\n mimetype='application/json'\n )\n\n print(results)\n return response\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"429872350","text":"import resources\nimport pyglet\nfrom GameObjects import PlayerObject\nfrom MinionObjects import Cowboy, Blob\nfrom pyglet.window import key\nfrom Time import Timer\nfrom shoot import hit_cowboy, hit_blob\nfrom pyglet.window import mouse\nimport sys\n\n# Window setting\nwindow = pyglet.window.Window(width=1200, height=900, caption=\"Space Invaders\", resizable=False)\nwindow.set_location(400, 100)\nframe_rate = 1/16\n\n# Make background\nglobal background_sprite\nbackground = pyglet.resource.image('battleback1.png')\nbackground.width = 1200\nbackground.height = 900\nbackground_sprite = pyglet.sprite.Sprite(img=background, x=0, y=0)\n\n# Create player\nplayer = PlayerObject(600, 0, \"main2.png\")\n\n# Game settings\ncharacter_speed = 5.0\nspawn_speed = 4 # seconds\n\n# Cowboy handle\ncowboys = []\nnumber = 2\ncowboyBatch = pyglet.graphics.Batch()\n\n# Blob handle\nblobs = []\nblobnumber = 1\nblobBatch = pyglet.graphics.Batch()\n\n# Other\npressing_keys=[]\n\n\ndef spawn(dt):\n global number\n for i in range(number):\n cowboy = Cowboy(cowboyBatch, \"Cowboy2.png\")\n cowboys.append(cowboy)\n number += 1\n\n for i in range(blobnumber):\n blob = Blob(blobBatch, \"blob.png\")\n blobs.append(blob)\n\n\ndef moveCharacter(dt):\n if pyglet.window.key.LEFT in pressing_keys:\n player.move(-character_speed, 0)\n if pyglet.window.key.RIGHT in pressing_keys:\n player.move(character_speed, 0)\n if pyglet.window.key.UP in pressing_keys:\n player.move(0, character_speed)\n if pyglet.window.key.DOWN in pressing_keys:\n player.move(0, -character_speed)\n\n\n@window.event\ndef on_draw():\n window.clear()\n background_sprite.draw()\n player.sprite.draw()\n for cowboy in cowboys:\n cowboy.draw()\n for blob in blobs:\n blob.draw()\n timer.label.draw()\n\n\n@window.event\ndef on_mouse_press(x, y, button, modifier):\n for cowboy in cowboys:\n if button == mouse.LEFT:\n if hit_cowboy(x, y, cowboy.cowboy_sprite.x, cowboy.cowboy_sprite.y) is True:\n cowboys.remove(cowboy)\n break\n\n for blob in blobs:\n if button == mouse.LEFT:\n if hit_blob(x, y, blob.blob_sprite.x, blob.blob_sprite.y) is True:\n blobs.remove(blob)\n break\n\n\n@window.event\ndef on_key_press(symbol, modifiers):\n pressing_keys.append(symbol)\n\n\n@window.event\ndef on_key_release(symbol, modifiers):\n pressing_keys.remove(symbol)\n\n\ndef update(dt):\n player.update(dt)\n pos = player.update(dt)\n for cowboy in cowboys:\n # if hit(player.sprite.x, player.sprite.y, cowboy.cowboy_sprite.x, cowboy.cowboy_sprite.y) is True:\n #\n cowboy.update(dt, pos)\n\n for blob in blobs:\n blob.update(dt, pos)\n\n on_draw()\n\nif __name__ == \"__main__\":\n timer = Timer()\n pyglet.clock.schedule_interval(update, 1.0/60)\n pyglet.clock.schedule_interval(spawn, spawn_speed)\n pyglet.clock.schedule_interval(moveCharacter, 1.0/60)\n pyglet.clock.schedule_interval(timer.update, 1.0)\n pyglet.app.run()\n","sub_path":"Game/GameWindow.py","file_name":"GameWindow.py","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"54980127","text":"from direct.showbase.ShowBase import ShowBase\nfrom panda3d.core import Lens, LensNode, PerspectiveLens, OrthographicLens\n# from direct.interval.IntervalGlobal import Sequence, Func, Wait, SoundInterval\nfrom ursina.sequence import Sequence, Func, Wait\nfrom direct.interval.IntervalGlobal import SoundInterval\nfrom direct.task.Task import Task\nfrom panda3d.core import NodePath, PandaNode\nfrom panda3d.core import Vec2, Vec3, Point3\nfrom panda3d.core import loadPrcFileData, Filename, AntialiasAttrib\nfrom panda3d.core import PNMImage, Texture\n\nimport sys\nimport os\nimport math\nimport random\nimport inspect\nimport importlib\nimport subprocess\nimport time\nfrom pathlib import Path\n\nfrom ursina import application\nfrom ursina.entity import Entity\nfrom ursina import scene\nfrom ursina import window\nfrom ursina import mouse\nfrom ursina import camera\nfrom ursina import raycaster\nfrom ursina.raycaster import raycast, boxcast\nfrom ursina import color\nfrom ursina.input_handler import held_keys\nfrom ursina import input_handler\n\n\ndef save_prefab(target, name=None, path='prefabs'):\n if not name:\n name = target.name\n\n prefab_path = os.path.join(\n path,\n target.name + '_' + str(target.get_key()) + '.py')\n\n with open(prefab_path, 'w') as file:\n file.write('from ursina import *\\n\\n')\n\n file.write('class ' + name.title() + '_' + str(target.get_key()) + '(Entity):\\n\\n')\n file.write(' def __init__(self):\\n')\n file.write(' super().__init__()\\n')\n\n entities_to_save = list()\n entities_to_save.append(target)\n for e in scene.entities:\n if e.has_ancestor(target):\n entities_to_save.append(e)\n\n for e in entities_to_save:\n if e is target:\n prefix = ' self'\n else:\n prefix = ' self.' + e.name + '_' + str(e.get_key())\n\n color_str = ('(' + str(e.color[0]) + ', '\n + str(e.color[1]) + ', '\n + str(e.color[2]) + ', '\n + str(e.color[3]) + ')')\n\n palette = [item for item in dir(color) if not item.startswith('__')]\n for colorname in palette:\n if getattr(color, colorname) == e.color:\n color_str = 'color.' + colorname\n break\n\n if e is not target:\n file.write(prefix + ' = Entity()' + '\\n')\n\n parent_str = 'self.' + e.parent.name + '_' + str(e.parent.get_key())\n if e.parent == target:\n parent_str = 'self'\n\n file.write(prefix + '.enabled = ' + str(e.enabled) + '\\n'\n + prefix + '.is_editor = ' + str(e.is_editor) + '\\n'\n + prefix + '.name = ' + '\\'' + str(e.name) + '\\'' + '\\n'\n + prefix + '.parent = ' + parent_str + '\\n')\n\n if e.origin != Vec3(0,0,0):\n file.write(prefix + '.origin = ' + vec3_to_string(e.origin) + '\\n')\n if e.position != Vec3(0,0,0):\n file.write(prefix + '.position = ' + vec3_to_string(e.position) + '\\n')\n if e.rotation != Vec3(0,0,0):\n file.write(prefix + '.rotation = ' + vec3_to_string(e.rotation) + '\\n')\n if e.scale != Vec3(1,1,1):\n file.write(prefix + '.scale = ' + vec3_to_string(e.scale) + '\\n')\n\n if e.model:\n file.write(prefix + '.model = ' + '\\'' + os.path.basename(str(e.model))[:4] + '\\'' + '\\n')\n if e.color:\n file.write(prefix + '.color = ' + color_str + '\\n')\n if e.texture:\n file.write(prefix + '.texture = ' + str(e.texture) + '\\n')\n\n file.write(prefix + '.collision = ' + str(e.collision) + '\\n')\n if e.collider:\n file.write(prefix + '.collider = ' + str(e.collider) + '\\n')\n\n\n\n\n\n for s in e.scripts:\n if e is target:\n script_prefix = prefix + '.' + str(s.__class__.__name__).lower()\n else:\n script_prefix = prefix + '_' + str(s.__class__.__name__).lower()\n\n file.write(script_prefix + ' = ' + prefix[8:] + '.add_script(\\'' + s.__class__.__name__ + '\\')\\n')\n\n for var in [item for item in vars(s) if not item.startswith('_')]:\n\n varvalue = getattr(s, var)\n\n if not varvalue:\n continue\n\n print(type(varvalue))\n\n if varvalue.__class__ == Entity:\n if varvalue is target:\n varvalue = 'self'\n else:\n varvalue = str(varvalue.name) + '_' + str(varvalue.get_key())\n\n print('hyhrh')\n file.write(script_prefix + '.' + var + ' = ' + str(varvalue) + '\\n')\n\n print('saved prefab:', path, target.name)\n\ndef _vec3_to_string(vec3):\n string = '(' + str(round(vec3[0], 3)) + ', ' + str(round(vec3[1], 3))\n if vec3[2] is not 0:\n string += ', ' + str(round(vec3[2]), 3)\n string += ')'\n return string\n\n\ndef invoke(function, *args, **kwargs):\n delay = 0\n if 'delay' in kwargs:\n delay = kwargs['delay']\n del kwargs['delay']\n\n if not delay:\n function(*args, **kwargs)\n return function\n\n s = Sequence()\n s.append(Wait(delay))\n s.append(Func(function, *args, **kwargs))\n s.start()\n return s\n\n\ndef destroy(entity, delay=0):\n if delay == 0:\n _destroy(entity)\n return\n\n s = Sequence()\n s.append(Wait(delay))\n s.append(Func(_destroy, entity))\n s.start()\n\ndef _destroy(entity):\n if not entity:\n print('entity is None')\n return\n if entity in scene.entities:\n scene.entities.remove(entity)\n\n if hasattr(entity, 'on_destroy'):\n entity.on_destroy()\n\n if hasattr(entity, 'scripts'):\n for s in entity.scripts:\n del s\n\n if hasattr(entity, 'animations'):\n for anim in entity.animations:\n anim.finish()\n anim.kill()\n\n if hasattr(entity, 'tooltip'):\n destroy(entity.tooltip)\n # entity.tooltip.removeNode()\n\n entity.removeNode()\n\n #unload texture\n # if hasattr(entity, 'texture') and entity.texture != None:\n # entity.texture.releaseAll()\n\n del entity\n\n\ndef import_all_classes(path=application.asset_folder, debug=False):\n path = str(path)\n sys.path.append(path)\n from ursina.string_utilities import snake_to_camel\n from glob import iglob\n imported_successfully = list()\n\n for file_path in iglob(path + '**/*.py', recursive=True):\n if '\\\\build\\\\' in file_path or '__' in file_path:\n continue\n\n rel_path = file_path[len(path):][:-3].replace('\\\\', '.')\n if rel_path.startswith('.'):\n rel_path = rel_path[1:]\n module_name = os.path.basename(file_path).split('.')[0]\n class_name = snake_to_camel(module_name)\n module_name = module_name\n import_statement = 'from ' + rel_path + ' import *'\n\n try:\n exec(import_statement, globals())\n imported_successfully.append(module_name)\n if debug:\n print(import_statement)\n except:\n if debug:\n print(' x', import_statement)\n pass\n\n return imported_successfully\n\n\nfrom ursina.text import Text\ndef print_on_screen(text):\n text_entity = Text(\n # parent = camera.ui,\n text = str(text),\n position = window.top_left,\n origin = (-.5, .5),\n # scale = (.1, .1)\n )\n destroy(text_entity, 1)\n\n\nif __name__ == '__main__':\n\n from ursina import *\n app = Ursina()\n def test_func(item, x=None, y=None):\n print(item, x, y)\n\n test_func('test')\n invoke(test_func, 'test', delay=.1)\n invoke(test_func, 'test1', 1, 2, delay=.2)\n invoke(test_func, 'test2', x=1, y=2, delay=.3)\n\n app.run()\n","sub_path":"ursina/ursinastuff.py","file_name":"ursinastuff.py","file_ext":"py","file_size_in_byte":8026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"423938202","text":"# Py 2 & 3 support\nfrom __future__ import division, print_function, unicode_literals\n\n# Common Imports\nimport numpy as np\nimport os\n\n# ML Imports\nfrom sklearn.svm import SVC\nfrom sklearn import datasets\n\n# Graph Imports\n# %matplotlib inline # notebook magics\nimport matplotlib.pyplot as plt\nplt.rcParams['axes.labelsize'] = 14\nplt.rcParams['xtick.labelsize'] = 12\nplt.rcParams['ytick.labelsize'] = 12\n\n# Instantiate datasets\nX = iris = datasets.load_iris()\nX = iris[\"data\"][:, (2, 3)]\ny = iris[\"target\"]\n\nsetosa_or_versicolor = (y == 0) | (y == 1)\nX = X[setosa_or_versicolor]\ny = y[setosa_or_versicolor]\n\n# Save directory\nPROJECT_ROOT_DIR = \".\"\n\n# Declare functions\n\n\ndef save_fig(fig_id, tight_layout=True):\n path = os.path.join(PROJECT_ROOT_DIR, \"images\", fig_id + \".png\")\n print(\"Saving figure\", fig_id)\n if tight_layout:\n plt.tight_layout()\n plt.savefig(path, format='png', dpi=300)\n\n\ndef plot_svc_decision_boundary(svm_clf, xmin, xmax):\n w = svm_clf.coef_[0]\n b = svm_clf.intercept_[0]\n x0 = np.linspace(xmin, xmax, 200)\n decision_boundary = -w[0] / w[1] * x0 - b / w[1]\n margin = 1 / w[1]\n gutter_up = decision_boundary + margin\n gutter_down = decision_boundary - margin\n svs = svm_clf.support_vectors_\n plt.scatter(svs[:, 0], svs[:, 1], s=180, facecolors=\"#FFAAAA\")\n plt.plot(x0, decision_boundary, \"k-\", linewidth=2)\n plt.plot(x0, gutter_up, \"k--\", linewidth=2)\n plt.plot(x0, gutter_down, \"k--\", linewidth=2)\n\n\n# Outlier sensitivity\nX_outliers = np.array([[3.4, 1.3], [3.2, 0.8]])\ny_outliers = np.array([0, 0])\nXo1 = np.concatenate([X, X_outliers[:1]], axis=0)\nyo1 = np.concatenate([y, y_outliers[:1]], axis=0)\nXo2 = np.concatenate([X, X_outliers[1:]], axis=0)\nyo2 = np.concatenate([y, y_outliers[1:]], axis=0)\n\nsvm_clf2 = SVC(kernel=\"linear\", C=10**9)\nsvm_clf2.fit(Xo2, yo2)\n\nplt.figure(figsize=(12, 2.7))\n\nplt.subplot(121)\nplt.plot(Xo1[:, 0][yo1 == 1], Xo1[:, 1][yo1 == 1], \"bs\")\nplt.plot(Xo1[:, 0][yo1 == 0], Xo1[:, 1][yo1 == 0], \"yo\")\nplt.text(0.3, 1.0, \"Impossible\", fontsize=24, color=\"red\")\nplt.xlabel(\"Petal length\", fontsize=14)\nplt.ylabel(\"Petal width\", fontsize=14)\nplt.annotate(\n \"Outlier\",\n xy=(X_outliers[0][0], X_outliers[0][1]),\n xytext=(2.5, 1.7),\n ha=\"center\",\n arrowprops=dict(facecolor='black', shrink=0.1),\n fontsize=16,\n)\n\nplt.axis([0, 5.5, 0, 2])\n\nplt.subplot(122)\nplt.plot(Xo2[:, 0][yo2 == 1], Xo2[:, 1][yo2 == 1], \"bs\")\nplt.plot(Xo2[:, 0][yo2 == 0], Xo2[:, 1][yo2 == 0], \"yo\")\nplot_svc_decision_boundary(svm_clf2, 0, 5.5)\nplt.xlabel(\"Petal length\", fontsize=14)\nplt.annotate(\n \"Outlier\",\n xy=(X_outliers[1][0], X_outliers[1][1]),\n xytext=(3.2, 0.08),\n ha=\"center\",\n arrowprops=dict(facecolor='black', shrink=0.1),\n fontsize=16,\n)\n\nplt.axis([0, 5.5, 0, 2])\n\nsave_fig(\"sensitivity_to_outliers_plot\")\nplt.show()\n","sub_path":"support_vector_machine/examples/outliers.py","file_name":"outliers.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"216078129","text":"import pickle\nimport troposphere\nfrom troposphere import *\nfrom troposphere.route53 import RecordSetType\nimport troposphere.ecs as ecs\nfrom troposphere.ecs import Service, ContainerDefinition, TaskDefinition, Environment, Cluster\nfrom netaddr import *\nimport troposphere.ec2 as ec2\nfrom troposphere.iam import Role, InstanceProfile\nfrom awacs.aws import Allow, Statement, Principal, Policy\nfrom awacs.sts import AssumeRole\nimport os\n\nregion = 'us-east-2'\n\nip = IPNetwork('239.254.99.0/25')\nip_list = list(ip)\n\necs_template = Template()\n\ncustomer_cluster = ecs.Cluster('CustomerCluster')\nmatching_engine_cluster = ecs.Cluster('MatchingEngineCluster')\nmarket_data_cluster = ecs.Cluster('MarketDataCluster')\nbroker_dealer_cluster = ecs.Cluster('BrokerDealerCluster')\necs_template.add_resource(customer_cluster)\necs_template.add_resource(matching_engine_cluster)\necs_template.add_resource(market_data_cluster)\necs_template.add_resource(broker_dealer_cluster)\n\n#ddog task and service\ndata_dog_environment_api_key = ecs.Environment(Name='API_KEY', Value=os.environ['DD_API_KEY'])\ndata_dog_environment_app_key = ecs.Environment(Name='APP_KEY', Value=os.environ['DD_APP_KEY'])\n\nif region == 'us-west-2':\n eip_list = ['eipalloc-a9f662cd', 'eipalloc-05b57d62', 'eipalloc-62fc6c06', 'eipalloc-e7b42183', 'eipalloc-18c9017f']\n ImageId='ami-3dc2165d'\n HostedZoneId='Z2J9AY0IWC7L8U'\n fileName='aex_us_west_2.json'\n Image='007038732177.dkr.ecr.us-west-2.amazonaws.com/aex:latest'\n Image\nif region == 'us-east-1':\n eip_list = ['eipalloc-f93c46c6', 'eipalloc-7d596542', 'eipalloc-6f5c6050', 'eipalloc-115e622e', 'eipalloc-8a5f63b5']\n ImageId='ami-f66607e1'\n HostedZoneId='Z1W96SO54I67M9'\n fileName='aex_us_east_1.json'\n Image='007038732177.dkr.ecr.us-east-1.amazonaws.com/aex:latest'\nif region == 'us-east-2':\n eip_list = ['eipalloc-ee15ec87', 'eipalloc-6c08f105', 'eipalloc-5a0bf233', 'eipalloc-9e16eff7', 'eipalloc-f816ef91']\n ImageId='ami-704f1515'\n HostedZoneId='Z1W96SO54I67M9'\n fileName='aex_us_east_2.json'\n Image='007038732177.dkr.ecr.us-east-2.amazonaws.com/aex:latest'\necs_instance_sg = ecs_template.add_resource(\n ec2.SecurityGroup(\n \"InstanceSecurityGroup\",\n GroupDescription=\"Allow access to 3000 ports\",\n SecurityGroupIngress=[\n ec2.SecurityGroupRule(\n IpProtocol=\"tcp\",\n FromPort=\"30000\",\n ToPort=\"40000\",\n CidrIp=\"0.0.0.0/0\",\n ),\n ec2.SecurityGroupRule(\n IpProtocol=\"tcp\",\n FromPort=\"22\",\n ToPort=\"22\",\n CidrIp=\"0.0.0.0/0\",\n ),\n ec2.SecurityGroupRule(\n IpProtocol=\"tcp\",\n FromPort=\"6783\",\n ToPort=\"6793\",\n CidrIp=\"172.31.0.0/16\",\n ),\n ec2.SecurityGroupRule(\n IpProtocol=\"udp\",\n FromPort=\"6783\",\n ToPort=\"6784\",\n CidrIp=\"172.31.0.0/16\",\n ),\n ec2.SecurityGroupRule(\n IpProtocol=\"tcp\",\n FromPort=\"4040\",\n ToPort=\"4040\",\n CidrIp=\"172.31.0.0/16\",\n )\n ]\n )\n)\n\necs_instance_role = ecs_template.add_resource(Role(\n \"ecsRole\",\n AssumeRolePolicyDocument=Policy(\n Statement=[\n Statement(\n Effect=Allow,\n Action=[AssumeRole],\n Principal=Principal(\"Service\", [\"ec2.amazonaws.com\"])\n )\n ]\n ),\n ManagedPolicyArns=['arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role', 'arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess', 'arn:aws:iam::aws:policy/AmazonEC2ContainerServiceFullAccess', 'arn:aws:iam::aws:policy/AmazonKinesisFullAccess']\n))\n\necs_task_role = ecs_template.add_resource(Role(\n \"ecsTaskRole\",\n AssumeRolePolicyDocument=Policy(\n Statement=[\n Statement(\n Effect=Allow,\n Action=[AssumeRole],\n Principal=Principal(\"Service\", [\"ecs-tasks.amazonaws.com\"])\n )\n ]\n ),\n ManagedPolicyArns=['arn:aws:iam::aws:policy/AmazonKinesisFirehoseFullAccess', 'arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess', 'arn:aws:iam::aws:policy/AmazonKinesisFullAccess']\n))\n\necs_instance_profile = ecs_template.add_resource(InstanceProfile(\n \"ecsInstanceProfile\",\n Roles=[Ref(ecs_instance_role)]\n))\n\n#customer cluster instances\ncount = 1\nfor eip in eip_list:\n instance1 = ecs_template.add_resource(ec2.Instance(\n \"customerClusterInstance\" + str(count),\n SecurityGroups=[Ref(ecs_instance_sg)],\n IamInstanceProfile=Ref(ecs_instance_profile),\n KeyName='aws',\n InstanceType='r3.4xlarge',\n ImageId=ImageId,\n Tags=[ec2.Tag('weave:peerGroupName','reInvent')],\n BlockDeviceMappings=[ec2.BlockDeviceMapping(DeviceName='/dev/xvda',Ebs=ec2.EBSBlockDevice(VolumeSize=100))],\n UserData=Base64(Join('', [\n \"#!/bin/bash\\n\",\n \"echo ECS_CLUSTER=\", Ref(customer_cluster), \" >> /etc/ecs/ecs.config\\n\",\n \"echo SERVICE_TOKEN=\", os.environ['WEAVE_SERVICE_TOKEN'], \" >> /etc/weave/scope.config\\n\",\n \"docker run -d --name dogstatsd -e API_KEY=\", os.environ['DD_API_KEY'], \" datadog/docker-dogstatsd\\n\",\n ]))\n )\n )\n eipassoc1 = ecs_template.add_resource(ec2.EIPAssociation(\n \"EIPAssoc1\" + str(count),\n InstanceId=Ref(instance1),\n AllocationId=eip\n ))\n count +=1\n\n#matching engine cluster instances\nfor count in range(0, 5):\n instance1 = ecs_template.add_resource(ec2.Instance(\n \"matchingEngineInstance\" + str(count),\n SecurityGroups=[Ref(ecs_instance_sg)],\n IamInstanceProfile=Ref(ecs_instance_profile),\n KeyName='aws',\n InstanceType='r3.4xlarge',\n ImageId=ImageId,\n Tags=[ec2.Tag('weave:peerGroupName','reInvent')],\n BlockDeviceMappings=[ec2.BlockDeviceMapping(DeviceName='/dev/xvda',Ebs=ec2.EBSBlockDevice(VolumeSize=100))],\n UserData=Base64(Join('', [\n \"#!/bin/bash\\n\",\n \"echo ECS_CLUSTER=\", Ref(matching_engine_cluster), \" >> /etc/ecs/ecs.config\\n\",\n \"echo SERVICE_TOKEN=\", os.environ['WEAVE_SERVICE_TOKEN'], \" >> /etc/weave/scope.config\\n\",\n \"docker run -d --name dogstatsd -e API_KEY=\", os.environ['DD_API_KEY'], \" datadog/docker-dogstatsd\\n\",\n ]))\n )\n )\n\n#market data instances\nfor count in range(0, 2):\n instance1 = ecs_template.add_resource(ec2.Instance(\n \"marketDataInstance\" + str(count),\n SecurityGroups=[Ref(ecs_instance_sg)],\n IamInstanceProfile=Ref(ecs_instance_profile),\n KeyName='aws',\n InstanceType='r3.4xlarge',\n ImageId=ImageId,\n Tags=[ec2.Tag('weave:peerGroupName','reInvent')],\n BlockDeviceMappings=[ec2.BlockDeviceMapping(DeviceName='/dev/xvda',Ebs=ec2.EBSBlockDevice(VolumeSize=100))],\n UserData=Base64(Join('', [\n \"#!/bin/bash\\n\",\n \"echo ECS_CLUSTER=\", Ref(market_data_cluster), \" >> /etc/ecs/ecs.config\\n\",\n \"echo SERVICE_TOKEN=\", os.environ['WEAVE_SERVICE_TOKEN'], \" >> /etc/weave/scope.config\\n\",\n \"docker run -d --name dogstatsd -e API_KEY=\", os.environ['DD_API_KEY'], \" datadog/docker-dogstatsd\\n\",\n ]))\n )\n )\n#docker run -d --name dogstatsd -h `hostname` -e ef3d399b75961da5e51f63f0b3addf0b datadog/docker-dogstatsd\n#broker dealer instances\nfor count in range(0, 5):\n instance1 = ecs_template.add_resource(ec2.Instance(\n \"brokerDealerInstance\" + str(count),\n SecurityGroups=[Ref(ecs_instance_sg)],\n IamInstanceProfile=Ref(ecs_instance_profile),\n KeyName='aws',\n InstanceType='r3.4xlarge',\n ImageId=ImageId,\n Tags=[ec2.Tag('weave:peerGroupName','reInvent')],\n BlockDeviceMappings=[ec2.BlockDeviceMapping(DeviceName='/dev/xvda',Ebs=ec2.EBSBlockDevice(VolumeSize=100))],\n UserData=Base64(Join('', [\n \"#!/bin/bash\\n\",\n \"echo ECS_CLUSTER=\", Ref(broker_dealer_cluster), \" >> /etc/ecs/ecs.config\\n\",\n \"echo SERVICE_TOKEN=\", os.environ['WEAVE_SERVICE_TOKEN'], \" >> /etc/weave/scope.config\\n\",\n \"docker run -d --name dogstatsd -e API_KEY=\", os.environ['DD_API_KEY'], \" datadog/docker-dogstatsd\\n\",\n ]))\n )\n )\n\nwith open('symbols.pickle', 'rb') as handle:\n symbols = pickle.load(handle)\n\n#print symbols\n\nfor symbol in symbols:\n myDNSRecord = ecs_template.add_resource(RecordSetType(symbol,HostedZoneId=HostedZoneId,Comment=symbol,Name=symbol + \".aex.com\",Type=\"A\", TTL=60, ResourceRecords=[str((ip_list.pop()))]))\n\n\n#matching-engine task\nmyEnvironment = ecs.Environment(Name='symbol', Value='AMZN')\ndefaultMode = ecs.Environment(Name='mode', Value='production')\nlog = ecs.LogConfiguration(LogDriver='awslogs', Options={\"awslogs-group\":\"/aex/matching-engine\", \"awslogs-region\": \"us-west-2\"})\ncontainer_definition = ecs.ContainerDefinition(Name='matchingEngine', Image=Image, Cpu=100, Memory=1024, Command=[\"/bin/sh\", \"start_me.sh\"], Environment=[myEnvironment, defaultMode, data_dog_environment_api_key, data_dog_environment_app_key], LogConfiguration=log)\ntask_definition = ecs.TaskDefinition('matchingEngine', ContainerDefinitions=[container_definition], TaskRoleArn=Ref(ecs_task_role))\nmytask = ecs_template.add_resource(task_definition)\n\n#fix-gateway task\nfix_gateway_environment_connectiontype = ecs.Environment(Name='ConnectionType', Value='default')\nfix_gateway_environment_sendercompid = ecs.Environment(Name='SenderCompID', Value='default')\nfix_gateway_environment_targetcompid = ecs.Environment(Name='TargetCompID', Value='default')\nfix_gateway_environment_socketconnecthost = ecs.Environment(Name='SocketConnectHost', Value='default')\nfix_gateway_environment_socketconnectport = ecs.Environment(Name='SocketConnectPort', Value='default')\nfix_gateway_web_port = ecs.PortMapping(ContainerPort=80, HostPort=0)\nfix_gateway_fix_port = ecs.PortMapping(ContainerPort=11310, HostPort=0)\nfix_gateway_log = ecs.LogConfiguration(LogDriver='awslogs', Options={\"awslogs-group\":\"/aex/fix-gateway\", \"awslogs-region\": \"us-west-2\"})\nfix_gateway_container_definition = ecs.ContainerDefinition(\n Name='customerGateway',\n Image=Image,\n Cpu=100,\n Memory=1024,\n Command=[\"/bin/sh\", \"start_acceptor.sh\"],\n Environment=[fix_gateway_environment_connectiontype,\n fix_gateway_environment_sendercompid,\n fix_gateway_environment_targetcompid,\n fix_gateway_environment_socketconnecthost,\n fix_gateway_environment_socketconnectport,\n data_dog_environment_api_key,\n data_dog_environment_app_key],\n LogConfiguration=fix_gateway_log,\n PortMappings=[fix_gateway_web_port, fix_gateway_fix_port])\n\nfix_gateway_task_definition = ecs.TaskDefinition('customerGateway', ContainerDefinitions=[fix_gateway_container_definition])\nfix_task = ecs_template.add_resource(fix_gateway_task_definition)\n\n#customer-oms task\noms_gateway_environment_connectiontype = ecs.Environment(Name='ConnectionType', Value='default')\noms_gateway_environment_sendercompid = ecs.Environment(Name='SenderCompID', Value='default')\noms_gateway_environment_targetcompid = ecs.Environment(Name='TargetCompID', Value='default')\noms_gateway_environment_socketconnecthost = ecs.Environment(Name='SocketConnectHost', Value='default')\noms_gateway_environment_socketconnectport = ecs.Environment(Name='SocketConnectPort', Value='default')\noms_gateway_web_port = ecs.PortMapping(ContainerPort=80, HostPort=0)\noms_gateway_fix_port = ecs.PortMapping(ContainerPort=11310, HostPort=0)\noms_gateway_log = ecs.LogConfiguration(LogDriver='awslogs', Options={\"awslogs-group\":\"/aex/oms-gateway\", \"awslogs-region\": \"us-west-2\"})\noms_gateway_container_definition = ecs.ContainerDefinition(\n Name='omsGateway',\n Image=Image,\n Cpu=100,\n Memory=1024,\n Command=[\"/bin/sh\", \"start_oms.sh\"],\n Environment=[oms_gateway_environment_connectiontype,\n oms_gateway_environment_sendercompid,\n oms_gateway_environment_targetcompid,\n oms_gateway_environment_socketconnecthost,\n oms_gateway_environment_socketconnectport,\n data_dog_environment_api_key,\n data_dog_environment_app_key],\n LogConfiguration=oms_gateway_log,\n PortMappings=[oms_gateway_web_port, oms_gateway_fix_port])\n\noms_gateway_task_definition = ecs.TaskDefinition('omsEngine', ContainerDefinitions=[oms_gateway_container_definition])\noms_task = ecs_template.add_resource(oms_gateway_task_definition)\n\n#utility task\nterminal_environment = ecs.Environment(Name='TERM', Value='screen')\nutility_container_definition = ecs.ContainerDefinition(Name='utility', Image=Image, Cpu=100, Memory=1024, Command=[\"/bin/sh\", \"start_ui.sh\"], Environment=[myEnvironment, defaultMode, data_dog_environment_api_key, data_dog_environment_app_key, terminal_environment], LogConfiguration=log)\nutility_task_definition = ecs.TaskDefinition('utilityTask', ContainerDefinitions=[utility_container_definition], TaskRoleArn=Ref(ecs_task_role))\nmytask = ecs_template.add_resource(utility_task_definition)\necs_file = open(fileName, \"wb\")\necs_file.write(ecs_template.to_json())\necs_file.close()\n","sub_path":"generate_aex_cloudformation.py","file_name":"generate_aex_cloudformation.py","file_ext":"py","file_size_in_byte":13820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"496491157","text":"# https://atcoder.jp/contests/abc144/tasks/abc144_b\nimport sys\nsys.setrecursionlimit(2147483647)\nINF=float(\"inf\")\nMOD=10**9+7\ninput=lambda :sys.stdin.readline().rstrip()\ndef resolve():\n s=set()\n for i in range(1,10):\n for j in range(1,10):\n s.add(i*j)\n n=int(input())\n print(\"Yes\" if n in s else \"No\")\nresolve()\n","sub_path":"ABC144/b_81.py","file_name":"b_81.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"640237105","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom gum.utils import elasticsearch_connection\n\n\nclass ElasticsearchManager(object):\n \"\"\"Like a `ModelManager` gives to the user methods to apply queries\n to Elasticsearch from a specific model.\n \"\"\"\n\n def __init__(self, model=None, mapping_type=None):\n self.model = None\n self.mapping_type = None\n\n def search(self, **kwargs):\n \"\"\"Partial application of `search` function from Elasticsearch\n module.\n \"\"\"\n es = elasticsearch_connection()\n if 'index' not in kwargs:\n kwargs[\"index\"] = self.mapping_type.index\n if 'doc_type' not in kwargs:\n kwargs[\"doc_type\"] = self.mapping_type.get_type()\n return es.search(**kwargs)","sub_path":"gum/managers.py","file_name":"managers.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"508272473","text":"# Copyright 2018, Antoine \"hashar\" Musso\n# Copyright 2018, Wikimedia Foundation 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 logging\nimport os\nimport subprocess\n\n\ndef update(args, mwdir=None):\n log = logging.getLogger('mw.maintenance.update')\n\n cmd = ['php', 'maintenance/update.php', '--quick']\n cmd.extend(args)\n log.info(' '.join(cmd))\n\n update_env = {}\n update_env.update(os.environ)\n if mwdir is not None:\n update_env['MW_INSTALL_PATH'] = mwdir\n\n p = subprocess.Popen(cmd, cwd=mwdir, env=update_env)\n p.communicate()\n if p.returncode > 0:\n raise Exception(\n 'Update failed with exit code: %s' % p.returncode)\n\n\ndef install(args, mwdir=None):\n log = logging.getLogger('mw.maintenance.install')\n\n cmd = ['php', 'maintenance/install.php']\n cmd.extend(args)\n cmd.extend([\n '--with-extensions', # T189567\n '--pass=testwikijenkinspass',\n 'TestWiki',\n 'WikiAdmin'\n ])\n log.info(' '.join(cmd))\n\n install_env = {}\n install_env.update(os.environ)\n\n # LANG is passed to $wgShellLocale\n install_env.update({'LANG': 'C.UTF-8'})\n\n p = subprocess.Popen(cmd, cwd=mwdir, env=install_env)\n p.communicate()\n if p.returncode > 0:\n raise Exception(\n 'Install failed with exit code: %s' % p.returncode)\n\n\ndef rebuildLocalisationCache(lang=['en'], mwdir=None):\n log = logging.getLogger('mw.maintenance.rebuildLocalisationCache')\n cmd = ['php', 'maintenance/rebuildLocalisationCache.php']\n cmd.extend(['--lang', ','.join(lang)])\n log.info(' '.join(cmd))\n\n p = subprocess.Popen(cmd, cwd=mwdir)\n p.communicate()\n if p.returncode > 0:\n raise Exception(\n 'rebuildLocalisationCache failed with exit code: %s' % (\n p.returncode))\n","sub_path":"quibble/mediawiki/maintenance.py","file_name":"maintenance.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"132457225","text":"from flask import request\nfrom . import metrics\n\n\nclass MetricsRegister:\n common_counter = metrics.counter(\n \"flask_by_endpoint_counter\",\n \"Request count by endpoints\",\n labels={\"endpoint\": lambda: request.endpoint},\n )\n\n @classmethod\n def register_defaults(cls):\n # register additional default metrics\n metrics.register_default(\n metrics.counter(\n \"flask_by_path_counter\",\n \"Request count by request paths\",\n labels={\"path\": lambda: request.path},\n )\n )\n","sub_path":"webserver/metrics/metrics_register.py","file_name":"metrics_register.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"458921931","text":"import sys, os \nimport pandas as pd\nimport datetime\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"winerama.settings\")\n\nimport django\ndjango.setup()\n\nfrom reviews.models import Review, Wine \n\ndef save_review_from_row(review_row):\n review = Review()\n\n # id, username, wine_id, rating, published_date, comment\n\n review.id = int(review_row[0]) + 1\n\n review.user_name = review_row[5]\n\n review.wine = Wine.objects.get(id=review_row[2])\n\n review.rating = review_row[3]\n\n review.pub_date = datetime.datetime.now()\n\n review.comment = datetime.datetime.fromtimestamp(\n int(review_row[4])\n ).strftime('%Y-%m-%d %H:%M:%S')\n\n print(review.id, \n review.user_name,\n review.wine,\n review.rating,\n review.pub_date,\n review.comment)\n\n review.save()\n \n \nif __name__ == \"__main__\":\n \n if len(sys.argv) == 2:\n print(\"Reading from file \" + str(sys.argv[1]))\n reviews_df = pd.read_csv(sys.argv[1])\n print(reviews_df)\n\n #reviews_df.apply(\n # save_review_from_row,\n # axis=1\n #)\n \n objs = [\n Review(\n id=index,\n user_name=e.username,\n user_id = e.UserID,\n wine=Wine.objects.get(id=e.MovieID),\n rating=e.Rating,\n pub_date=datetime.datetime.now(),\n comment=e.Timestamp\n )\n for index, e in reviews_df.iterrows()\n ]\n\n msg = Review.objects.bulk_create(objs)\n\n print(\"There are {} reviews in DB\".format(Review.objects.count()))\n \n else:\n print(\"Please, provide Reviews file path\")\n","sub_path":"load_ratings.py","file_name":"load_ratings.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"200971952","text":"from dimensions import DIMENSIONS\n\n\ndef test_list_structure():\n \"\"\"\n 1. Test DIMENSIONS is a list of dictionaries\n 2. Test the number of dimensions IMPORTANT: If test is to be restructured on a different number\n of dimension this is the only test that should be corrected\n \"\"\"\n assert type(DIMENSIONS).__name__ == 'list'\n actual_list_structure = set((type(elem).__name__ for elem in DIMENSIONS))\n expected_list_structure = {'dict'}\n assert actual_list_structure == expected_list_structure\n assert len(DIMENSIONS) == 6\n\n\ndef test_element_structure():\n \"\"\"\n 1. Test that all dictionaries have proper keys\n \"\"\"\n actual_element_keys = set(k for elem in DIMENSIONS for k in elem)\n expected_element_keys = {'name', 'answers'}\n assert actual_element_keys == expected_element_keys\n\n\ndef test_number_of_answers_per_dimension():\n \"\"\"\n 1. Test the correlation between the number of dimensions and the number of answers\n \"\"\"\n n = len(DIMENSIONS)\n actual_number = set(len(elem['answers']) for elem in DIMENSIONS)\n expected_number = {2 * (n - 1)}\n assert actual_number == expected_number\n","sub_path":"python-solution/tests/test_dimensions.py","file_name":"test_dimensions.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"459338390","text":"import matplotlib.pyplot as plt\nimport torch\n\n\ndef show_batch(dataloader):\n n = dataloader.batch_size\n imgs, masks = next(iter(dataloader))\n print(len(imgs), imgs.shape)\n imgs = imgs.permute(0, 2, 3, 1)\n plt.figure(figsize=(12, 5))\n for i in range(dataloader.batch_size):\n ax1 = plt.subplot(2, n, i+1)\n ax1.imshow(imgs[i])\n ax1.axis('off')\n ax2 = plt.subplot(2, n, n+i+1)\n ax2.imshow(masks[i])\n ax2.axis('off')\n plt.show()","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"577589355","text":"#!/usr/bin/python\nimport os,datetime\nfrom time import *\nimport time \nfrom datetime import datetime,timedelta\nfrom time import mktime\n#Zugriff auf den Feiertagskalender des gewaehlten Jahres\n\ndef Feiertagskalender():\n\t\tJahr = raw_input(\"Jahr:\")\n\t\tJahr = int(Jahr)\n\t\ta = Jahr % 19\n\t\tb = Jahr % 4\n\t\tc = Jahr % 7\n\t\tk = Jahr / 100\n\t\tp = (8 * k + 13) / 25\n\t\tq = k / 4\n\t\tM = (15 + k - p - q) % 30\n\t\td = (19 * a + M) % 30\n\t\tN = (4 + k -q) % 7\n\t\te = (2 * b + 4 * c + 6 * d + N) % 7\n\t\tTage = (21 + d + e)\n\t\tdatum = '01.03.' + str(Jahr)\n\t\tdatum1 = time.strptime(datum,'%d.%m.%Y')\n\t\tostern = datetime.fromtimestamp(mktime(datum1)) + timedelta(Tage)\n\t\tostern = ostern.strftime('%d.%m.%Y')\n\t\taschermittwoch = datetime.fromtimestamp(mktime(datum1)) + timedelta(Tage) - timedelta(46)\n\t\taschermittwoch = aschermittwoch.strftime('%d.%m.%Y')\n\t\tpalmsonntag = datetime.fromtimestamp(mktime(datum1)) + timedelta(Tage) - timedelta(7)\n\t\tpalmsonntag = palmsonntag.strftime('%d.%m.%Y')\n\t\tgruendonnerstag = datetime.fromtimestamp(mktime(datum1)) + timedelta(Tage) + timedelta(3)\n\t\tgruendonnerstag = gruendonnerstag.strftime('%d.%m.%Y')\n\t\tkarfreitag = datetime.fromtimestamp(mktime(datum1)) + timedelta(Tage) - timedelta(2)\n\t\tkarfreitag = karfreitag.strftime('%d.%m.%Y')\n\t\tostermontag = datetime.fromtimestamp(mktime(datum1)) + timedelta(Tage) + timedelta(1)\n\t\tostermontag = ostermontag.strftime('%d.%m.%Y')\n\t\tchristihimmelfahrt = datetime.fromtimestamp(mktime(datum1)) + timedelta(Tage) + timedelta(39)\n\t\tchristihimmelfahrt = christihimmelfahrt.strftime('%d.%m.%Y')\n\t\tpfingstsonntag = datetime.fromtimestamp(mktime(datum1)) + timedelta(Tage) + timedelta(49)\n\t\tpfingstsonntag = pfingstsonntag.strftime('%d.%m.%Y')\n\t\tpfingstmontag = datetime.fromtimestamp(mktime(datum1)) + timedelta(Tage) + timedelta(50)\n\t\tpfingstmontag = pfingstmontag.strftime('%d.%m.%Y')\n\t\tfronleichnam = datetime.fromtimestamp(mktime(datum1)) + timedelta(Tage) + timedelta(60)\n\t\tfronleichnam = fronleichnam.strftime('%d.%m.%Y')\n\t\tneujahr = '01.01.' + str(Jahr)\n\t\tdreikoenige = '06.01.' + str(Jahr)\n\t\tweihnachten = '25.12.' + str(Jahr)\n\t\tstephanstag = '26.12.' + str(Jahr)\n\t\tnationalfeiertag = '01.08.' + str(Jahr)\n\t\tsilvester = '31.12.' + str(Jahr)\n\t\tf = open('Feiertagskalender.txt','w')\n\t\tf.write((str(\"Ostern:\")) + \"\" + (str(ostern)) + \"\\n\") \n\t\tf.write((str(\"Aschermittwoch:\")) + \"\" + (str(aschermittwoch)) + \"\\n\")\n\t\tf.write((str(\"Palmsonntag:\")) + \"\" + (str(palmsonntag)) + \"\\n\")\n\t\tf.write((str(\"Gruendonnertag:\")) + \"\" +(str(gruendonnerstag)) + \"\\n\")\n\t\tf.write((str(\"Karfreitag:\")) + \"\" + (str(karfreitag)) + \"\\n\")\n\t\tf.write((str(\"Ostermontag:\")) + \"\" +(str(ostermontag))+ \"\\n\")\n\t\tf.write((str(\"Christihimmelfahrt:\")) + \"\" + (str(christihimmelfahrt)) + \"\\n\")\n\t\tf.write((str(\"Pfingssonntag:\")) + \"\" + (str(pfingstsonntag)) + \"\\n\")\n\t\tf.write((str(\"Pfingsmontag:\")) + \"\" + (str(pfingstmontag)) + \"\\n\")\n\t\tf.write((str(\"Fronleichnahm:\")) + \"\" + (str(fronleichnam)) + \"\\n\")\n\t\tf.write((str(\"Neujahr:\")) + \"\" + (str(neujahr)) + \"\\n\")\n\t\tf.write((str(\"Dreikoenigstag:\")) + \"\" + (str(dreikoenige)) + \"\\n\")\n\t\tf.write((str(\"Weihnachten:\")) + \"\" + (str(weihnachten)) + \"\\n\")\n\t\tf.write((str(\"Stephanstag:\")) + \"\" + (str(stephanstag)) + \"\\n\")\n\t\tf.write((str(\"Nationalfeiertag:\")) + \"\" + (str(nationalfeiertag)) + \"\\n\" )\n\t\tf.write((str(\"Silvester:\")) + \"\" + (str(silvester)) + \"\\n\")\n\n\t\tf.close()\nFeiertagskalender()\n\ndef Sortieren():\n\t\tos.system('sort Feiertagskalender.txt > Feiertage.txt')\n\t\tos.system('rm Feiertagskalender.txt')\n\nSortieren()\n","sub_path":"Time/ostern/Feiertage.py","file_name":"Feiertage.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"15025638","text":"# -*- coding: utf-8 -*-\nimport pusher\nimport json\nimport requests\nimport webapp2\nfrom django.shortcuts import render_to_response\nfrom django.conf import settings\nfrom django.http import HttpResponse\nfrom django.template import RequestContext\n# from django.core.serializers.json import DjangoJSONEncoder\nfrom ChatAdmin.models import PeopleModelForm\n\n\npusher.app_id = settings.PUSHER_APP_ID\npusher.key = settings.PUSHER_KEY\npusher.secret = settings.PUSHER_SECRET\n\np = pusher.Pusher()\n\n\ndef home(request):\n if not request.session.get('user'):\n request.session['user'] = 'user-%s' % request.session.session_key\n return render_to_response('pusher_index.html', {\n 'PUSHER_KEY': settings.PUSHER_KEY,\n }, RequestContext(request))\n\n\ndef message(request):\n if request.session.get('user') and request.POST.get('name') and request.POST.get('message') \\\n and request.POST.get('email'):\n p['chat'].trigger('message', {\n 'user': request.session['user'],\n 'name': request.POST.get('name'),\n 'email': request.POST.get('email'),\n 'message': request.POST.get('message'),\n })\n return HttpResponse('')\n\n\nclass AuthHandler(webapp2.RequestHandler):\n def post(self):\n channel_name = self.request.get('chat')\n socket_id = self.request.get('socket_id')\n p = pusher.Pusher(app_id=pusher.app_id, key=pusher.key, secret=pusher.secret)\n\n auth = p[channel_name].authenticate(socket_id)\n json_data = json.dumps(auth)\n self.response.out.write(json_data)\n\n\ndef main():\n application = webapp2.WSGIApplication([('/pusher/auth', AuthHandler)])\n\n\n\n\n\n\n\n","sub_path":"SupportChat/pusher_server_api.py","file_name":"pusher_server_api.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"366653203","text":"# -*- coding: utf-8 -*-\n\ndef isPalindrome(x):\n \"\"\"\n :type x: int\n :rtype: bool\n \"\"\"\n ret = 0\n temp = abs(x)\n \n while temp != 0:\n remainder = temp % 10\n ret = ret * 10 + remainder\n temp = int (temp / 10)\n \n if x >= 0 and x == ret:\n return True\n else:\n return False","sub_path":"PalindromeNumber.py","file_name":"PalindromeNumber.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"357748969","text":"#!/usr/bin/env python3\nimport asyncio\n\nimport argparse\nimport raftos\nimport random\nimport string\n\ndef randomword(length):\n return ''.join(random.choice(string.ascii_lowercase) for i in range(length))\n\nasync def run(node_id, peers):\n # List of songs\n song_list = raftos.ReplicatedList(name = 'song_list')\n\n # Song distributions\n which_song = raftos.ReplicatedDict(name = 'which_song')\n\n await raftos.wait_until_leader(node_id)\n for i in range(5):\n song = node_id + ' => ' + randomword(random.randint(3, 5))\n print (song)\n await song_list.append(song)\n\n while True:\n # Brought to you by :\n await raftos.wait_until_leader(node_id)\n snapshot = await song_list.get()\n song = snapshot.pop() if(len(snapshot) > 0) else None\n await song_list.set(snapshot)\n\n song is not None and print ('leader: select, %r' % song)\n\n # And boom goes the dynamite\n snapshot = await which_song.get()\n for peer in peers:\n snapshot[peer] = song\n await which_song.set(snapshot)\n\n # The Devil opened up his case and he said, \"I'll start this show.\"\n # And fire flew from his fingertips as he rosined up his bow.\n # And he pulled the bow across the strings and it made an evil hiss.\n # And a band of demons joined in and it sounded something like this.\n keys = await which_song.keys()\n if (node_id in keys):\n song = await which_song[node_id]\n\n print (song)\n await asyncio.sleep(60)\n\nif (__name__ == '__main__'):\n parser = argparse.ArgumentParser()\n parser.add_argument('--node')\n parser.add_argument('--cluster')\n args = parser.parse_args()\n\n cluster = ['127.0.0.1:{}'.format(port) for port in args.cluster.split()]\n node = '127.0.0.1:{}'.format(args.node)\n\n raftos.configure({\n 'log_path': './',\n 'serializer': raftos.serializers.JSONSerializer\n })\n\n loop = asyncio.get_event_loop()\n loop.create_task(raftos.register(node, cluster=cluster))\n loop.run_until_complete(run(node, cluster))\n","sub_path":"node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"599830422","text":"import spacy\nfrom spacy.matcher import Matcher\n\nnlp = spacy.load(\"zh_core_web_sm\")\nmatcher = Matcher(nlp.vocab)\n\ndoc = nlp(\n \"我之前有去下载Dota到电脑上面,但是根本打不开游戏,怎么办?\"\n \"我下载Minecraft,是Windows的版本,下载后是一个'.zip'的文件夹,然后我用了默认软件做了\"\n \"解压...我是不是还需要去下载Winzip?\"\n)\n\n# 写一个模板来匹配\"下载\"加一个代词\npattern = [{\"TEXT\": \"下载\"}, {\"POS\": \"PROPN\"}]\n\n# 把模板加入到matcher中,然后把matcher应用到doc上面\nmatcher.add(\"DOWNLOAD_THINGS_PATTERN\", None, pattern)\nmatches = matcher(doc)\nprint(\"Total matches found:\", len(matches))\n\n# 遍历所有的匹配,打印span的文本\nfor match_id, start, end in matches:\n print(\"Match found:\", doc[start:end].text)","sub_path":"exercises/zh/solution_01_12_02.py","file_name":"solution_01_12_02.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"637571581","text":"\"\"\"CPU functionality.\"\"\"\n\nimport sys\n\n# operation codes:\nHLT = 0b00000001\nLDI = 0b10000010\nPRN = 0b01000111\nMUL = 0b10100010\nPUSH = 0b01000101\nPOP = 0b01000110\n # reserved registers\nIM = 5\nIS = 6\nSP = 7\n # flags\nFL_LT = 0b100\nFL_GT = 0b010\nFL_EQ = 0b001\nFL_TIMER = 0b00000001\nFL_KEYBOARD = 0b00000010\n\nclass CPU:\n \"\"\"Main CPU class.\"\"\"\n\n def __init__(self):\n \"\"\"Construct a new CPU.\"\"\"\n self.ram = [0]*256\n self.reg = [0]*8\n self.reg[SP] = 0xf4\n\n self.processCounter = 0\n self.flags = 0\n # self.interrupts = 1;\n self.isPaused = False\n # self.last_timer_int = None\n self.instruction_sets_processCounter = False\n\n self.branchTree = {\n HLT: self.op_HLT,\n LDI: self.op_LDI,\n PRN: self.op_PRN,\n MUL: self.op_MUL,\n PUSH: self.op_PUSH,\n POP: self.op_POP\n }\n\n def load(self):\n \"\"\"Load a program into memory.\"\"\"\n\n address = 0\n\n fp = open(filename, \"r\")\n for line in fp:\n # split by comment and strip empty spaces\n instruction = line.split(\"#\")[0].strip()\n if instruction == \"\":\n continue\n value = int(instruction, 2)\n self.ram[address] = value\n address += 1\n\n def stack_push(self, val):\n self.reg[SP] -= 1\n self.ram_write(self.reg[SP], val)\n\n def stack_pop(self):\n val = self.ram_read(self.reg[SP])\n self.reg[SP] += 1\n return val\n\n def ram_read(self, index):\n return self.ram[index]\n\n def ram_write(self, index, value):\n self.ram[index] = value\n\n\n def alu(self, op, reg_a, reg_b):\n \"\"\"ALU operations.\"\"\"\n\n if op == \"ADD\":\n self.reg[reg_a] += self.reg[reg_b]\n elif op == \"MUL\":\n self.reg[reg_a] *= self.reg[reg_b]\n else:\n raise Exception(\"Unsupported ALU operation\")\n\n def trace(self):\n \"\"\"\n Handy function to print out the CPU state. You might want to call this\n from run() if you need help debugging.\n \"\"\"\n\n print(f\"TRACE: %02X | %02X %02X %02X |\" % (\n self.pc,\n #self.fl,\n #self.ie,\n self.ram_read(self.pc),\n self.ram_read(self.pc + 1),\n self.ram_read(self.pc + 2)\n ), end='')\n\n for i in range(8):\n print(\" %02X\" % self.reg[i], end='')\n\n print()\n\n def run(self):\n \"\"\"Run the CPU.\"\"\"\n while not self.isPaused:\n ir = self.ram[self.processCounter]\n operand_a = self.ram_read(self.processCounter + 1)\n operand_b = self.ram_read(self.processCounter + 2)\n\n instruction_size = ( ir >> 6 ) + 1\n self.instruction_sets_processCounter = ( (ir >> 4) &0b1 ) == 1\n\n if ir in self.branchTree:\n self.branchTree[ir](operand_a, operand_b)\n else:\n raise Exception(f'Unknown Instruction {bin(ir)} at {hex(self.processCounter)}')\n\n if not self.instruction_sets_processCounter:\n self.processCounter += instruction_size\n\n def op_HLT(self, operand_a, operand_b):\n self.isPaused = True\n\n def op_LDI(self, operand_a, operand_b):\n self.reg[operand_a] = operand_b\n\n def op_PRN(self, operand_a, operand_b):\n print(self.reg[operand_a])\n \n def op_MUL(self, operand_a, operand_b):\n self.alu(\"MUL\", operand_a, operand_b)\n\n def op_PUSH(self, operand_a, operand_b):\n self.stack_push(self.reg[operand_a])\n\n def op_POP(self, operand_a, operand_b):\n self.reg[operand_a] = self.stack_pop()\n","sub_path":"ls8/cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":3694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"272670376","text":"#-*- coding:utf-8 -*_\r\nimport os\r\nimport numpy\r\n\r\n\r\n#-------将目录下的图片路径逐行读入txt文件中-----------\r\npath = os.getcwd()\r\nimg_path = os.path.join(path, \"res/video/white\")\r\nimg_list = [os.path.join(img_path, x) for x in os.listdir(img_path) if x.endswith(\".jpg\")]\r\n\r\ntxt_file = \"realdata.txt\"\r\ntxt_path = os.path.join(path, txt_file)\r\nif os.path.exists(txt_path):\r\n os.remove(txt_path)\r\n\r\nobj = open(txt_path, 'w')\r\nfor img in img_list:\r\n obj.writelines(img)\r\n obj.writelines('\\n') #每次写入一个路径之后再写一个换行符\r\nobj.close()\r\nprint(\"the txt file has done\")\r\n\r\n\r\n","sub_path":"press_detect/some_file/to_txt.py","file_name":"to_txt.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"245326690","text":"# udp的recvfrom是阻塞的,\n# 一個recvfrom(x)必須對唯一一個sendinto(y),收完了x個字節的數據就算完成,若是y>x數據就丟失,\n# 這意味著udp根本不會粘包,但是會丟數據,不可靠\n\nfrom socket import *\n\nip_port = ('127.0.0.1', 8000)\nbuffer_size = 1024\n\nudp_server = socket(AF_INET, SOCK_DGRAM) # SOCK_DGRAM基於UDP協議\nudp_server.bind(ip_port) # 將地址綁到服務器\n\nwhile True:\n data, addr = udp_server.recvfrom(buffer_size)\n print('客戶端發來的信息 ', data)\n udp_server.sendto(data.upper(), addr)\n","sub_path":"SelfLearn/網路編程/180802_socket/180803_UDPserver.py","file_name":"180803_UDPserver.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"581169282","text":"#!/usr/bin/env python\r\n\r\nfrom os.path import exists\r\nfrom setuptools import setup\r\n\r\npackages = [\"rapidz\", \"rapidz.dataframe\"]\r\n\r\ntests = [p + \".tests\" for p in packages]\r\n\r\n\r\nsetup(\r\n name=\"rapidz\",\r\n version='0.2.1',\r\n description=\"Streams\",\r\n url=\"http://github.com/xpdAcq/rapidz/\",\r\n maintainer=\"Simon Billinge\",\r\n maintainer_email=\"simon.billinge@gmail.com\",\r\n license=\"BSD\",\r\n keywords=\"streams\",\r\n packages=packages + tests,\r\n python_requires='>=3.9',\r\n long_description=(\r\n open(\"README.rst\").read() if exists(\"README.rst\") else \"\"\r\n ),\r\n install_requires=list(open(\"requirements.txt\").read().strip().split(\"\\n\")),\r\n zip_safe=False,\r\n)\r\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"122529476","text":"import random\n\nclass Room(object):\n\n def __init__(self, terrain, pos):\n self.name = terrain.name\n self.description = terrain.description\n self.terrain = terrain\n self.pos = pos\n self.exits = dict()\n self.contents = list()\n self.contents.extend(terrain.gen_resources())\n\n def mine(self):\n \"\"\"Yield some material from mining.\"\"\"\n mined_resource = None\n total_weight = 1000\n for resource in self.contents:\n if not resource.is_mineral_resource: continue\n\n total_weight += resource.weight\n if random.random() < resource.weight/total_weight:\n mined_resource = resource\n\n if not mined_resource:\n return None\n\n result = mined_resource.mine()\n if not result:\n return None\n\n self.contents.append(result)\n\n if mined_resource.weight <= 0:\n self.contents.remove(mined_resource)\n\n return result\n","sub_path":"mineraffair/room.py","file_name":"room.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"189067863","text":"class Solution:\n def countAndSay(self, n: int) -> str:\n if n == 1:\n return \"1\"\n\n s = self.countAndSay(n - 1)\n ans = \"\"\n count = 0\n i = 0\n c = s[i]\n while i < len(s):\n if c == s[i]:\n count += 1\n else:\n ans += str(count) + s[i - 1]\n c = s[i]\n count = 1\n i += 1\n ans += str(count) + s[i - 1]\n return ans\n\n\ndef main():\n print(\"hello world\")\n test = Solution()\n for i in range(1, 10):\n print(test.countAndSay(i))\n\n\nif __name__ == '__main__':\n main()","sub_path":"src/38_count_and_say.py","file_name":"38_count_and_say.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"106988343","text":"import time\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.webdriver.common.by import By\n\ndef scroll_to(driver, element):\n y_pos = element.location['y']\n driver.execute_script(\"window.scrollTo(0, \" + str(y_pos - 100) + \")\")\n time.sleep(0.5)\n\ndef wait_for_element(driver, class_name, ind):\n times = 0\n while len(driver.find_elements_by_class_name(class_name)) < ind+1:\n time.sleep(0.2)\n times = times + 0.2\n if times > 5:\n return 1\n return 0\n\ndef wait_for_results(driver):\n '''\n Wait for page to load all results\n '''\n time.sleep(1)\n # Pick location if needed\n if len(driver.find_elements_by_class_name('gdpr-vx-consent-bar-button'))>0:\n driver.find_element_by_class_name('gdpr-vx-consent-bar-button').click()\n time.sleep(1)\n if len(driver.find_elements(By.ID, \"setting-location\"))!=0:\n driver.find_element_by_class_name('close').click()\n time.sleep(1)\n select = Select(driver.find_element_by_id('setting-location'))\n select.select_by_index(1)\n time.sleep(1)\n driver.find_element_by_class_name('energy-button').click()\n time.sleep(1)\n\n # Wait until first results are loaded\n wait_for_element(driver, 'result-price', 0)\n prices = driver.find_elements_by_class_name('result-price')\n time.sleep(1)\n\n # Only one offer per company\n\n button = driver.find_element_by_class_name('foldout-trigger.button-toggle-touch')\n scroll_to(driver, button)\n time.sleep(3)\n button.click()\n time.sleep(1)\n button = driver.find_elements_by_class_name('energy-select')[-2]\n scroll_to(driver, button)\n select = Select(button)\n select.select_by_index(0)\n time.sleep(1)\n\n\n\n # Scroll to end of page and pick all results\n\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n time.sleep(1)\n driver.find_elements_by_class_name('highlight-text')[-10].click()\n time.sleep(5)\n prices = driver.find_elements_by_class_name('result-price')\n return prices\n\ndef get_info(driver, class_name, ind, times=1):\n time.sleep(times)\n wait = wait_for_element(driver, class_name, ind)\n if wait:\n return 0\n else:\n element = driver.find_elements_by_class_name(class_name)[ind]\n return element.get_attribute('innerText')\n\ndef get_infos(driver, class_name, times=1):\n time.sleep(times)\n element = driver.find_elements_by_class_name(class_name)\n texts = [ele.get_attribute('innerText') for ele in element]\n return texts\n\ndef show_details(driver, ind):\n button = driver.find_elements_by_class_name('button-text-open')[ind]\n scroll_to(driver, button)\n time.sleep(1)\n button.click()\n\ndef hide_details(driver, ind):\n button = driver.find_elements_by_class_name('button-text-close')[ind]\n scroll_to(driver, button)\n button.click()\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"163081616","text":"# -*- coding: utf-8 -*-\n\n# python std lib\nimport sys\nimport os\nimport unittest\nfrom contextlib import contextmanager\n\n# Ensures that the $PACKAGE$ lib/ folder exists in path so imports will work proper.\nsys.path.append('lib')\n\n# Import used to localize source files\nimport pykwalify\n\n# python std logging\nimport logging\nimport logging.config\n\nLog = None\nIN_VIRTUALENV = True if hasattr(sys, 'real_prefix') else False\nif IN_VIRTUALENV:\n path = os.path.join(sys.prefix, 'etc', \"pykwalify\", 'logging.ini')\n if not os.path.exists(path): # we are not installed, running from source tree\n (prefix, bindir) = os.path.split(os.path.dirname(os.path.abspath(sys.argv[0])))\n path = os.path.join(prefix, \"pykwalify\", \"config\", \"logging.ini\")\n logging.config.fileConfig(path)\nelse:\n logging.config.fileConfig(os.path.join(os.sep, 'etc', \"pykwalify\", 'logging.ini'))\nLog = logging.getLogger()\n\n# Use this regexp to validate any logging output\nlogging_regex = \"%s - %s:[0-9]+ - %s\" # % (LoggingLevel, LoggerName, Msg)\n\n# Set the root logger to be silent so all code that uses the python logger\n# will not print anything unless we want it to, then it should be specified\n# in each test and reseted after that test\ndef _set_log_lv(level = 1337, loggers = None):\n \"\"\" If no level is set then level will be so high all logging is silenced\n \"\"\"\n if loggers is None:\n # If no additional loggers is specified then only apply to root logger\n Log.setLevel(level)\n for handler in Log.handlers:\n handler.level = level\n else:\n # If we have other logging instances specified apply to root logger and them\n if not Log in loggers:\n loggers.append(Log)\n\n for log_instance in loggers:\n log_instance.setLevel(level)\n for handler in log_instance.handlers:\n handler.level = level\n\ndef get_log_lv():\n return Log.level\n\n# Initially silence all logging \n_set_log_lv()\n\nfrom io import StringIO\nfrom pykwalify.utils import *\n\nclass TestHelper(unittest.TestCase):\n \"\"\" NEVER EVER do assertion inside one of the context managers in this class unless it is\n specified in each functions documentation that it is safe to use assertsions inside it\n \"\"\"\n\n @contextmanager\n def _custom_argv(self, new_args): \n \"\"\" Used when simulating a call to an script/code that requires cli inputs.\n\n new_args - must be a list [] type\n \"\"\"\n self.assertTrue(isinstance(new_args, list),\n msg=\"input argument not valid list\")\n\n new_args.insert(0, \"\")\n backup_args = sys.argv # Backups the existing argv:s\n sys.argv = new_args # Sets the new argv\n yield\n sys.argv = backup_args\n\n @contextmanager\n def _set_log_lv(self, level=1337, loggers = None):\n \"\"\" Sets a specified logging level and resets it when done\n \"\"\"\n backup_log_lv = get_log_lv()\n _set_log_lv(level = level, loggers = loggers)\n yield\n _set_log_lv(level = backup_log_lv, loggers = loggers)\n\n\n__all__ = []\n\ndef run(argv):\n #unittest.main()\n loader = unittest.TestLoader()\n loader.sortTestMethodsUsing = None\n suite = unittest.TestSuite()\n \n tests = []\n \n # called without arguments\n if len(argv) == 1:\n for test in __all__:\n suite.addTests(loader.loadTestsFromTestCase(test))\n tests.append(str(test))\n # called with arguments, iterate over the list and run specified tests\n else:\n argv.pop(0) # remove ourself\n for name in sys.argv:\n try:\n test = getattr(sys.modules['tests'], name)\n except AttributeError:\n continue\n suite.addTests(loader.loadTestsFromTestCase(test))\n tests.append(name)\n \n print(\"TESTS: %s\" % ', '.join(tests))\n \n # Can be used to reduce the output from the tests if so desired\n if \"verbosity\" in os.environ:\n verbosity = int(os.environ[\"verbosity\"])\n else:\n verbosity = 2\n\n unittest.TextTestRunner(verbosity=verbosity).run(suite)\n\n\ndef gettestcwd(*args):\n \"\"\" Because os.getcwd() cannot be guaranted to work in all cases where the invoke path is\n from another place rather then where runtests.py script is located.\n This function should be used because it returns the abspath to the runtets.py script that \n should manually be concated with any relative path to locate any testfiles.\n To get to the subfolder /tests/ that must be explicit added as extra positional argument to *args\n \"\"\"\n (prefix, bindir) = os.path.split(os.path.dirname(os.path.abspath(sys.argv[0])))\n return concat_path(prefix, bindir, *args)\n\n\ndef concat_path(b, *args):\n \"\"\" Concats b with all arguments in '*args', handles if any argument contains more then 1 directory, example: foo/bar/asd/\n\n Note: this is analogous to list_path() except that this function returns a\n string, though this function is not cross-platform since it uses a\n hardcoded \"/\" instead of os.sep.\n\n Arguments:\n - `b`: string - base from where to concat all '*args'\n - `*args`: strings - all extra paths to concat, concats in order of list\n \"\"\"\n base = b # tmp var\n for a in args:\n if \"/\" in a:\n for s in a.split(\"/\"):\n base = os.path.join(base, s)\n else:\n base = os.path.join(base, a)\n\n return base\n","sub_path":"tests/testhelper.py","file_name":"testhelper.py","file_ext":"py","file_size_in_byte":5448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"503960829","text":"# -*- coding: utf-8 -*-\n\nimport pytest\n\nfrom ..parser.parser import EmailParser, Tokenizer\nfrom ..exc import ParseError, TokenizeError\n\n\nclass TestEmailParser(object):\n\n @pytest.mark.parametrize('from_address, expected_nickname, expected_email', [\n pytest.param('Eva Chen ',\n 'Eva Chen',\n 'ceo1.ccs@trend.com.tw',\n id='FAST001'),\n pytest.param('eva_chen@trendmicro.com ',\n 'eva_chen@trendmicro.com',\n 'ceo2.ccs@trend.com.jp',\n id='FAST002'),\n pytest.param('',\n None,\n 'ceo3.ccs@trend.com.jp',\n id='FAST003'),\n pytest.param('ceo4.ccs@roadrunner.com',\n None,\n 'ceo4.ccs@roadrunner.com',\n id='FAST004'),\n ])\n def test_parse_from_addr_fast(self,\n from_address,\n expected_nickname,\n expected_email):\n\n actual_nickname, actual_email = EmailParser.parse_addr(from_address)\n assert expected_nickname == actual_nickname\n assert expected_email == actual_email\n\n @pytest.mark.parametrize('from_address', [\n pytest.param('', id='TOFT002'),\n pytest.param('<>', id='TOFT003'),\n ])\n def test_parse_from_address_toft(self, from_address):\n _, _ = EmailParser.parse_addr(from_address)\n\n @pytest.mark.parametrize('from_address', [\n pytest.param(None, id='FET001')\n ])\n def test_parse_from_address_fet(self, from_address):\n with pytest.raises(ParseError):\n _, _ = EmailParser.parse_addr(from_address)\n\n @pytest.mark.parametrize('email,expected_domain', [\n pytest.param('ceo.ccs@roadrunner.com',\n 'roadrunner.com',\n id='FAST001'),\n pytest.param('ceo.ccs@not_me@roadrunner.com',\n 'roadrunner.com',\n id='FAST002'),\n pytest.param('ceo.ccsnot_meroadrunner.com',\n None,\n id='FAST003')\n ])\n def test_parse_domain_from_email_fast(self, email, expected_domain):\n actual_domain = EmailParser.parse_domain(email)\n assert expected_domain == actual_domain\n\n\nclass TestTokenizer(object):\n\n @pytest.mark.parametrize('raw_str,expected_token_list', [\n pytest.param('eva_chen@trendmicro.com',\n {'eva', 'chen', 'trendmicro', 'com'},\n id='FAST001'),\n pytest.param('Eva Chen',\n {'eva', 'chen'},\n id='FAST002'),\n pytest.param('Eva;Chen#Luby,Lien.Vincent Lee,',\n {'eva', 'chen', 'luby', 'lien', 'vincent', 'lee'},\n id='FAST003'),\n pytest.param('(Eva Chen)',\n {'eva', 'chen'},\n id='FAST004'),\n pytest.param('[Eva Chen]',\n {'eva', 'chen'},\n id='FAST005'),\n pytest.param('{Eva Chen}',\n {'eva', 'chen'},\n id='FAST006'),\n pytest.param('Eva_Chen',\n {'eva', 'chen'},\n id='FAST007'),\n pytest.param('\"Eva_Chen\"',\n {'eva', 'chen'},\n id='FAST008'),\n ])\n def test_normalized_tokenize_fast(self, raw_str, expected_token_list):\n actual_token_list = Tokenizer.normalized_tokenize(raw_str)\n assert expected_token_list == actual_token_list\n\n @pytest.mark.parametrize('raw_str', [\n pytest.param(None, id='FET001')\n ])\n def test_normalized_tokenize_fet(self, raw_str):\n with pytest.raises(TokenizeError):\n _ = Tokenizer.normalized_tokenize(raw_str)\n","sub_path":"common/parser/test_parser.py","file_name":"test_parser.py","file_ext":"py","file_size_in_byte":4024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"372507297","text":"#!/usr/bin/env python\n\nimport os, re, string, subprocess, sys, importlib\nImport('env')\nsys.path.append(os.getenv(\"MUSE_WORK_DIR\")+'/site_scons')\n#------------------------------------------------------------------------------\n# print(\"Stntuple/SConscript:muse branch: PWD:\"+os.getenv(\"PWD\"))\n\n# pass the package name as a parameter\n\nx = subprocess.call(os.getenv(\"MUSE_WORK_DIR\")+'/Stntuple/scripts/build_config_muse Stntuple',shell=True)\n# print(\"Stntuple/SConscript back from build_config_muse\")\n\nstntuple_env = env.Clone()\n#------------------------------------------------------------------------------\n# done\n#------------------------------------------------------------------------------\nexec(open(os.environ['MUSE_WORK_DIR']+\"/site_scons/stntuple_site_init.py\").read())\n\nfrom stntuple_helper import *\n\nstntuple_env.Append(BUILDERS = {'StntupleCodegen' : stntuple_codegen })\nstntuple_env.Append(BUILDERS = {'StntupleRootCint' : stntuple_rootcint})\n\nstntuple_env['CPPPATH' ].append(os.environ['MUSE_WORK_DIR']+'/include');\n\nstntuple_env.Append(FORTRANPATH = [os.environ['MUSE_WORK_DIR']+'/include']);\n\n# print(stntuple_env.Dump())\n\nExport('stntuple_env')\nExport('stntuple_helper')\n","sub_path":"SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"409250130","text":"from odoo import fields, models, api, _\nfrom datetime import datetime, date, timedelta\nimport requests\nimport json\nfrom odoo.exceptions import UserError\n\nclass ResUesrs(models.Model):\n _inherit= 'res.users'\n\n @api.model\n def create(self, vals):\n res = super(ResUesrs, self).create(vals)\n data = {\n 'name': res.name,\n 'username': res.login,\n 'password': res.password,\n 'userid': res.name,\n 'wing_id': res.name,\n 'section_id': res.name,\n 'designation_id': res.name,\n 'email': res.login,\n 'mobile': res.name,\n 'user_type_id': res.name,\n 'is_wing_head': res.name,\n 'user_id': res.name,\n }\n\n req = requests.post('http://103.92.47.152/STPI/www/web-service/add-user/', data=data,\n json=None)\n try:\n # print('=====================================================', req)\n pastebin_url = req.text\n print('===========================pastebin_url==========================', pastebin_url)\n dictionary = json.loads(pastebin_url)\n except Exception as e:\n print('=============Error==========', e)\n\n\n\nclass HrDepartment(models.Model):\n _inherit= 'hr.department'\n\n @api.model\n def create(self, vals):\n res = super(HrDepartment, self).create(vals)\n data = {\n 'name': res.name,\n 'dept_id': res.name,\n 'user_id': res.name,\n }\n\n req = requests.post('http://103.92.47.152/STPI/www/web-service/department/', data=data,\n json=None)\n try:\n # print('=====================================================', req)\n pastebin_url = req.text\n print('===========================pastebin_url==========================', pastebin_url)\n dictionary = json.loads(pastebin_url)\n except Exception as e:\n print('=============Error==========', e)\n\n\nclass HrJob(models.Model):\n _inherit= 'hr.job'\n\n @api.model\n def create(self, vals):\n res = super(HrJob, self).create(vals)\n data = {\n 'name': res.name,\n 'designation_id': res.name,\n 'user_id': res.name,\n }\n\n req = requests.post('http://103.92.47.152/STPI/www/web-service/designation/', data=data,\n json=None)\n try:\n # print('=====================================================', req)\n pastebin_url = req.text\n print('===========================pastebin_url==========================', pastebin_url)\n dictionary = json.loads(pastebin_url)\n except Exception as e:\n print('=============Error==========', e)","sub_path":"smart_office/models/res_users.py","file_name":"res_users.py","file_ext":"py","file_size_in_byte":2810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"327066656","text":"from PyQt5 import QtCore, QtGui, QtWidgets\r\n\r\nclass Ui_Target(object):\r\n def setupUi(self, Dialog):\r\n Dialog.setObjectName(\"Dialog\")\r\n Dialog.resize(467, 160)\r\n icon = QtGui.QIcon()\r\n icon.addPixmap(QtGui.QPixmap(\":/images/1.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n Dialog.setWindowIcon(icon)\r\n Dialog.setStyleSheet(\"border-image: url(:/images/BackGround.jpg);\")\r\n self.gridLayout = QtWidgets.QGridLayout(Dialog)\r\n self.gridLayout.setObjectName(\"gridLayout\")\r\n self.verticalLayout = QtWidgets.QVBoxLayout()\r\n self.verticalLayout.setObjectName(\"verticalLayout\")\r\n spacerItem = QtWidgets.QSpacerItem(428, 28, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)\r\n self.verticalLayout.addItem(spacerItem)\r\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout()\r\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\r\n spacerItem1 = QtWidgets.QSpacerItem(28, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\r\n self.horizontalLayout_2.addItem(spacerItem1)\r\n self.label = QtWidgets.QLabel(Dialog)\r\n self.label.setMinimumSize(QtCore.QSize(215, 21))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Shell Dlg 2\")\r\n font.setPointSize(10)\r\n self.label.setFont(font)\r\n self.label.setStyleSheet(\"border-image: url(:/images/1WhiteTransparent.png);\\n\"\r\n\"\")\r\n self.label.setObjectName(\"label\")\r\n self.horizontalLayout_2.addWidget(self.label)\r\n spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)\r\n self.horizontalLayout_2.addItem(spacerItem2)\r\n self.TargetBox = QtWidgets.QComboBox(Dialog)\r\n self.TargetBox.setMinimumSize(QtCore.QSize(81, 18))\r\n font = QtGui.QFont()\r\n font.setPointSize(9)\r\n self.TargetBox.setFont(font)\r\n self.TargetBox.setStyleSheet(\"border-image: url(:/images/1WhiteBackground.jpg);\")\r\n self.TargetBox.setObjectName(\"TargetBox\")\r\n self.TargetBox.addItem(\"\")\r\n self.horizontalLayout_2.addWidget(self.TargetBox)\r\n spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)\r\n self.horizontalLayout_2.addItem(spacerItem3)\r\n self.verticalLayout.addLayout(self.horizontalLayout_2)\r\n spacerItem4 = QtWidgets.QSpacerItem(428, 28, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\r\n self.verticalLayout.addItem(spacerItem4)\r\n self.horizontalLayout = QtWidgets.QHBoxLayout()\r\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\r\n spacerItem5 = QtWidgets.QSpacerItem(318, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)\r\n self.horizontalLayout.addItem(spacerItem5)\r\n self.Targets = QtWidgets.QDialogButtonBox(Dialog)\r\n font = QtGui.QFont()\r\n font.setPointSize(10)\r\n self.Targets.setFont(font)\r\n self.Targets.setStyleSheet(\"border-image: url(:/images/1WhiteBackground.jpg);\")\r\n self.Targets.setOrientation(QtCore.Qt.Horizontal)\r\n self.Targets.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)\r\n self.Targets.setObjectName(\"Targets\")\r\n self.horizontalLayout.addWidget(self.Targets)\r\n spacerItem6 = QtWidgets.QSpacerItem(38, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)\r\n self.horizontalLayout.addItem(spacerItem6)\r\n self.verticalLayout.addLayout(self.horizontalLayout)\r\n self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1)\r\n\r\n self.retranslateUi(Dialog)\r\n self.Targets.accepted.connect(Dialog.accept)\r\n self.Targets.rejected.connect(Dialog.reject)\r\n QtCore.QMetaObject.connectSlotsByName(Dialog)\r\n\r\n def retranslateUi(self, Dialog):\r\n _translate = QtCore.QCoreApplication.translate\r\n Dialog.setWindowTitle(_translate(\"Dialog\", \"Select target\"))\r\n self.label.setText(_translate(\"Dialog\", \"

    Which is your target column?

    \"))\r\n self.TargetBox.setItemText(0, _translate(\"Dialog\", \"SELECT\"))\r\nimport Images_rc\r\n\r\n\r\nif __name__ == \"__main__\":\r\n import sys\r\n app = QtWidgets.QApplication(sys.argv)\r\n Dialog = QtWidgets.QDialog()\r\n ui = Ui_Target()\r\n ui.setupUi(Dialog)\r\n Dialog.show()\r\n sys.exit(app.exec_())\r\n","sub_path":"Target.py","file_name":"Target.py","file_ext":"py","file_size_in_byte":4481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"644126219","text":"import pymongo\n\nclass Mongo:\n \n # 登录注册部分\n def find_by_name(self, username):\n res = self.login.find_one({'username': username})\n return res\n \n def login_add(self, username, nickname, password):\n uid = self.max_uid = self.max_uid + 1\n data = {\n 'username': username,\n 'nickname': nickname,\n 'password': password,\n 'uid': uid\n }\n self.login.insert_one(data)\n return uid\n\n # 设置部分\n def find_by_uid(self, uid):\n res = self.login.find_one({'uid': uid})\n return res\n\n def setting_reset(self, find_res, item, data):\n uid = find_res['uid']\n find_res[item] = data\n cond = {'uid': uid}\n print(data)\n res = self.login.update_one(cond, {'$set': find_res})\n\n # 好友部分\n def friend_add(self, src, dst):\n cond = {'src': src, 'dst': dst}\n res = self.friend.find_one(cond)\n if res is not None:\n res['accept'] = True\n self.friend.update_one(cond, {'$set': res})\n print('{} and {} become friend!'.format(src, dst))\n return\n data = {\n 'src': src,\n 'dst': dst,\n 'accept': False\n }\n self.friend.insert_one(data)\n print('insert data {}'.format(data))\n \n def friend_find(self, src, dst, accept, remove):\n l = []\n cond = {}\n if src != None:\n cond['src'] = src\n if dst != None:\n cond['dst'] = dst\n if accept != None:\n cond['accept'] = accept\n results = self.friend.find(cond)\n for result in results:\n l.append(result)\n if remove == True:\n self.friend.remove(cond)\n return l\n\n def message_add(self, msg):\n data = {\n 'src': msg.src,\n 'dst': msg.dst,\n 'time': msg.time,\n 'text': msg.text,\n 'image': msg.image\n }\n self.message.insert_one(data)\n\n def message_find(self, uid, time):\n l = []\n r1 = self.message.find({'src': uid})\n r2 = self.message.find({'dst': uid})\n for r in r1:\n l.append(r)\n for r in r2:\n l.append(r)\n return l\n \n def post_add(self, post):\n data = {\n 'uid': post.uid,\n 'text': post.text,\n 'image': post.image,\n 'time': post.time,\n 'desc': post.desc,\n 'username': post.username,\n 'nickname': post.nickname,\n 'icon': post.icon\n }\n self.post.insert_one(data)\n return ''\n\n def post_find(self, time):\n res = self.post.find({'time': {'$gt': time}},sort=[(\"time\", -1)])\n t = 0\n l = []\n for r in res:\n l.append(r)\n t += 1\n if t >= 5:\n break\n return l\n\n def __init__(self):\n self.client = pymongo.MongoClient(host='localhost')\n # 在此处更改 db 即可\n self.db = self.client.test2\n # login part\n self.login = self.db.login\n # friend request part\n self.friend = self.db.friend\n # message part\n self.message = self.db.message\n # post part\n self.post = self.db.post\n m = self.login.find_one(sort=[(\"uid\",-1)])\n if m is None:\n self.max_uid = 0\n else:\n self.max_uid = m['uid']\n\n# login 部分: 包含每个用户的用户名,昵称,密码,uid 等信息","sub_path":"Server/src/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"495318396","text":"__author__ = 'Vegard'\nfrom math import pow, sqrt\nfrom heapq import heapify, heappop, heappush\nimport glob\nclass Board:\n\n def __init__(self, file):\n self.board = []\n #Reads in file, saves A and B values, and creates new nodes in a matrix\n with open(file) as fil:\n linjer = fil.readlines()\n self.gridHeight = len(linjer)\n\n for x, linje in enumerate(linjer):\n\n self.board.append([])\n self.gridLength = len(linje)\n for y, char in enumerate(linje):\n if char ==\"\\n\":\n pass\n\n self.board[x].append(Node(x, y, char))\n\n if char==\"A\":\n self.start = (x, y)\n if char==\"B\":\n self.goal = (x, y)\n\n\n\n\n def heuristic(self, cell):\n return abs(cell.x-self.goal[0]) + abs(cell.y-self.goal[1])\n\n\n def bestFirstSearch(self):\n self.closed = []\n self.opened = []\n heapify(self.opened)\n startNode = self.board[self.start[0]][self.start[1]]\n gCost = 0\n hCost = self.heuristic(startNode)\n totalCost = gCost+hCost\n startNode.g = gCost\n startNode.f = totalCost\n heappush(self.opened, (startNode.g, startNode))\n while len(self.opened):\n\n node = heappop(self.opened)[1]\n\n self.closed.append(node)\n #Return with node if it is the final solution\n if node.x==self.goal[0] and node.y==self.goal[1]:\n return self.printPath(node)\n\n\n for neighbour in self.generateSuccessors(node):\n\n #node.children.append(neighbour)\n if neighbour not in self.closed and neighbour.cost!=\"#\":\n\n if (neighbour.g, neighbour) not in self.opened:\n\n self.updateCell(neighbour, node)\n heappush(self.opened, (neighbour.g, neighbour))\n elif node.g+neighbour.cost0:\n children.append(self.board[x-1][y])\n if y >0:\n children.append(self.board[x][y-1])\n if x\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 click\n\nfrom platformio.account.client import AccountClient\n\n\n@click.command(\"logout\", short_help=\"Log out of PlatformIO Account\")\ndef account_logout_cmd():\n client = AccountClient()\n client.logout()\n click.secho(\"Successfully logged out!\", fg=\"green\")\n","sub_path":"platformio/account/commands/logout.py","file_name":"logout.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"550142229","text":"\"\"\"\nBuilt from Alexa Skill example, info here: http://amzn.to/1LzFrj6\n\"\"\"\n\nfrom __future__ import print_function\nimport requests\nimport json\nfrom datetime import datetime\nimport responses\n\nalexa = responses.alexa()\n\n# --------------- Helpers that build all of the responses ---------------------\n\n\ndef build_speechlet_response(title, speech_output, reprompt_text,\n should_end_session, card_output):\n card_text = card_output.replace(\"TinRiss\", \"TNRIS\")\n\n return {\n 'outputSpeech': {\n 'type': 'PlainText',\n 'text': speech_output\n },\n 'card': {\n 'type': 'Simple',\n 'title': title,\n 'content': card_text\n },\n 'reprompt': {\n 'outputSpeech': {\n 'type': 'PlainText',\n 'text': reprompt_text\n }\n },\n 'shouldEndSession': should_end_session\n }\n\n\ndef build_nocard_response(speech_output, reprompt_text, should_end_session):\n return {\n 'outputSpeech': {\n 'type': 'PlainText',\n 'text': speech_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_ssml_response(speech_output, reprompt_text, should_end_session):\n return {\n 'outputSpeech': {\n 'type': 'SSML',\n 'ssml': speech_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 return {\n 'version': '1.0',\n 'sessionAttributes': session_attributes,\n 'response': speechlet_response\n }\n\n\ndef build_nocard(attr, speech, reprompt, end):\n return build_response(attr, build_nocard_response(speech, reprompt, end))\n\n\ndef build_yescard(attr, title, speech, reprompt, end, card):\n return build_response(attr, build_speechlet_response(title, speech,\n reprompt, end, card))\n\n\n# -------------- Functions that control the skill's behavior -----------------\ndef get_welcome_response():\n \"\"\" If we wanted to initialize the session to have some attributes we could\n add those here\n \"\"\"\n\n session_attributes = {}\n speech_output = \"Howdy! Welcome to the Texas Natural Resources \" \\\n \"Information System. \" + alexa.instruction\n # If the user either does not reply to the welcome message or\n # says something that is not understood, they will be prompted again\n # with this text.\n reprompt_text = alexa.instruction\n should_end_session = False\n return build_response(session_attributes, build_nocard_response(\n speech_output, reprompt_text, should_end_session))\n\n\ndef handle_session_end_request():\n speech_output = \"Thanks for chatting with TinRiss. Goodbye.\"\n # Setting this to true ends the session and exits the skill.\n should_end_session = True\n return build_response({}, build_nocard_response(\n speech_output, None, should_end_session))\n\n\ndef create_session_ref(county):\n return {\"county\": county}\n\n\ndef get_county_fips(name):\n with open('counties_lower.json') as json_data:\n d = json.load(json_data)\n lower = name.lower()\n fips = d[lower]\n return fips\n\n\ndef format_year_list(the_list):\n no_none = [value for value in the_list if value is not None]\n return [int(i.split(\"-\")[0]) for i in no_none]\n\n\ndef get_hist_imagery_years(fips):\n url_base = 'https://historical-aerials.tnris.org/api/v1/' \\\n 'records?countyFips='\n url = url_base + str(fips)\n r = requests.get(url)\n imgs = r.json()\n if len(imgs) == 0:\n return 0\n if len(imgs) == 1:\n single_year = imgs[0]['Date']\n try:\n year = single_year.split(\"-\")[0]\n return int(year)\n except:\n return 0\n else:\n try:\n years = [int(i['Date'].split(\"-\")[0]) for i in imgs]\n except:\n init = [i['Date'] for i in imgs]\n years = format_year_list(init)\n\n unique_years = sorted(set(years))\n print(unique_years)\n oldest = unique_years[0]\n newest = unique_years[-1]\n length = len(unique_years)\n return [length, oldest, newest]\n\n\ndef get_imagery_years_list(fips):\n url_base = 'https://historical-aerials.tnris.org/api/v1/' \\\n 'records?countyFips='\n url = url_base + str(fips)\n print(url)\n r = requests.get(url)\n imgs = r.json()\n print(r)\n print(imgs)\n if len(imgs) == 0:\n return 0\n if len(imgs) == 1:\n single_year = imgs[0]['Date']\n try:\n year = single_year.split(\"-\")[0]\n return int(year)\n except:\n return 0\n else:\n try:\n years = [int(i['Date'].split(\"-\")[0]) for i in imgs]\n except:\n init = [i['Date'] for i in imgs]\n years = format_year_list(init)\n\n unique_years = sorted(set(years))\n print(unique_years)\n return unique_years\n\n\ndef confirm_year(years, requested_year):\n multiple = isinstance(years, list)\n year_num = int(requested_year)\n if multiple:\n if year_num in years:\n return True\n else:\n return min(years, key=lambda x: abs(x-year_num))\n elif years == 0:\n return None\n else:\n if year_num == years:\n return True\n else:\n return False\n\n\ndef lookup_session(intent, session):\n \"\"\"\n Looks up general information on file on a county\n \"\"\"\n session_attributes = {}\n should_end_session = False\n\n if 'County' in intent['slots']:\n try:\n historical_county = intent['slots']['County']['value']\n session_attributes = create_session_ref(historical_county)\n fips = get_county_fips(historical_county)\n years = get_hist_imagery_years(fips)\n multiple = isinstance(years, list)\n\n if multiple:\n reprompt_text = alexa.reprompt_1\n text = alexa.imagery_range(historical_county, years[0],\n years[1], years[2])\n speech_output = text + reprompt_text\n elif years == 0:\n reprompt_text = alexa.reprompt_2\n text = alexa.imagery_none(historical_county)\n speech_output = text + reprompt_text\n else:\n reprompt_text = alexa.reprompt_1\n text = alexa.imagery_single(historical_county, years)\n speech_output = text + reprompt_text\n\n card_title = historical_county.title() + \" County\"\n return build_yescard(session_attributes, card_title,\n speech_output, reprompt_text,\n should_end_session, text)\n except:\n speech_output = alexa.confused + \"Please try again.\"\n reprompt_text = alexa.confused + alexa.instruction\n return build_nocard(session_attributes, speech_output,\n reprompt_text, should_end_session)\n else:\n speech_output = alexa.confused + \"Please try again.\"\n reprompt_text = alexa.confused + alexa.instruction\n return build_nocard(session_attributes, speech_output, reprompt_text,\n should_end_session)\n\n\ndef list_years_session(intent, session):\n \"\"\"\n Lists the specific years on file for a county\n \"\"\"\n session_attributes = {}\n should_end_session = False\n\n if session.get('attributes', {}) and \"county\" in session.get('attributes',\n {}):\n session_county = session['attributes']['county']\n else:\n session_county = \"\"\n print(session_county)\n if 'County' in intent['slots']:\n try:\n historical_county = intent['slots']['County']['value']\n if session_county != historical_county:\n session_attributes = create_session_ref(historical_county)\n fips = get_county_fips(historical_county)\n years = get_imagery_years_list(fips)\n multiple = isinstance(years, list)\n\n if multiple:\n reprompt_text = alexa.reprompt_1\n text = alexa.list_range(historical_county, years)\n speech_output = text + reprompt_text\n elif years == 0:\n reprompt_text = alexa.reprompt_2\n text = alexa.imagery_none(historical_county)\n speech_output = text + reprompt_text\n else:\n reprompt_text = alexa.reprompt_1\n text = alexa.imagery_single(historical_county, years)\n speech_output = text + reprompt_text\n\n card_title = historical_county.title() + \" County\"\n return build_yescard(session_attributes, card_title, speech_output,\n reprompt_text, should_end_session, text)\n except:\n try:\n if session_county == \"\":\n msg = 'No county saved in session and no new ' \\\n 'county requested.'\n print(msg)\n raise Exception(msg)\n session_attributes = create_session_ref(session_county)\n fips = get_county_fips(session_county)\n years = get_imagery_years_list(fips)\n multiple = isinstance(years, list)\n\n if multiple:\n reprompt_text = alexa.reprompt_1\n text = alexa.list_range(session_county, years)\n speech_output = text + reprompt_text\n elif years == 0:\n reprompt_text = alexa.reprompt_2\n text = alexa.imagery_none(session_county)\n speech_output = text + reprompt_text\n else:\n reprompt_text = alexa.reprompt_1\n text = alexa.imagery_single(session_county, years)\n speech_output = text + reprompt_text\n\n card_title = session_county.title() + \" County\"\n return build_yescard(session_attributes, card_title,\n speech_output, reprompt_text,\n should_end_session, text)\n except:\n speech_output = alexa.confused + \"Please try again.\"\n reprompt_text = alexa.confused + alexa.instruction\n return build_nocard(session_attributes, speech_output,\n reprompt_text, should_end_session)\n else:\n speech_output = alexa.confused + \"Please try again.\"\n reprompt_text = alexa.confused + alexa.instruction\n\n return build_nocard(session_attributes, speech_output, reprompt_text,\n should_end_session)\n\n\ndef specific_year_session(intent, session):\n \"\"\"\n Verify a specific year on file for a county\n \"\"\"\n session_attributes = {}\n should_end_session = False\n\n if session.get('attributes', {}) and \"county\" in session.get('attributes',\n {}):\n session_county = session['attributes']['county']\n else:\n session_county = \"\"\n print(session_county)\n if 'County' in intent['slots'] and 'ImageryYear' in intent['slots']:\n try:\n historical_county = intent['slots']['County']['value']\n if session_county != historical_county:\n session_attributes = create_session_ref(historical_county)\n try:\n requested_year = intent['slots']['ImageryYear']['value']\n fips = get_county_fips(historical_county)\n years = get_imagery_years_list(fips)\n multiple = isinstance(years, list)\n confirmation = confirm_year(years, requested_year)\n\n if multiple:\n reprompt_text = alexa.reprompt_3\n if confirmation is True:\n text = alexa.affirmative_year(historical_county,\n requested_year)\n else:\n text = alexa.negative_year(historical_county,\n requested_year,\n confirmation)\n speech_output = text + reprompt_text\n elif years == 0:\n reprompt_text = alexa.reprompt_2\n text = alexa.imagery_none(historical_county)\n speech_output = text + reprompt_text\n else:\n reprompt_text = alexa.reprompt_1\n if confirmation is True:\n text = alexa.affirmative_year(historical_county,\n requested_year)\n else:\n text = alexa.negative_year_single(historical_county,\n requested_year,\n years)\n speech_output = text + reprompt_text\n\n card_title = historical_county.title() + \" County\"\n return build_yescard(session_attributes, card_title,\n speech_output, reprompt_text,\n should_end_session, text)\n except:\n speech_output = alexa.confused_2 + \"Please try again.\"\n reprompt_text = alexa.confused_2 + alexa.instruction\n return build_nocard(session_attributes, speech_output,\n reprompt_text, should_end_session)\n\n except:\n try:\n if session_county == \"\":\n msg = 'No county saved in session and no new ' \\\n 'county requested.'\n print(msg)\n raise Exception(msg)\n else:\n session_attributes = create_session_ref(session_county)\n\n try:\n requested_year = intent['slots']['ImageryYear']['value']\n fips = get_county_fips(session_county)\n years = get_imagery_years_list(fips)\n multiple = isinstance(years, list)\n confirmation = confirm_year(years, requested_year)\n\n if multiple:\n reprompt_text = alexa.reprompt_3\n if confirmation is True:\n text = alexa.affirmative_year(session_county,\n requested_year)\n else:\n text = alexa.negative_year(session_county,\n requested_year,\n confirmation)\n speech_output = text + reprompt_text\n elif years == 0:\n reprompt_text = alexa.reprompt_2\n text = alexa.imagery_none(session_county)\n speech_output = text + reprompt_text\n else:\n reprompt_text = alexa.reprompt_1\n if confirmation is True:\n text = alexa.affirmative_year(session_county,\n requested_year)\n else:\n text = alexa.negative_year_single(session_county,\n requested_year,\n years)\n speech_output = text + reprompt_text\n\n card_title = session_county.title() + \" County\"\n return build_yescard(session_attributes, card_title,\n speech_output, reprompt_text,\n should_end_session, text)\n except:\n speech_output = alexa.confused_2 + \"Please try again.\"\n reprompt_text = alexa.confused_2 + alexa.instruction\n\n return build_nocard(session_attributes, speech_output,\n reprompt_text, should_end_session)\n\n except:\n speech_output = alexa.confused + \"Please try again.\"\n reprompt_text = alexa.confused + alexa.instruction\n\n return build_nocard(session_attributes, speech_output,\n reprompt_text, should_end_session)\n else:\n speech_output = alexa.confused + \"Please try again.\"\n reprompt_text = alexa.confused + alexa.instruction\n\n return build_nocard(session_attributes, speech_output, reprompt_text,\n should_end_session)\n\n\ndef band_session(intent, session):\n \"\"\"\n Easter Egg\n \"\"\"\n session_attributes = {}\n should_end_session = True\n\n if session.get('attributes', {}) and \"county\" in session.get('attributes',\n {}):\n session_county = session['attributes']['county']\n session_attributes = create_session_ref(session_county)\n speech_output = \"Oh, that's an easy one. Primus is the greatest \" \\\n \"band in the world. Well, I don't \" \\\n \"know. It could be \" \\\n \"Led Zeppelin. Nah, it's definitely \" \\\n \"Primus.\"\n reprompt_text = alexa.instruction\n return build_response(session_attributes, build_ssml_response(\n speech_output, reprompt_text, should_end_session))\n\n# --------------- Events ------------------\n\n\ndef on_session_started(session_started_request, session):\n \"\"\" Called when the session starts \"\"\"\n\n print(\"on_session_started requestId=\" +\n 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 print(\"on_intent requestId=\" + intent_request['requestId'] +\n \", sessionId=\" + session['sessionId'])\n\n intent = intent_request['intent']\n intent_name = intent_request['intent']['name']\n print(intent_name)\n\n # Dispatch to your skill's intent handlers\n if intent_name == \"SpecificYearIntent\":\n return specific_year_session(intent, session)\n elif intent_name == \"ListYearsIntent\":\n return list_years_session(intent, session)\n elif intent_name == \"LookupIntent\":\n return lookup_session(intent, session)\n elif intent_name == \"BandIntent\":\n return band_session(intent, session)\n elif intent_name == \"AMAZON.HelpIntent\":\n return get_welcome_response()\n elif (intent_name == \"AMAZON.CancelIntent\" or\n 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 \"\"\"\n Uncomment this if statement and populate with your skill's application ID\n to prevent someone else from configuring a skill that sends requests to\n this 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\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","sub_path":"lambda-code/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":21510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"157570170","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport re\nimport requests\nimport bs4\nimport pymysql\nimport time\n# 打开数据库连接\ndb = pymysql.connect(\"101.132.195.63\", \"rc\", \"rc123\", \"pydb\", charset='utf8')\n# 使用 cursor() 方法创建一个游标对象 cursor\ncursor = db.cursor()\nprint('start')\nm = 1\nwhile m <= 73:\n\n # 要抓取的目标页码地址\n # url = 'http://list.mogujie.com/book/accessories/10061955?mt=12.18940.r153160.24443&acm=3.mce.1_10_188k2.18940..iOPIAqQwjmQFc.pos_0-m_192141-sd_119-mf_15261_944839-idx_0-mfs_46-dm1_5000&ptp=1._mf1_1239_15261.0.0.mVsdTMSI'\n # url = 'https://search.51job.com/list/020000,000000,0000,00,9,99,Java%25E5%25BC%2580%25E5%258F%2591%25E5%25B7%25A5%25E7%25A8%258B%25E5%25B8%2588,2,1.html?lang=c&stype=1&postchannel=0000&workyear=99&cotype=99°reefrom=99&jobterm=99&companysize=99&lonlat=0%2C0&radius=-1&ord_field=0&confirmdate=9&fromType=&dibiaoid=0&address=&line=&specialarea=00&from=&welfare='\n url = 'https://search.51job.com/list/020000,000000,0000,00,9,99,Java%25E5%25BC%2580%25E5%258F%2591%25E5%25B7%25A5%25E7%25A8%258B%25E5%25B8%2588,2,' + '%d' % m + \\\n '.html?lang=c&stype=1&postchannel=0000&workyear=99&cotype=99°reefrom=99&jobterm=99&companysize=99&lonlat=0%2C0&radius=-1&ord_field=0&confirmdate=9&fromType=&dibiaoid=0&address=&line=&specialarea=00&from=&welfare='\n print('url is :' + url)\n m = m + 1\n # 抓取页码内容,返回响应对象\n response = requests.get(url)\n\n encod = response.encoding\n # print(encod)\n # 查看响应状态码\n status_code = response.status_code\n # print(status_code)\n content = bs4.BeautifulSoup(\n response.content.decode(encod).encode(encod), \"lxml\")\n # print(content)\n\n texts = content.find_all('div', class_='el')\n\n jobinfo = texts[17:len(texts)]\n # print(jobinfo)\n for infos in jobinfo:\n t1info = infos.find_all('p', class_='t1')\n t2info = infos.find_all('span', class_='t2')\n t3info = infos.find_all('span', class_='t3')\n t4info = infos.find_all('span', class_='t4')\n t5info = infos.find_all('span', class_='t5')\n a, b, c, d, e, f, g, h = '0', '1', '2', '3', '4', '5', '6', '51job'\n for t1 in t1info:\n t1hr = t1.find('a')\n t1strs = t1hr['href']\n e = t1strs\n # c = t1hr.text.split()\n for cs in t1hr.text.split():\n c = cs\n print(c)\n # print(t1strs + '---------' + t1hr.text)\n for t2 in t2info:\n t2hr = t2.find('a')\n t2strs = t2hr['href']\n f = t2strs\n b = t2hr.text\n # print(t2strs + '---------' + t2hr.text)\n for t3 in t3info:\n d = t3.text\n # print('---------' + t3.text)\n for t4 in t4info:\n # print('---------' + t4.text)\n g = t4.text\n for t5 in t5info:\n # print('---------' + t5.text)\n a = t5.text\n cursor.execute('insert into wuyoujob (public_date, companyname, title, work_add,job_url,company_url,salary,source) values(%s,%s,%s,%s,%s,%s,%s,%s)', (\n a, b, c, d, e, f, g, h))\n\n # 提交到数据库执行\n db.commit()\n # sleep(5)\nprint('end')\n","sub_path":"jobtitle.py","file_name":"jobtitle.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"60357985","text":"def medianfilter(img1,height,width):\n import numpy as np\n #import math\n a=0\n b=0\n q=[]\n img2=np.zeros((height,width,1),np.uint8)\n #img2=img1\n for d in range(1):\n\n for h in range(3,height,+3):\n for w in range(3,width,+3):\n q=[]\n for i in range(a,h):\n for j in range(b,w):\n q=[img1[i,j],img1[i,j-1],img1[i,j+1],img1[i-1,j],img1[i-1,j-1],img1[i-1,j+1],img1[i+1,j],img1[i+1,j+1],img1[i+1,j-1]]\n img2[i,j]=int(np.median(q))\n \n b=w\n a=h\t\t\n return img2\n \n\n","sub_path":"medianfilter.py","file_name":"medianfilter.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"54766029","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\"\"\"\n @file ProjectEuler/0004.py\n @author SHawnHardy\n @date 2020-04-25\n @copyright MIT License\n\"\"\"\n\nimport sys\n\nsys.setrecursionlimit(1000000)\n\nans = 101 * 101\nfor i in range(100, 1000):\n for j in range(ans // i + 1, 1000):\n num = str(i * j)\n if num == num[::-1]:\n ans = i * j\nprint(ans)\n# 906609\n","sub_path":"ProjectEuler/0004.py","file_name":"0004.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"293280143","text":"from bs4 import BeautifulSoup\nimport requests\nimport json\n\nr = requests.get('https://www.airbnb.com/s/Paris--France?guests=&checkin=11%2F16%2F2015&checkout=11%2F20%2F2015&ss_id=zru0ehp2&source=bb')\n\nairbnbSoup = BeautifulSoup(r.content)\n\nprices = airbnbSoup.find_all(\"span\", {\"class\": \"price-amount\"})\nnames = airbnbSoup.find_all(\"h3\", {\"class\": \"listing-name\"})\n\npricesText = [];\nnamesText = [];\ndata = [];\n\nindex = 0;\nfor p in prices:\n pricesText.append(p.text.strip())\n namesText.append(names[index].find('a').text.strip())\n data.append({'price': p.text.strip(), 'description': names[index].find('a').text.strip()})\n index += 1\n\n\n\n\nwith open(\"parisText.json\", \"w\") as outfile:\n json.dump({'data': data}, outfile, indent=4)","sub_path":"parisPython.py","file_name":"parisPython.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"238268917","text":"from keras.models import load_model\nfrom keras.preprocessing import image\nimport numpy as np\n\nimport socket\nimport time\n\n\n\nimg_width, img_height = 160, 120\n\n\nmodel = load_model('./data/models/beispiel1.h5')\nmodel.compile(loss='binary_crossentropy',optimizer='rmsprop', metrics=['accuracy'])\n\n\nimg = image.load_img('picture.png', target_size=(img_width, img_height))\nx = image.img_to_array(img)\nx = np.expand_dims(x, axis=0)\n\nclasses = model.predict_classes(x, batch_size=128)\nfor i in classes:\n\tprint(i[0])\n\tif i == 0:\n\t\tip = \"192.168.178.103\"\n\t\ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM) \n\t\ts.connect((ip, 50002))\n\t\ts.send(b\"forward_go\")\n\t\ts.close()\n\n\tif i == 1:\n\t\tprint(\"Hindernis erkannt!\")\n","sub_path":"ML_AP/beispiel1/code/keras/predict_test.py","file_name":"predict_test.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"251797448","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 03 15:26:49 2016\n\n@author: jzhu0922\n\"\"\"\n\nfrom pylab import *\n\nsubplot(2,2,1)\nxticks([]), yticks([])\ntext(0.5,0.5, 'subplot(2,2,1)',ha='center',va='center',size=20,alpha=.5)\n\nsubplot(2,2,2)\nxticks([]), yticks([])\ntext(0.5,0.5, 'subplot(2,2,2)',ha='center',va='center',size=20,alpha=.5)\n\nsubplot(2,2,3)\nxticks([]), yticks([])\ntext(0.5,0.5, 'subplot(2,2,3)',ha='center',va='center',size=20,alpha=.5)\n\nsubplot(2,2,4)\nxticks([]), yticks([])\ntext(0.5,0.5, 'subplot(2,2,4)',ha='center',va='center',size=20,alpha=.5)\n\n# savefig('../figures/subplot-grid.png', dpi=64)\nshow()\n\n\n#=================gridspec==========================================\n\nimport matplotlib.gridspec as gridspec\n\nG = gridspec.GridSpec(3, 3)\n\naxes_1 = subplot(G[0, :])\nxticks([]), yticks([])\ntext(0.5,0.5, 'Axes 1',ha='center',va='center',size=24,alpha=.5)\n\naxes_2 = subplot(G[1,:-1])\nxticks([]), yticks([])\ntext(0.5,0.5, 'Axes 2',ha='center',va='center',size=24,alpha=.5)\n\naxes_3 = subplot(G[1:, -1])\nxticks([]), yticks([])\ntext(0.5,0.5, 'Axes 3',ha='center',va='center',size=24,alpha=.5)\n\naxes_4 = subplot(G[-1,0])\nxticks([]), yticks([])\ntext(0.5,0.5, 'Axes 4',ha='center',va='center',size=24,alpha=.5)\n\naxes_5 = subplot(G[-1,-2])\nxticks([]), yticks([])\ntext(0.5,0.5, 'Axes 5',ha='center',va='center',size=24,alpha=.5)\n\n#plt.savefig('../figures/gridspec.png', dpi=64)\nshow()\n\n\n#==================axes===============================================\n\naxes([0.1,0.1,.8,.8])\nxticks([]), yticks([])\ntext(0.1,0.1, 'axes([0.1,0.1,.8,.8])',ha='left',va='center',size=16,alpha=.5)\n\naxes([0.2,0.2,.5,.5])\nxticks([]), yticks([])\ntext(0.1,0.1, 'axes([0.2,0.2,.5,.5])',ha='left',va='center',size=16,alpha=.5)\n\naxes([0.3,0.3,.5,.5])\nxticks([]), yticks([])\ntext(0.1,0.1, 'axes([0.3,0.3,.5,.5])',ha='left',va='center',size=16,alpha=.5)\n\naxes([0.4,0.4,.5,.5])\nxticks([]), yticks([])\ntext(0.1,0.1, 'axes([0.4,0.4,.5,.5])',ha='left',va='center',size=16,alpha=.5)\n\n# plt.savefig(\"../figures/axes-2.png\",dpi=64)\nshow()\n\n#==================grid============================\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nax = plt.axes([0.025,0.025,0.95,0.95])\n\nax.set_xlim(0,4)\nax.set_ylim(0,3)\nax.xaxis.set_major_locator(plt.MultipleLocator(1.0))\nax.xaxis.set_minor_locator(plt.MultipleLocator(0.1))\nax.yaxis.set_major_locator(plt.MultipleLocator(1.0))\nax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))\nax.grid(which='major', axis='x', linewidth=0.75, linestyle='-', color='0.75')\nax.grid(which='minor', axis='x', linewidth=0.25, linestyle='-', color='0.75')\nax.grid(which='major', axis='y', linewidth=0.75, linestyle='-', color='0.75')\nax.grid(which='minor', axis='y', linewidth=0.25, linestyle='-', color='0.75')\nax.set_xticklabels([])\nax.set_yticklabels([])\n\n# savefig('../figures/grid_ex.png',dpi=48)\nplt.show()\n\n\n","sub_path":"2-Matplotlib/subplot_axes.py","file_name":"subplot_axes.py","file_ext":"py","file_size_in_byte":2817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"602931896","text":"#!/usr/bin/python\n\n\"\"\"\nmultitasking.managers.base\n\"\"\"\n\nimport gevent\nimport logging\nimport logging.handlers\nimport signal\nimport sys\n\nfrom gevent import socket as _socket\n\nfrom multitasking.util.exceptions import StopTaskException\n\nclass TaskManager(object):\n \"\"\"\n Manager of tasks.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Create a new instance of a TaskManager.\n \"\"\"\n self._tasks = []\n self._logger = self._setup_logging()\n gevent.signal(signal.SIGINT, self.stop)\n\n def __repr__(self):\n \"\"\"\n The name of the TaskManager should be enough representation.\n \"\"\"\n return self.__class__.__name__\n\n def _setup_logging(self):\n \"\"\"\n Setup logging for this TaskManager.\n \"\"\"\n logger = logging.getLogger(self.__class__.__name__)\n logger.setLevel(logging.DEBUG)\n\n format_str = \"[MT] %(name)s - %(levelname)s - %(message)s\"\n formatter = logging.Formatter(format_str)\n\n syslog_handler = logging.handlers.SysLogHandler(address='/dev/log', facility='daemon')\n syslog_handler.setLevel(logging.DEBUG)\n syslog_handler.setFormatter(formatter)\n\n logger.addHandler(syslog_handler)\n\n return logger\n\n def stop(self):\n \"\"\"\n Called when this task manager should stop.\n \"\"\"\n for task in self._tasks:\n if task.started and not task.successful():\n task.kill(exception=StopTaskException, block=False)\n gevent.joinall(self._tasks)\n\n def execute(self, task, *args):\n \"\"\"\n Execute the given task. This task manager executes tasks locally,\n and all communications between tasks occurs over sockets.\n\n @param task: The task to run.\n @param args: Any arguments to pass to the task.\n \"\"\"\n # Create two connected sockets\n sock_one, sock_two = _socket.socketpair()\n\n # Assign one of the sockets to the task\n task = task(self)\n task._socket = sock_one\n\n # Start the task\n self._tasks.append(gevent.spawn(task, *args))\n\n # Return the other socket\n return sock_two\n\n def join(self):\n \"\"\"\n Join the manager, blocking until all tasks are complete.\n \"\"\"\n gevent.joinall(self._tasks)\n","sub_path":"multitasking/managers/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"360432885","text":"import sqlite3 as sq\n\n\nclass DataBase:\n\tdef __init__(self, path):\n\t\tself.path = path\n\n\t\"\"\" Connect to Data Base \"\"\"\n\tdef connect(self):\n\t\ttry:\n\t\t\tself.conn = sq.connect(str(self.path))\n\t\t\tself.cursor = self.conn.cursor()\n\t\texcept Exception as e:\n\t\t\tprint(\"[ERROR] File DataBase error: \" + e)\n\n\t\"\"\" Close \"\"\"\n\tdef close(self):\n\t\tself.cursor.close()\n\t\tself.conn.close()\n\t\tprint(\"[INFO] Close connect to database, and close cursor\")\n\t\t\n\t\"\"\" Add in Data Base \"\"\"\n\tdef insert(self, nameTable:str, paramArray):\n\t\tself.connect()\n\t\trequest = 'INSERT INTO ' + nameTable + ' VALUES(?, ?)'\n\t\tself.cursor.execute(request, paramArray)\n\n\t\tself.conn.commit()\n\t\tself.close()\n\n\tdef insert_status(self, name:str, author:str):\n\t\tself.connect()\n\t\tself.cursor.execute('''INSERT INTO status(name, author) VALUES(?, ?)''', (name, author))\n\n\t\tself.conn.commit()\n\t\tself.close()\n\n\tdef insert_users(self, funcType:int, user:str, money:int=None, vip:int=None):\n\t\tself.connect()\n\n\t\tif funcType == 1:\n\t\t\ttry:\n\t\t\t\tself.cursor.execute('''INSERT INTO users(user) VALUES(?) ''', (str(user),))\n\t\t\texcept sqlite3.IntegrityError as e:\n\t\t\t\tprint('[ERROR] sqlite3 ' + e)\n\n\t\telif funcType == 2:\n\t\t\tself.cursor.execute()\n\n\t\tself.conn.commit()\n\t\tself.close()\n\n\tdef insert_guild(self, funcType:int, guild_id, guild_name=None, channel=None):\n\t\tself.connect()\n\n\t\tif funcType == 1 and channel == None:\n\t\t\ttry:\n\t\t\t\tself.cursor.execute('''INSERT INTO guild(guild_id, guild_name) VALUES(?, ?)''', (guild_id, guild_name))\n\t\t\texcept Exception as e:\n\t\t\t\tprint('[ERROR] sqlite3 ' + e)\n\n\t\telse:\n\t\t\tprint(\"[ERROR] sqlite3: No func\")\n\n\t\tself.conn.commit()\n\t\tself.close()\n\n\t\"\"\" Update in Data Base \"\"\"\n\tdef update_guild(self, funcType:int, guild_id, channel_join=None):\n\t\tself.connect()\n\n\t\tif funcType == 1 and channel_join != None :\n\t\t\tself.cursor.execute(\"\"\"UPDATE guild SET channel_join=? WHERE guild_id=? \"\"\", (channel_join, guild_id))\n\t\telse:\n\t\t\tpass\n\n\t\tself.conn.commit()\n\t\tself.close()\n\n\t\"\"\" Remove in Data Base \"\"\"\n\tdef delete(self, nameTable:str, func:str):\n\t\tself.connect()\n\t\trequest = '''DELETE FROM {0} {1}'''.format(nameTable, func)\n\t\tself.cursor.execute(request)\n\t\tself.conn.commit()\n\t\tself.close()\n\n\tdef delete_status(self, id):\n\t\tself.connect()\n\t\t\n\t\ttry:\n\t\t\tself.cursor.execute('''DELETE FROM status WHERE id=?''', (id,))\n\n\t\texcept Exception as e:\n\t\t\traise e\n\n\t\tself.conn.commit()\n\t\tself.close()\n\n\tdef delete_guild(self, id):\n\t\tself.connect()\n\t\t\n\t\ttry:\n\t\t\tself.cursor.execute('''DELETE FROM guild WHERE guild_id=?''', (int(id),))\n\n\t\texcept Exception as e:\n\t\t\tprint(\"[ERROR] sqlite3 \" + e)\n\n\t\tself.conn.commit()\n\t\tself.close()\n\n\t\"\"\" Select in Data Base \"\"\"\n\tdef _select_order_by(self, nameTable:str, sort:str):\n\t\tself.connect()\n\t\ttry:\n\t\t\trequest = 'SELECT * FROM {0} ORDER BY {1}'.format(nameTable, sort)\n\t\t\tself.cursor.execute(request)\n\t\t\tdata = self.cursor.fetchall()\n\t\t\treturn data\n\t\texcept Exception as e:\n\t\t\tprint(\"[ERROR] sqlite3 \" + e)\n\t\tself.close()\n\n\tdef _select_where(self, nameTable:str, elements:str, lines:str):\n\t\tself.connect()\n\t\ttry:\n\t\t\trequest = \"SELECT * FROM {0} WHERE {1}=?\".format(nameTable, elements)\n\t\t\tself.cursor.execute(request, (lines,))\n\t\t\tdata = self.cursor.fetchall()\n\t\t\treturn data\n\t\texcept Exception as e:\n\t\t\tprint(\"[ERROR] sqlite3 \" + e)\n\t\tself.close()\n\n\tdef _select_all(self, nameTable:str):\n\t\tself.connect()\n\t\ttry:\n\t\t\trequest = 'SELECT * FROM {0}'.format(nameTable,)\n\t\t\tself.cursor.execute(request)\n\t\t\tdata = self.cursor.fetchall()\n\t\t\treturn data\n\t\texcept Exception as e:\n\t\t\tprint(\"[ERROR] sqlite3 \" + e)\n\t\tself.close()","sub_path":"DataBase.py","file_name":"DataBase.py","file_ext":"py","file_size_in_byte":3512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"408304325","text":"import pytest\nimport sys\nimport os\n\nsys.path.insert(0, os.path.abspath('.'))\nsys._called_from_test = True\n\nimport main\n\n\n@pytest.fixture\ndef app():\n return main.app\n\n\n@pytest.fixture\ndef test_client(app):\n return app.test_client()\n\n\ndef test_title(test_client):\n if hasattr(sys, '_called_from_test'):\n print(\"called from a test\")\n response = test_client.get(\"/\")\n assert \"Check Yo Self\" in response.data.decode(\"utf-8\")\n\n\ndef test_text_box(test_client):\n response = test_client.get(\"/\")\n assert \"Write something here to have it spell checked!\" in response.data.decode(\"utf-8\")\n","sub_path":"tests/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"608153974","text":"import requests , json , argparse , sys , socket\nfrom termcolor import colored\ntry:\n import requests.packages.urllib3\n requests.packages.urllib3.disable_warnings()\nexcept:\n pass\ndef banner():\n print(\"\"\"\n _ __ _ _ \n | | / / | | (_) \n | |/ / ___ _ __ ___ | |__ _ _ __ ___ \n | \\ / _ \\| '_ \\ / __|| '_ \\ | || '__| / _ \\ \n | |\\ \\| __/| | | |\\__ \\| | | || || | | (_) |\n \\_| \\_/ \\___||_| |_||___/|_| |_||_||_| \\___/ \n Create By InfinitumIT \n { omae wa mou shindeiru! Nani? } \n \"\"\")\ndef parser_error():\n banner()\n if sys.argv[0]==None:\n print(\"Usage: python \" + sys.argv[0] + \" [Options] use -h for help\")\n sys.exit()\n else:\n pass\ndef parse_args():\n # parse the arguments\n parser = argparse.ArgumentParser(description='Web Information Gathering Tool.')\n parser.add_argument('-m', action=\"store\", help='Modules : header or domain .Usage:[-m header]')\n parser.add_argument('-f', action=\"store\", help='Url list load from path. Do not add https:// tag.')\n parser.add_argument('-o', action=\"store\" , help='Output File path.')\n return parser.parse_args()\n# Header Security Checker\n\ndef headersecurity(file):\n whitelist = [\"X-Frame-Options\",\"Strict-Transport-Security\",\"X-XSS-Protection\",\"X-Content-Type-Options\", \"Content-Security-Policy\"] \n with open(file) as fp: \n line = fp.readline()\n while line:\n user_agent = {'User-agent': 'Mozilla/5.0'}\n r = requests.get(line.strip(), headers=user_agent,verify=False)\n print(\"\\nScan Url -> \" + line.strip())\n for whiteitem in whitelist:\n if whiteitem in r.headers:\n print(colored(whiteitem, 'white'), colored(' available', 'green'))\n else:\n print(colored(whiteitem, 'white'), colored(' not available.', 'red'))\n line = fp.readline() \n# Domain To Ip Address Converter\ndef domaintoip(file):\n with open(file) as fp: \n line = fp.readline()\n while line:\n print(colored(\"Host: \" , 'red'), colored(line.strip() , 'white' ) , colored(\" IP: \", 'red'), colored(socket.gethostbyname(line.strip()), 'white'))\n line = fp.readline()\ndef DnsResolver(file):\n with open(file) as fp: \n line = fp.readline()\n while line:\n reversed_dns = socket.gethostbyaddr(line.strip())\n print(colored(\"Host: \" , 'red'), colored(line.strip() , 'white' ) , colored(\" DNS: \", 'red'), colored(reversed_dns[0], 'white'))\n line = fp.readline()\n#Main\ndef main():\n parser_error()\n args = parse_args()\n if (args.m == \"header\"): \n headersecurity(args.f)\n elif (args.m == \"domain\"):\n domaintoip(args.f)\n elif (args.m == \"dnsresolve\"):\n DnsResolver(args.f)\n#Load Main\nmain()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"616417904","text":"def maxoccchar(text):\r\n max_l=-1\r\n text=list(text)\r\n for i in text:\r\n if(text.count(i)>max_l):\r\n max_l=text.count(i)\r\n string = i \r\n return(string)\r\nprint(maxoccchar(\"bbbaaacc\"))\r\n\r\n","sub_path":"maximum_occuring_char.py","file_name":"maximum_occuring_char.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"104518878","text":"import numpy as nmp\r\nimport math\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom scipy.integrate import odeint\r\n\r\na_1 = 7\r\nb_1 = 3.00\r\n\r\nTime_null = 0\r\nTime_Max = 37\r\nStep = 0.05\r\n\r\nt = nmp.arange(Time_null, Time_Max, Step)\r\nt = nmp.append(t, Time_Max)\r\n\r\ndef p(t):\r\n\treturn 0\r\n\r\ndef syst(x,t):\r\n\treturn x[1], -a_1 * a_1 * x[0] - b_1 * x[1] - p(t)\r\n\r\nv0 = (1, 1.2)\r\n\r\nyf = odeint(syst, v0, t)\r\n\r\nx = []\r\ny = []\r\n\r\nfor i in range(len(yf)):\r\n\tx.append(yf[i][0])\r\n\ty.append(yf[i][1])\r\n\r\nplt.figure(figsize = (10,10))\r\nplt.plot(x,y,'r', label = 'x')\r\nplt.show()\r\n","sub_path":"lab 4/lab4 2.py","file_name":"lab4 2.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"580317245","text":"from django.conf.urls import url\nfrom api import views\n\nurlpatterns = [\n url(r'^offers/$', views.OfferListAPIView.as_view(),\n name='offers-list-api'),\n url(r'^offers/(?P[0-9]+)/$', views.OfferDetailAPIView.as_view(),\n name='offer-detail-api'),\n url(r'^categories/$', views.CategoryListAPIView.as_view(),\n name='category-list-api'),\n url(r'^categories/(?P[0-9]+)/$', views.CategoryDetailAPIView.as_view(),\n name='category-detail-api'),\n url(r'statistics/$', views.StatisticsAPIView.as_view(),\n name='statistics-api'),\n]\n","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"565560160","text":"import argparse\nimport base64\nimport json\nimport sys\nimport random\nimport logging\nimport threading\n\nimport dns.query\nimport dns.message\nimport dns.rdatatype\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(logging.StreamHandler(sys.stderr))\nlogger.setLevel(logging.INFO)\n\nrdtypes = [dns.rdatatype.A, dns.rdatatype.AAAA, dns.rdatatype.MX, dns.rdatatype.TXT, dns.rdatatype.SRV]\nresolvers = ['1.1.1.1', '8.8.8.8', '9.9.9.9', '208.67.222.222', '64.6.64.6']\n\nlock = threading.Lock()\n\ndef query_worker(infile: str, outfile: str):\n def read_data():\n _results = []\n with open(infile, 'r') as fp:\n for line in fp:\n qname = line.strip().split(',')[1] + '.'\n for t in rdtypes:\n q = dns.message.make_query(qname, t)\n q.use_edns(True)\n where = random.choice(resolvers)\n try:\n ans = dns.query.udp(q, where=where, timeout=2)\n except dns.exception.Timeout:\n continue\n except Exception as e:\n logger.exception(e)\n continue\n else:\n _results.append((base64.b64encode(q.to_wire()).decode(), base64.b64encode(ans.to_wire()).decode()))\n logger.info('{} -> {} ? {}'.format(qname, where, dns.rcode.to_text(ans.rcode())))\n return _results\n try:\n results = read_data()\n except Exception as e:\n logger.exception(e)\n else:\n with lock, open(outfile, 'a') as out:\n for r in results:\n print(json.dumps(r), file=out)\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('domain_files', nargs='+', help='Files with domains in them to resolve')\n parser.add_argument('-o', '--output', required=True, help='Output file to store queries and responses in')\n args = parser.parse_args()\n threads = []\n for file in args.domain_files:\n t = threading.Thread(target=query_worker, args=(file, args.output))\n t.daemon = True\n t.start()\n threads.append(t)\n for t in threads:\n t.join()\n\nif __name__ == '__main__':\n main()","sub_path":"deepresolver/scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"452603963","text":"#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n#转换颜色空间\r\n#在 OpenCV 的 HSV 格式中,H(色彩/色度)的取值范围是 [0,179], S(饱和度)的取值范围 [0,255],V(亮度)的取值范围 [0,255]。但是不同的软件使用的值可能不同。所以当你拿 OpenCV 的 HSV 值与其他软件的 HSV 值对比时,一定要记得归一化。\r\nimport cv2\r\nimport numpy as np\r\n\r\ncap = cv2.VideoCapture(0)\r\n\r\nwhile(1):\r\n #获取每一帧\r\n ret,frame = cap.read()\r\n #转换到HSV\r\n hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)\r\n #设定蓝色的阀值\r\n lower_blue = np.array([110,50,50])\r\n upper_blue = np.array([130,255,255])\r\n #根据阀值构建掩模\r\n mask = cv2.inRange(hsv,lower_blue,upper_blue)\r\n #对原图和掩模进行位运算\r\n res = cv2.bitwise_and(frame,frame,mask=mask)\r\n #显示图像\r\n cv2.imshow('frame',frame)\r\n cv2.imshow('mask',mask)\r\n cv2.imshow('res',res)\r\n k = cv2.waitKey(5)&0xFF\r\n if k == 27:\r\n break\r\n#关闭窗口\r\ncv2.destroyAllWindows()","sub_path":"转换颜色空间.py","file_name":"转换颜色空间.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"118925398","text":"\"\"\"\n@difficulty: easy\n@tags: misc\n@notes: max(abs(x1 - x0), abs(y1 - y0)) is the diff between nodes.\n\"\"\"\nclass Solution:\n def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:\n total = 0\n x0, y0 = points[0]\n for i in range(1, len(points)):\n x1, y1 = points[i]\n total += max(abs(x1 - x0), abs(y1 - y0))\n x0, y0 = x1, y1\n return total\n","sub_path":"solution/python/1266.py","file_name":"1266.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"457520108","text":"KNOWN_CODES = {\n 'af': 'ZA',\n 'agq': 'CM',\n 'ak': 'GH',\n 'am': 'ET',\n 'ar': 'AE',\n 'as': 'IN',\n 'asa': 'TZ',\n 'az': 'AZ',\n 'bas': 'CM',\n 'be': 'BY',\n 'bem': 'ZM',\n 'bez': 'IT',\n 'bg': 'BG',\n 'bm': 'ML',\n 'bn': 'BD',\n 'bo': 'CN',\n 'br': 'FR',\n 'brx': 'IN',\n 'bs': 'BA',\n 'ca': 'ES',\n 'cgg': 'UG',\n 'chr': 'US',\n 'cs': 'CZ',\n 'cy': 'GB',\n 'da': 'DK',\n 'dav': 'KE',\n 'de': 'DE',\n 'dje': 'NE',\n 'dua': 'CM',\n 'dyo': 'SN',\n 'ebu': 'KE',\n 'ee': 'GH',\n 'en': 'GB',\n 'el': 'GR',\n 'es': 'ES',\n 'et': 'EE',\n 'eu': 'ES',\n 'ewo': 'CM',\n 'fa': 'IR',\n 'fil': 'PH',\n 'fr': 'FR',\n 'ga': 'IE',\n 'gl': 'ES',\n 'gsw': 'CH',\n 'gu': 'IN',\n 'guz': 'KE',\n 'gv': 'GB',\n 'ha': 'NG',\n 'haw': 'US',\n 'he': 'IL',\n 'hi': 'IN',\n 'ff': 'CN',\n 'fi': 'FI',\n 'fo': 'FO',\n 'hr': 'HR',\n 'hu': 'HU',\n 'hy': 'AM',\n 'id': 'ID',\n 'ig': 'NG',\n 'ii': 'CN',\n 'is': 'IS',\n 'it': 'IT',\n 'ja': 'JP',\n 'jmc': 'TZ',\n 'ka': 'GE',\n 'kab': 'DZ',\n 'ki': 'KE',\n 'kam': 'KE',\n 'mer': 'KE',\n 'kde': 'TZ',\n 'kea': 'CV',\n 'khq': 'ML',\n 'kk': 'KZ',\n 'kl': 'GL',\n 'kln': 'KE',\n 'km': 'KH',\n 'kn': 'IN',\n 'ko': 'KR',\n 'kok': 'IN',\n 'ksb': 'TZ',\n 'ksf': 'CM',\n 'kw': 'GB',\n 'lag': 'TZ',\n 'lg': 'UG',\n 'ln': 'CG',\n 'lt': 'LT',\n 'lu': 'CD',\n 'lv': 'LV',\n 'luo': 'KE',\n 'luy': 'KE',\n 'mas': 'TZ',\n 'mfe': 'MU',\n 'mg': 'MG',\n 'mgh': 'MZ',\n 'ml': 'IN',\n 'mk': 'MK',\n 'mr': 'IN',\n 'ms': 'MY',\n 'mt': 'MT',\n 'mua': 'CM',\n 'my': 'MM',\n 'naq': 'NA',\n 'nb': 'NO',\n 'nd': 'ZW',\n 'ne': 'NP',\n 'nl': 'NL',\n 'nmg': 'CM',\n 'nn': 'NO',\n 'nus': 'SD',\n 'nyn': 'UG',\n 'om': 'ET',\n 'or': 'IN',\n 'pa': 'PK',\n 'pl': 'PL',\n 'ps': 'AF',\n 'pt': 'PT',\n 'rm': 'CH',\n 'rn': 'BI',\n 'ro': 'RO',\n 'ru': 'RU',\n 'rw': 'RW',\n 'rof': 'TZ',\n 'rwk': 'TZ',\n 'saq': 'KE',\n 'sbp': 'TZ',\n 'seh': 'MZ',\n 'ses': 'ML',\n 'sg': 'CF',\n 'shi': 'MA',\n 'si': 'LK',\n 'sk': 'SK',\n 'sl': 'SI',\n 'sn': 'ZW',\n 'so': 'SO',\n 'sq': 'AL',\n 'sr': 'RS',\n 'sv': 'SE',\n 'sw': 'TZ',\n 'swc': 'CD',\n 'ta': 'IN',\n 'te': 'IN',\n 'teo': 'UG',\n 'th': 'TH',\n 'ti': 'ET',\n 'to': 'TO',\n 'tr': 'TR',\n 'twq': 'NE',\n 'tzm': 'MA',\n 'uk': 'UA',\n 'ur': 'PK',\n 'uz': 'UZ',\n 'vai': 'LR',\n 'vi': 'VN',\n 'vun': 'TZ',\n 'xog': 'UG',\n 'yav': 'CM',\n 'yo': 'NG',\n 'zh': 'CN',\n 'zh-cn': 'CN',\n 'zh-tw': 'TW',\n 'zu': 'ZA'\n}\n\n# Returns a country's flag according to ISO 639-1 language code\n# Note: Some languages could return just two regional indicator letter emojis (if that combination doesn't create a flag emoji)\n# Doesn't cover every ISO 639-1 code\n# Returns empty string for invalid/unknown ISO 639-1 language codes\ndef code_to_country(code):\n if not code:\n return ''\n elif code in KNOWN_CODES:\n country = KNOWN_CODES.get(code)\n # Unicode: chr(ord('A') + 127397) = 🇦\n # 🇬 + 🇧 = 🇬🇧\n return chr(ord(country[0]) + 127397) + chr(ord(country[1]) + 127397)\n return ''\n","sub_path":"bot/emoji_locale.py","file_name":"emoji_locale.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"642261703","text":"'''Write a program which randomly picks an integer from 1 to 100. Your program should prompt the user for guesses – if the user guesses incorrectly, it should print whether the guess is too high or too low. If the user guesses correctly, the program should print how many guesses the user took to guess the right answer. You can assume that the user will enter valid input.\n'''\n\nimport tkinter as tk\nimport random\n\nsecret_n = random.randint(1, 100)\n\nclass GuessNumber():\n\tdef __init__(self, master):\n\t\t\n\t\tself.master = master\n\t\tmaster.title(\"Guess a Number - a simple game\")\n\t\t\n\t\t# build upper_frm for labels\n\t\tself.upper_frm = tk.Frame(master, bg='#66CDAA')\n\t\t\n\t\t# welcome_lbl welcomes + explain game\n\t\tself.welcome_lbl = tk.Label(self.upper_frm, text=\"Welcome to Guess a Number!\\nI'm thinking about a positive integer\\nbetween 1 and 100,\\ncan you guess which one?\", bg='#66CDAA')\n\t\t\n\t\t# build lower_frm for ent + btn\n\t\tself.lower_frm = tk.Frame(master, bg='#FFFFF0')\n\t\t\n\t\t# update_lbl shows how the game is developing\n\t\tself.update_lbl = tk.Label(self.lower_frm, text='Go ahead, you can press \"Guess\" now', bg='#FFFFF0')\n\t\t\n\t\t# entry width=20 IntVar()\n\t\t#self.ent_var = tk.IntVar()\n\t\tvcmd = master.register(self.validate) # we have to wrap the command\n\t\tself.ent = tk.Entry(self.lower_frm, width=10, validate='key', validatecommand=(vcmd, '%P'))\n\t\t\n\t\t# btn_guess\n\t\tself.btn_guess = tk.Button(self.lower_frm, text='Guess', bg='#59B395', relief=tk.RAISED, bd=3, command=self.choose)\n\t\t\n\t\t# btn_reset\n\t\tself.btn_reset = tk.Button(self.lower_frm, text='Reset', bg='#59B395', relief=tk.RAISED, bd=3, command=self.reset, state=tk.DISABLED)\n\t\t\n\t\t# btn_quit\n\t\tself.btn_quit = tk.Button(self.lower_frm, text='Quit', command=self.master.destroy, bg='#59B395', relief=tk.RAISED, bd=3)\n\t\t\n\t\t# build side_frm for score keeping\n\t\tself.side_frm = tk.Frame(master, bg='#CD6689')\n\t\tself.lbl_side = tk.Label(self.side_frm, bg='#CD6689', text='Guess count:')\n\t\tself.lbl_count = tk.Label(self.side_frm, bg='#CD6689', text='0')\n\t\tself.lbl_nums = tk.Label(self.side_frm, bg='#CD6689', text='')\n\t\t\n\t\t# LAYOUT\n\t\t# root\n\t\tmaster.rowconfigure([0, 1, 2, 3], minsize=100)\n\t\tmaster.columnconfigure([0, 1, 2, 3], minsize=100)\n\t\tmaster.resizable(False, False)\n\t\t\n\t\t# upper_frm\n\t\tself.upper_frm.grid(row=0,column=0, columnspan=3, sticky='nsew')\n\t\tself.welcome_lbl.grid(row=0, columnspan=3, sticky='ew', ipadx=50, pady=30)\n\t\t\n\t\t# lower_frm\n\t\tself.lower_frm.grid(row=1, column=0, rowspan=3, columnspan=3, sticky='nsew')\n\t\tself.lower_frm.rowconfigure([0, 1, 2, 3], minsize=75)\n\t\tself.lower_frm.columnconfigure([0, 1, 2], minsize=75)\n\t\tself.update_lbl.grid(row=0, column=1, sticky='ew', pady=20)\n\t\tself.ent.grid(row=1, column=1, padx=10, pady=10)\n\t\tself.btn_guess.grid(row=2, column=1, padx=10, pady=10)\n\t\tself.btn_reset.grid(row=3, column=1, padx=10, pady=30, sticky='e')\n\t\tself.btn_quit.grid(row=3, column=2, padx=10, pady=30, sticky='w')\n\t\t\n\t\t# side_frm\n\t\tself.side_frm.grid(row=0, rowspan=4, column=3, sticky='nsew')\n\t\tself.lbl_side.grid(row=0, ipadx=10, padx=10, pady=10, sticky='nsew')\n\t\tself.lbl_count.grid(row=1, padx=10, sticky='nsew')\n\t\tself.lbl_nums.grid(row=2, padx=10, sticky='nsew')\n\t\t\n\t\t# METHODS:\n\tdef choose(self):\n\t\t'''Evaluate the user's guess and display the result through self.update_lbl and self.lbl_count.\n\t\t'''\n\t\tuser_guess = int(self.ent.get())\n\t\told_value = self.lbl_count['text']\n\t\told_num = self.lbl_nums['text']\n\t\t\n\t\tif user_guess == secret_n:\n\t\t\tnew_value = str(int(old_value) + 1)\n\t\t\tself.lbl_count['text'] = new_value\n\t\t\tself.update_lbl['text'] = 'Congratulations!!!\\nYou guessed my number after {} tries'.format(self.lbl_count['text'])\n\t\t\tnew_num = self.ent.get()\n\t\t\tself.lbl_nums['text'] = old_num + '\\n' + new_num\n\t\t\tself.btn_reset.configure(state=tk.NORMAL)\n\t\telif user_guess < secret_n:\n\t\t\tself.update_lbl['text'] = \"Too low!\"\n\t\t\tnew_value = str(int(old_value) + 1)\n\t\t\tself.lbl_count['text'] = new_value\n\t\t\tnew_num = self.ent.get()\n\t\t\tself.lbl_nums['text'] = old_num + '\\n' + new_num\n\t\telif user_guess > secret_n:\n\t\t\tself.update_lbl['text'] = \"Too high!\"\n\t\t\tnew_value = str(int(old_value) + 1)\n\t\t\tself.lbl_count['text'] = new_value\n\t\t\tnew_num = self.ent.get()\n\t\t\tself.lbl_nums['text'] = old_num + '\\n' + new_num\n\t\t\n\tdef reset(self):\n\t\tself.ent.delete(0, tk.END)\n\t\tself.update_lbl['text'] = 'Go ahead, you can press \"Guess\" now'\n\t\tself.lbl_count['text'] = '0'\n\t\tself.lbl_nums['text'] = ''\n\t\n\tdef validate(self, new_text):\n\t\tif not new_text:\n\t\t\t# the field is being cleared\n\t\t\tself.entered_number = 0\n\t\t\treturn True\n\t\ttry:\n\t\t\tguess = int(new_text)\n\t\t\tif 1 <= guess <= 100:\n\t\t\t\tself.entered_number = guess\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\t\texcept ValueError:\n\t\t\treturn False\n\t\nroot = tk.Tk()\nmy_game = GuessNumber(root)\nroot.mainloop()","sub_path":"guess_the_number.py","file_name":"guess_the_number.py","file_ext":"py","file_size_in_byte":4748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"27117374","text":"'''\npython-elinks installs an encoding error handler that uses the same ASCII replacements as ELinks does.\n'''\n\nclassifiers = '''\nDevelopment Status :: 4 - Beta\nIntended Audience :: Developers\nLicense :: OSI Approved :: GNU General Public License (GPL)\nOperating System :: OS Independent\nProgramming Language :: Python\nProgramming Language :: Python :: 2\nProgramming Language :: Python :: 3\nTopic :: Software Development :: Libraries :: Python Modules\nTopic :: Text Processing :: Filters\n'''.strip().split('\\n')\n\nimport os\nimport distutils.core\n\ntry:\n # Python 3.X\n from distutils.command.build_py import build_py_2to3 as distutils_build_py\nexcept ImportError:\n # Python 2.X\n from distutils.command.build_py import build_py as distutils_build_py\n\ndef get_version():\n d = {}\n file = open(os.path.join('elinks', '__init__.py'))\n try:\n for line in file:\n if line.startswith('__version__ ='):\n exec(line, d)\n finally:\n file.close()\n try:\n return d['__version__']\n except LookupError:\n raise IOError('Unexpected end-of-file')\n\nos.putenv('TAR_OPTIONS', '--owner root --group root --mode a+rX')\n\ndistutils.core.setup(\n name = 'python-elinks',\n version = get_version(),\n license = 'GNU GPL 2',\n platforms = ['any'],\n description = 'ELinks-like encoding error handler',\n long_description = __doc__.strip(),\n classifiers = classifiers,\n url = 'http://jwilk.net/software/python-elinks',\n author = 'Jakub Wilk',\n author_email = 'jwilk@jwilk.net',\n packages = ['elinks'],\n cmdclass = dict(build_py=distutils_build_py),\n)\n\n# vim:ts=4 sw=4 et\n","sub_path":"pypi_install_script/python-elinks-0.3.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"391580297","text":"#!/usr/bin/env python3\n\nfrom datetime import datetime\n\nimport guzzle_sphinx_theme\n\nextensions = [\n \"sphinx.ext.githubpages\",\n \"sphinx.ext.intersphinx\",\n \"sphinx.ext.mathjax\",\n \"sphinx.ext.todo\",\n \"guzzle_sphinx_theme\",\n]\n\nsource_suffix = \".rst\"\nmaster_doc = \"index\"\nexclude_patterns = [\"_build\", \"Thumbs.db\", \".DS_Store\"]\n\nproject = \"Nengo Enhancement Proposals\"\ncopyright = \"2017, Applied Brain Research\"\nauthor = \"Applied Brain Research\"\nversion = release = datetime.now().strftime(\"%Y-%m-%d\")\nlanguage = None\n\ntodo_include_todos = True\n\nintersphinx_mapping = {}\n\n# HTML theming\npygments_style = \"sphinx\"\ntemplates_path = [\"_templates\"]\nhtml_static_path = []\nhtml_use_smartypants = True\n\nhtml_theme_path = guzzle_sphinx_theme.html_theme_path()\nhtml_theme = \"guzzle_sphinx_theme\"\n\nhtml_theme_options = {\n \"project_nav_name\": \"NEPs\",\n \"base_url\": \"https://www.nengo.ai/enhancement-proposals\",\n}\n\n# Other builders\nhtmlhelp_basename = \"NEPs\"\n\nlatex_elements = {\n # \"papersize\": \"letterpaper\",\n # \"pointsize\": \"11pt\",\n # \"preamble\": \"\",\n # \"figure_align\": \"htbp\",\n}\n\nlatex_documents = [\n (master_doc, # source start file\n \"neps.tex\", # target name\n project, # title\n \"Applied Brain Research\", # author\n \"manual\"), # documentclass\n]\n\nman_pages = [\n # (source start file, name, description, authors, manual section).\n (master_doc, \"neps\", project, [author], 1)\n]\n\ntexinfo_documents = [\n (master_doc, # source start file\n \"NEPs\", # target name\n project, # title\n author, # author\n \"Nengo\", # dir menu entry\n project, # description\n \"Miscellaneous\"), # category\n]\n","sub_path":"conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"229781969","text":"from sqlalchemy import Column, String, Integer, create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom ..event_types import ADD_NEW_ITEM\n\n\nTABLE_NAME_ITEMS = \"items\"\nTABLE_NAME_INDEX = \"index\"\n\n\nBase = declarative_base()\n\n\nclass Items(Base):\n __tablename__ = TABLE_NAME_ITEMS\n\n id = Column(Integer, primary_key=True)\n name = Column(String)\n\n\nclass Index(Base):\n __tablename__ = TABLE_NAME_INDEX\n\n id = Column(Integer, primary_key=True)\n index = Column(Integer)\n\n\nclass PostgresReadModel:\n\n # Constructor\n\n def __init__(self, event_store):\n self._event_store = event_store\n\n # Read model methods\n\n def get_items(self):\n engine = self._get_engine()\n self._ensure_updated(engine)\n\n Session = sessionmaker(bind=engine)\n session = Session()\n\n rows = session.query(Items).all()\n\n items = [{\"name\": r.name} for r in rows]\n\n return items\n\n # Helper methods\n\n def _get_engine(self):\n\n db_params = {\n \"host\": \"postgres\",\n \"port\": 5432,\n \"database\": \"postgres\",\n \"user\": \"postgres\",\n \"password\": \"notverysecret\",\n }\n\n db_link = \"postgresql://{}:{}@{}:{}/{}\".format(\n db_params[\"user\"],\n db_params[\"password\"],\n db_params[\"host\"],\n db_params[\"port\"],\n db_params[\"database\"],\n )\n\n return create_engine(db_link, echo=True)\n\n def _ensure_db_created(self, engine):\n\n has_tables = [\n engine.dialect.has_table(engine, TABLE_NAME_ITEMS),\n engine.dialect.has_table(engine, TABLE_NAME_INDEX),\n ]\n\n if not all(has_tables):\n Base.metadata.create_all(engine)\n\n def _get_index(self, engine):\n\n Session = sessionmaker(bind=engine)\n session = Session()\n\n indexes = session.query(Index).all()\n\n return indexes[0].index if indexes else 0\n\n def _set_index(self, engine, index):\n\n Session = sessionmaker(bind=engine)\n session = Session()\n\n indexes = session.query(Index).all()\n\n if indexes:\n indexes[0].index = index\n else:\n new_item = Index(index=index)\n session.add(new_item)\n\n session.commit()\n\n def _ensure_updated(self, engine):\n\n self._ensure_db_created(engine)\n index = self._get_index(engine)\n\n new_events = self._event_store.get_events(index + 1)\n\n event_handlers = self._get_event_handlers()\n\n if new_events:\n\n last_index = new_events[-1].get(\"index\")\n\n for event in new_events:\n\n handler = event_handlers.get(event.get(\"type\"))\n\n if handler:\n handler(engine, event)\n\n self._set_index(engine, last_index)\n\n def _get_event_handlers(self):\n return {ADD_NEW_ITEM: self._handle_add_new_item}\n\n def _handle_add_new_item(self, engine, event):\n Session = sessionmaker(bind=engine)\n session = Session()\n\n payload = event.get(\"payload\")\n name = payload.get(\"name\") if payload else None\n new_item = Items(name=name)\n\n session.add(new_item)\n session.commit()\n","sub_path":"fullstack/1/server/events/readmodels/postgres.py","file_name":"postgres.py","file_ext":"py","file_size_in_byte":3272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"112791935","text":"import numpy as np\r\nfrom scipy import ndimage\r\nfrom PIL import Image\r\n\r\nroberts_cross_v = np.array([[1, 0],\r\n [0, -1]])\r\n\r\nroberts_cross_h = np.array([[0, 1],\r\n [-1, 0]])\r\n\r\nstoch_bits = 5\r\nstoch = int(2**stoch_bits)\r\n\r\n\r\ndef load_image(infilename):\r\n img = Image.open(infilename)\r\n img.load()\r\n # note signed integer\r\n return np.asarray(img, dtype=\"int32\")\r\n\r\n\r\ndef save_image(data, outfilename):\r\n img = Image.fromarray(np.asarray(np.clip(data, 0, 255), dtype=\"uint8\"), \"L\")\r\n img.save(outfilename)\r\n\r\n\r\nif __name__ == '__main__':\r\n np.set_printoptions(threshold=np.inf)\r\n\r\n infilename = 'edge_detection_original.jpg'\r\n outfilename = 'perm_ED_S3_' + str(stoch_bits) + '_stochastic_bits_subtraction.jpg'\r\n\r\n outfilename_1 = 'output_conv_circle.jpg'\r\n outfilename_2 = 'output_stoch_circle.jpg'\r\n image = load_image(infilename)\r\n image = image[..., 0]\r\n image_conv = (image // stoch) * stoch\r\n image_stoch = image % stoch\r\n\r\n # conventional part\r\n vertical = ndimage.convolve(image_conv, roberts_cross_v)\r\n horizontal = ndimage.convolve(image_conv, roberts_cross_h)\r\n\r\n output_image_conv = abs(vertical) + abs(horizontal)\r\n output_image_conv = output_image_conv[:-1, :-1]\r\n save_image(output_image_conv, outfilename_1)\r\n\r\n # stochastic part\r\n\r\n # fixed SN length -- 256\r\n # Is = np.random.randint(0, 255 % stoch + 1, (image.shape[0] - 1, image.shape[1] - 1, 256), dtype='uint8')\r\n # changing SN length -- stoch\r\n Is = np.random.randint(0, 255 % stoch + 1, (image.shape[0] - 1, image.shape[1] - 1, stoch), dtype='uint8')\r\n\r\n Is_1 = (Is < image_stoch[:-1, :-1, np.newaxis])\r\n Is_2 = (Is < image_stoch[1:, :-1, np.newaxis])\r\n Is_3 = (Is < image_stoch[:-1, 1:, np.newaxis])\r\n Is_4 = (Is < image_stoch[1:, 1:, np.newaxis])\r\n\r\n t_1 = np.logical_xor(Is_1, Is_4)\r\n t_2 = np.logical_xor(Is_2, Is_3)\r\n\r\n # Generate SNs for select lines\r\n Ss = np.random.randint(0, 2, t_1.shape, dtype='uint8')\r\n\r\n output_image_stoch = t_1 * Ss + t_2 * (1 - Ss)\r\n output_image_stoch = np.mean(output_image_stoch, axis=-1) * (stoch - 1)\r\n save_image(output_image_stoch, outfilename_2)\r\n\r\n save_image(output_image_conv - output_image_stoch, outfilename)\r\n","sub_path":"Design Set 3/hybrid_edge_detection.py","file_name":"hybrid_edge_detection.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"219560194","text":"from django.conf.urls import patterns, url\nfrom SABR import views\n\nurlpatterns = patterns('',\n url(r'^$', views.index, name='index'),\n url(r'^player/(?P[\\w\\-]+)/$', views.player, name='player'),\n # url(r'^search-form/$', views.search_form),\n url(r'^search/$', views.search),\n url(r'^api/get_players/', views.get_players, name='get_players'),\n url(r'^about', views.about, name='about'),\n \n \n \n \n \n \n\n \n )\n \n ","sub_path":"SABR/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"54982244","text":"\"\"\"\nCopyright (c) Facebook, Inc. and its affiliates.\n\nThis source code is licensed under the MIT license found in the\nLICENSE file in the root directory of this source tree.\n\"\"\"\n\nimport torchaudio\n\nimport audioset\n\n\nclass Dataset(audioset.Dataset):\n\n splits = {\n \"train\": [\"train-clean-100\"],\n \"validation\": [\"dev-clean\"],\n \"test\": [\"test-clean\", \"test-other\"],\n }\n\n sample_rate = 16000\n\n def __init__(self, data_path, preprocessor, split, augment=False):\n augmentation = []\n if augment:\n augmentation = [\n torchaudio.transforms.FrequencyMasking(27, iid_masks=True),\n torchaudio.transforms.FrequencyMasking(27, iid_masks=True),\n torchaudio.transforms.TimeMasking(100, iid_masks=True),\n torchaudio.transforms.TimeMasking(100, iid_masks=True),\n ]\n\n super(Dataset, self).__init__(\n data_path,\n preprocessor,\n split,\n self.splits,\n augmentation=augmentation,\n sample_rate=self.sample_rate,\n )\n\n\nif __name__ == \"__main__\":\n import argparse\n import torch\n\n parser = argparse.ArgumentParser(description=\"Compute data stats.\")\n parser.add_argument(\"--data_path\", type=str, help=\"Path to dataset JSON files.\")\n parser.add_argument(\n \"--save_text\", type=str, help=\"Path to save parsed train text.\", default=None\n )\n parser.add_argument(\n \"--save_tokens\", type=str, help=\"Path to save tokens.\", default=None\n )\n parser.add_argument(\n \"--compute_stats\",\n action=\"store_true\",\n help=\"Compute training data statistics.\",\n default=False,\n )\n args = parser.parse_args()\n\n preprocessor = audioset.Preprocessor(args.data_path, 80, Dataset.splits)\n print(f\"Number of tokens: {preprocessor.num_tokens}\")\n trainset = Dataset(args.data_path, preprocessor, split=\"train\", augment=False)\n if args.save_text is not None:\n with open(args.save_text, \"w\") as fid:\n fid.write(\"\\n\".join(t for _, t, _ in trainset.dataset))\n if args.save_tokens is not None:\n with open(args.save_tokens, \"w\") as fid:\n fid.write(\"\\n\".join(preprocessor.tokens))\n valset = Dataset(args.data_path, preprocessor, split=\"validation\")\n testset = Dataset(args.data_path, preprocessor, split=\"test\")\n print(\"Number of examples per dataset:\")\n print(f\"Training: {len(trainset)}\")\n print(f\"Validation: {len(valset)}\")\n print(f\"Test: {len(testset)}\")\n\n if not args.compute_stats:\n import sys\n\n sys.exit(0)\n\n # Compute mean and var stats:\n audio = torch.cat([trainset[i][0] for i in range(len(trainset))], dim=2)\n mean = torch.mean(audio)\n std = torch.std(audio)\n print(f\"Data mean {mean} and standard deviation {std}.\")\n\n # Compute average lengths of audio and targets:\n avg_in_t = sum(w for (w, _), _ in trainset.sample_sizes()) / len(trainset)\n avg_tgt_l = sum(l for _, l in trainset.sample_sizes()) / len(trainset)\n print(f\"Average audio length {avg_in_t} (s)\")\n print(f\"Average target length {avg_tgt_l}\")\n","sub_path":"datasets/librispeech.py","file_name":"librispeech.py","file_ext":"py","file_size_in_byte":3150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"56118157","text":"import random\n\n\nclass Operation:\n \"\"\"\n Abstract base class for all types of operations that may be put into a pipeline.\n \"\"\"\n def __init__(self):\n \"\"\"\n Create the Operation.\n By default, `requires_full_dataset_in_memory` member variable is set to False to tell that\n the operation works with generators (may process just one sample at a time) and doesn't require the full dataset\n to be stored in the memory. It may be overriden in the subclasses.\n \"\"\"\n self.requires_full_dataset_in_memory = False\n\n def __str__(self):\n \"\"\" Stringify the operation \"\"\"\n return self.__class__.__name__\n\n def execute(self, images_and_density_maps):\n \"\"\" Abstract method that must be implemented in the subclasses, should take and return an iterable of img+DM pairs \"\"\"\n raise NotImplementedError(\"execute method not implemented in the child class\")\n\n\nclass Duplicate(Operation):\n \"\"\"\n Duplicates each sample in a dataset a specified number of times. One of the most helpful operations when it comes\n to data augmentation.\n \"\"\"\n def __init__(self, duplicates_num):\n \"\"\"\n Define duplication.\n\n :param duplicates_num: Each sample will be repeated that number of times.\n \"\"\"\n Operation.__init__(self)\n self.duplicates_num = duplicates_num\n\n def execute(self, images_and_density_maps):\n \"\"\" Duplicates samples \"\"\"\n for image_and_density_map in images_and_density_maps:\n for i in range(self.duplicates_num):\n yield image_and_density_map\n\n\nclass Dropout(Operation):\n \"\"\"\n Drops out samples with a given probability.\n \"\"\"\n def __init__(self, probability):\n \"\"\"\n Define dropout.\n\n :param probability: Each sample will be dropped out with this probability, meaning that the estimated number of output images for a dataset with `N` samples is `N*(1-probability)`.\n \"\"\"\n Operation.__init__(self)\n self.probability = probability\n\n def execute(self, images_and_density_maps):\n \"\"\" Drops out samples \"\"\"\n for image_and_density_map in images_and_density_maps:\n if random.random() >= self.probability:\n yield image_and_density_map\n\n\nclass RandomArgs(Operation):\n \"\"\"\n Allows running operations with randomized numeral arguments.\n \"\"\"\n def __init__(self, operation, const_args, random_args):\n \"\"\"\n Specify randomization by providing the operation to invoke, const arguments that must be passed as they are and\n random arguments that will be randomized.\n\n :param operation: Type of operation that will be invoked. Must come from this, .outputs or .transformations module.\n :param const_args: Dictionary of constant arguments, i.e. ones whose values (nor names) won't change.\n :param random_args: Dictionary of randomized arguments specified as (min, max) tuple for each arg name. Values are taken from uniform distribution and are either floats or ints, depending on the types of provided min and max values.\n \"\"\"\n Operation.__init__(self)\n self.operation = operation\n self.const_args = const_args\n self.random_args = random_args\n\n def _get_op_str(self):\n \"\"\"\n Retrieve string representation of the operation to invoke, in a form that is ready to be computed in eval. That\n means, a prefix with module name is added when necessary. Only operations from this, .outputs and\n .transformations modules are supported.\n\n :return: Potentially prefixed operation name.\n \"\"\"\n import CCAugmentation.outputs as cca_out\n import CCAugmentation.transformations as cca_trans\n\n op_name_str = self.operation.__name__\n\n try:\n getattr(cca_trans, op_name_str)\n op_str = f\"cca_trans.{op_name_str}\"\n except AttributeError:\n try:\n getattr(cca_out, op_name_str)\n op_str = f\"cca_out.{op_name_str}\"\n except AttributeError:\n op_str = op_name_str\n\n return op_str\n\n def _get_const_str(self):\n \"\"\"\n Transform dictionary of constant arguments to string that can be used inside parentheses in eval().\n\n :return: String representing constant arguments.\n \"\"\"\n const_components = []\n for k, v in self.const_args.items():\n v_str = f\"'{v}'\" if type(v) is str else str(v)\n const_components.append(f\"{k}={v_str}\")\n return \",\".join(const_components)\n\n def _get_rand_str(self):\n \"\"\"\n Randomize, cast and transform to string the arguments that are to be randomized.\n\n :return: String representing randomized arguments.\n \"\"\"\n rand_components = []\n for key, (min_val, max_val) in self.random_args.items():\n val = random.uniform(min_val, max_val)\n if type(min_val) is int and type(max_val) is int:\n val = int(val)\n rand_components.append(f\"{key}={str(val)}\")\n return \",\".join(rand_components)\n\n def execute(self, images_and_density_maps):\n \"\"\"\n Create and execute the given operation with a set of constant and randomized arguments.\n\n :param images_and_density_maps: Iterable of img+DM pairs that are to be used in the operation.\n :return: Result img+DM pairs from the operation.\n \"\"\"\n # these imports are used in eval(), don't remove them\n import CCAugmentation.outputs as cca_out\n import CCAugmentation.transformations as cca_trans\n _ = cca_out, cca_trans\n\n op_str = self._get_op_str()\n const_str = self._get_const_str()\n\n for image_and_density_map in images_and_density_maps:\n rand_str = self._get_rand_str()\n args_str = \",\".join([const_str, rand_str]) if const_str and rand_str else const_str + rand_str\n op = eval(f\"{op_str}({args_str})\")\n for result in op.execute([image_and_density_map]):\n yield result\n","sub_path":"shb-mcnn/exp/11-27_20-08_SHHB_MCNN_0.0001_[crop2]/code/CCAugmentation/operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":6105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"212630053","text":"from os.path import dirname, join\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom load_data import load_dataset\nfrom model import XGboostModel\n\ndata_train = join(dirname(dirname(dirname(__file__))), \"data\", \"vlsp2018\", \"corpus\", \"restaurant\", \"train.xlsx\")\ndata_dev = join(dirname(dirname(dirname(__file__))), \"data\", \"vlsp2018\", \"corpus\", \"restaurant\", \"dev.xlsx\")\n\nX_train, y_train = load_dataset(data_train)\nX_dev, y_dev = load_dataset(data_dev)\nmodels = []\n\nX = X_train + X_dev\ny = y_train + y_dev\n\nfor n_iter in [100, 140, 160, 200, 500]:\n # for max_depth in [50, 100, 140, 160, 200, 300]:\n for max_depth in [200, 300, 400, 500]:\n # for max_features in [1000, 2000, 2200, 2400, 2600, 3000]:\n for max_features in [2000, 3000, 4000]:\n name = \"XGBoost(n_iter {0} max_depth {1}) + Count(bigram, max_features {2})\".format(n_iter, max_depth, max_features)\n params = {\"n_iter\": n_iter, \"max_depth\": max_depth}\n model = XGboostModel(\n name,\n params,\n CountVectorizer(ngram_range=(1, 2), max_features=max_features)\n )\n models.append(model)\n\nfor model in models:\n from datetime import datetime\n start = datetime.now()\n model.load_data(X, y)\n model.fit_transform()\n model.train()\n model.evaluate(X_dev, y_dev)\n print(datetime.now() - start)\n","sub_path":"experiments/restaurant/tuning_xgboost.py","file_name":"tuning_xgboost.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"162514626","text":"# -----------------------------------------------------------------------------\n#\n# This file is part of the ParaNut project.\n#\n# Copyright (C) 2023-2024 Daniel Bortkevych \n# Oleg Murashko \n# Haris Vojic \n# Hochschule Augsburg, University of Applied Sciences\n#\n# Description:\n# Transfers requests and responses between View and Model\n#\n# --------------------- LICENSE -----------------------------------------------\n# Redistribution and use in source and binary forms, with or without \n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, \n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation \n# and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE \n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n# SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND \n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# -----------------------------------------------------------------------------\n\n## @package Controller\nimport math\nimport logging\nimport sys\n\nlogger\t\t\t= logging.getLogger(__name__)\n\nfile_handler\t= logging.FileHandler('logger/controll.log', mode = 'w')\nconsole_handler\t= logging.StreamHandler(stream = sys.stdout)\n\nformat = \"%(levelname)s:%(name)10.10s:%(funcName)20.20s:%(lineno)4d:%(message)s\"\nformatter\t\t= logging.Formatter(format)\n\nfile_handler.setFormatter(formatter)\nconsole_handler.setFormatter(formatter)\n\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(file_handler)\nlogger.addHandler(console_handler)\n\n##\tController class is responsible for the communication between the other \n#\tmodules\tof the MVC-model.\nclass Controller:\n\t## Constructor which takes external model and view to operate with.\n\t#\n\t# @param self The object pointer.\n\t# @param model Model object\n\t# @param view View object\n\t#\n\t# @return An instance of the Controller class initialized with the \n\t# specified View and Model object.\n\tdef __init__(self, model, view):\n\t\tlogger.debug(f'Initialization started')\n\t\tlogger.debug(f'Initializing model and view')\n\t\t\n\t\tself.model\t= model;\n\t\tself.view\t= view;\n\n\t\tlogger.debug(f'Initialization finished')\n\n\n\t\t\n\t# Getter methods\n\t#---------------------------------------------------------------------------\n\t@property\n\tdef model(self):\n\t\treturn self.__model\n\n\t@property\n\tdef view(self):\n\t\treturn self.__view\n\n\t# Setter methods\n\t#---------------------------------------------------------------------------\n\t@model.setter\n\tdef model(self, value):\n\t\tif value.__class__.__name__ == 'Model':\n\t\t\tself.__model = value\n\t\telse:\n\t\t\traise ValueError(f'Invalid model: {value}')\n\n\t@view.setter\n\tdef view(self, value):\n\t\tif value.__class__.__name__ == 'View':\n\t\t\tself.__view = value\n\t\telse:\n\t\t\traise ValueError(f'Invalid view: {value}')\n\n\t# Load/Store methods\n\t#---------------------------------------------------------------------------\n\n\t## Reloads configuration data from json file and saves them into a model \n\t# object.\n\t#\n\t# @param self\t\t\tThe object pointer.\n\tdef reload_object(self):\n\n\t\t## @var file\t\tThe JSON file to be opened.\n\t\tfile = f'{self.view.json_path}/{self.view.json_file}.json'\n\t\tlogger.debug(f'Reloading file: {file}')\n\t\tself.model._read_configuration(file)\n\t\n\t## Saves configuraiton as JSON.\n\t#\n\t# @param self\t\t\tThe object pointer.\n\t# @param filename\t\tString name of the file to be saved.\n\tdef save_configuration(self, filename):\n\t\tlogger.debug(f'Saving configuration under: {filename}')\t\n\t\tself.model.save_configuration(filename)\n\n\t## Loads configuration from self.config to glade.\n\t#\n\t# @param self\t\t\tThe object pointer.\n\tdef load_configuration(self):\n\t\tlogger.debug(f'Loading configuration from objects to gtk_objects')\n\t\tfor unit in self.model.get_units():\n\t\t\t# NOTE: potential bug solution\n\t\t\tif unit == \"description\":\n\t\t\t\tcontinue\n\t\t\tmodule = getattr(self.model, unit)\n\n\t\t\tfor setting in module.get_attributes():\n\t\t\t\tgtk_object = self.view.builder.get_object(setting)\n\n\t\t\t\tattribute = getattr(module, setting)\n\t\t\t\ttry:\n\t\t\t\t\tif \"ld\" in setting:\n\t\t\t\t\t\tld = int(attribute.get('value'))\n\t\t\t\t\t\tld = str(2**ld)\n\n\t\t\t\t\t\tgtk_object.set_text(ld)\n\n\t\t\t\t\telif \"cap1\" in setting:\n\t\t\t\t\t\tgtk_object.set_text(attribute.get('value'))\n\t\t\t\t\t\tself.view.check_cores()\n\n\t\t\t\t\telif \"mem_size\" in setting:\n\t\t\t\t\t\tvalue = attribute.get('value')\n\t\t\t\t\t\tvalue = ''.join(ch for ch in value if ch.isdigit())\n\t\t\t\t\t\t\n\t\t\t\t\t\tgtk_object.set_text(value)\n\t\t\t\t\n\t\t\t\t\telif \"perfcounter_bits\" in setting:\n\t\t\t\t\t\tgtk_object.set_value(int(attribute.get('value')))\n\n\t\t\t\t\telse:\n\t\t\t\t\t\tgtk_object.set_text(attribute.get('value'))\n\t\t\t\texcept:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tgtk_object.set_active_id(attribute.get('value'))\n\t\t\t\t\t# TODO: checkbox and radiobuttons\n\t\t\t\t\texcept:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tif attribute.get('value') == '1':\n\t\t\t\t\t\t\t\tgtk_object.set_active(True)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tgtk_object.set_active(False)\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\tlogger.error(f'Failed to edit: {setting}')\n\n\t## This function stores the configuration values from a View object into a \n\t# Model object.\n\t#\n\t# @param self\t\t\tThe object pointer.\n\tdef store_data(self):\n\t\tlogger.debug(f'Storing date from gtk_objects to objects')\n\t\tfor unit in self.model.get_units():\n\t\t\tif unit == \"description\":\n\t\t\t\tcontinue\n\t\t\tmodule = getattr(self.model, unit)\n\t\t\tfor setting in module.get_attributes():\n\t\t\t\tgtk_object = self.view.builder.get_object(setting)\n\t\t\t\t\n\t\t\t\tattribute = getattr(module, setting)\n\t\t\t\ttry:\n\t\t\t\t\tif gtk_object.__class__.__name__ == \"Entry\":\n\t\t\t\t\t\tif setting == \"mem_size\":\n\t\t\t\t\t\t\tvalue = f'({gtk_object.get_text()} * MB)'\n\t\t\t\t\t\t\tattribute.update({\"value\": value}) \n\n\t\t\t\t\t\telif \"ld\" in setting:\n\t\t\t\t\t\t\tld = gtk_object.get_text()\n\t\t\t\t\t\t\tld = int(ld)\n\t\t\t\t\t\t\tld = int(math.log2(ld))\n\t\t\t\t\t\t\tld = str(ld)\n\t\t\t\t\t\t\tattribute.update({\"value\": ld})\n\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tvalue = gtk_object.get_text()\n\t\t\t\t\t\t\tattribute.update({\"value\": value})\n\t\t\t\t\telif setting == \"perfcounter_bits\":\n\t\t\t\t\t\tvalue = int(gtk_object.get_value())\n\t\t\t\t\t\tvalue = str(value)\n\n\t\t\t\t\t\tattribute.update({\"value\": value})\n\n\t\t\t\t\telif gtk_object.__class__.__name__ == \"CheckButton\":\n\t\t\t\t\t\tif(gtk_object.get_active()):\n\t\t\t\t\t\t\tattribute.update({\"value\": \"1\"})\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tattribute.update({\"value\": \"0\"})\n\t\t\t\t\t\n\t\t\t\t\telif gtk_object.__class__.__name__ == \"ComboBoxText\":\n\t\t\t\t\t\tvalue = gtk_object.get_active_id()\n\t\t\t\t\t\tattribute.update({\"value\": value})\n\t\t\t\texcept:\n\t\t\t\t\tlogger.error(\"aloha\")\n\t\t\t\t\t\n\t## Creates \"config.mk\" configuration file.\n\t#\n\t#\n\t# @param self\t\t\tThe object pointer.\n\t# @pram path Path to the saving location of \"config.mk\"\n\tdef make_configuration(self, path = \"\"):\n\t\ttry:\n\t\t\tself.model.make_configuration(path = \"\")\n\t\texcept ValueError as error:\n\t\t\tself.view.show_error(error)\n\n\t## Reads data into objects from a JSON file.\n\t#\n\t# @param self\t\t\tThe object pointer.\n\tdef _load_configuration(self):\n\t\tjson_path = f'{self.view.json_path}/{self.view.json_file}'\n\t\tlogger.debug(f'Loading json configuration file {json_path}')\n\t\tself.model._read_configuration(json_path)\n","sub_path":"config-creator/src/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":7899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"545769035","text":"\"\"\"\n比较两个文件夹里面的内容,包括文件的大小,创建时间(比较同名文件),以及显示出不同文件(即不是共有的部分)\n\"\"\"\nimport os\nimport time\nfrom file_utils import paths\nfrom text_utils import text_diff\n\n\ndef listfiledetails(folder):\n assert os.path.exists(folder)\n\n foldercontents = []\n\n absfolder = os.path.abspath(folder)\n for file in os.listdir(absfolder):\n absfile = os.path.join(absfolder, file)\n filesize = os.path.getsize(absfile)\n createdtime = getreadabletime(os.path.getctime(absfile))\n contentitem = '%s\\t\\t%s\\t\\t%s' % (file, filesize, createdtime)\n\n foldercontents.append(contentitem)\n\n return foldercontents\n\n\ndef getreadabletime(seconds: float):\n \"\"\"\n 返回格式良好的时间,如果seconds为空,则返回当前时间的格式化字符串\n :param seconds: 时间秒数,\n :return:\n \"\"\"\n import time\n\n DEFAULT_FORMAT = '%y-%m-%d %H:%M:%S'\n\n return time.strftime(DEFAULT_FORMAT, time.gmtime(seconds))\n\n\ndef compareandgenerateresulthtml(folder1, folder2):\n assert folder1\n assert folder2\n\n assert paths.isvalidpath(folder1)\n assert paths.isvalidpath(folder2)\n\n fc1 = listfiledetails(folder1)\n fc2 = listfiledetails(folder2)\n\n rh = text_diff._diffstrtoHtml(fc1, fc2)\n\n with open('fs.html', 'w') as r:\n r.write(rh)\n\n pass\n\n\nif __name__ == '__main__':\n listfiledetails('test')\n","sub_path":"file_utils/dir_compare.py","file_name":"dir_compare.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"465114025","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.views.generic import TemplateView\nfrom gezimeclise.blog import urls as blog_url\nfrom django.conf import settings\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^$', TemplateView.as_view(template_name=\"index.html\"),\n name=\"landing_page\"),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^kullanicilar/', include('gezimeclise.profiles.urls')),\n url(r'^yazilar/', include('gezimeclise.blog.urls')),\n url(r'^bildirimler/', include('gezimeclise.notifications.urls')),\n url(r'^facebook/', include('django_facebook.urls')),\n url(r'^forum/', TemplateView.as_view(template_name=\"moot_it_forum.html\"),\n name=\"forum\"),\n url(r'^accounts/', include('django_facebook.auth_urls')),\n url(r'^talepler/', include('gezimeclise.causes.urls'))\n)\n\nif settings.DEBUG:\n urlpatterns += patterns('',\n (r'^media/(?P.*)$', 'django.views.static.serve',\n {'document_root': settings.MEDIA_ROOT}),\n )\n","sub_path":"gezimeclise/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"433897064","text":"from datetime import datetime\nfrom datetime import timedelta\nfrom get_actions import get_actions\nimport pandas as pd\nimport pickle\nimport os\n\n\n#计算日期差\ndef lasttime(the_time):\n end_date = end_date_line\n return int((datetime.strptime(end_date, '%Y-%m-%d') - datetime.strptime(the_time,'%Y-%m-%d')).total_days())\n\n#获取商品各种互动行为总数\ndef get_product_num(start_date, end_date):\n dump_path = './data/product/product_num_%s_%s.pkl' % (start_date, end_date)\n if os.path.exists(dump_path):\n actions = pickle.load(open(dump_path, 'rb'),)\n else:\n actions = get_actions(start_date, end_date)\n actions = actions[['product_id', 's_num', 'c_num', 'r_num', 'b_num']]\n\n #各项求和\n actions = actions.groupby(['product_id'], as_index=False).sum()\n pickle.dump(actions, open(dump_path, 'wb'))\n return actions\n\n#获取用户最近一次互动行为的时间与截止时��的间隔,最大间隔默认为30天\ndef get_product_lasttime(start_date, end_date):\n feature = ['product_id','product_s_lasttime','product_c_lasttime','product_r_lasttime','product_b_lasttime']\n dump_path = './data/product/product_lasttime_%s_%s.pkl' % (start_date, end_date)\n global end_date_line\n end_date_line = end_date\n\n if os.path.exists(dump_path):\n actions = pickle.load(open(dump_path, 'rb'),)\n else:\n actions = get_actions(start_date, end_date)\n actions = actions[['product_id', 's_num', 'c_num','r_num','b_num','Date']]\n\n actions = actions.groupby(['product_id', 's_num', 'c_num','r_num','b_num'], as_index=False).last()\n actions['product_s_lasttime'] = actions[actions.s_num != 0].Date.map(lasttime)\n actions['product_c_lasttime'] = actions[actions.c_num != 0].Date.map(lasttime)\n actions['product_r_lasttime'] = actions[actions.r_num != 0].Date.map(lasttime)\n actions['product_b_lasttime'] = actions[actions.b_num != 0].Date.map(lasttime)\n\n actions = actions.groupby(['product_id'], as_index=False).sum()\n actions = actions[feature]\n actions = actions.fillna(30)\n actions.to_csv('./data/product/product_lasttime_%s_%s.csv' % (start_date, end_date), index=False,index_label=False)\n pickle.dump(actions, open(dump_path, 'wb'))\n return actions\n\n\ndef get_product_feat(start_date, end_date):\n #读取product特征的两个分表\n product_action_num = get_product_num(start_date, end_date)\n product_lasttime = get_product_lasttime(start_date, end_date)\n\n #合成product特征总表\n actions = pd.merge(product_action_num, product_lasttime, how='left', on=['product_id'])\n\n # 空值填充\n actions = actions.fillna({'product_s_lasttime':360, 'product_c_lasttime':360,\n 'product_r_lasttime':360, 'product_b_lasttime':360})\n actions.to_csv('./data/product/product_feat_%s_%s.csv' % (start_date, end_date), index=False,\n index_label=False)\n\n\nif __name__ == '__main__':\n start_date1 = '2016-01-01'\n end_date1 = '2016-01-31'\n\n start_date2 = '2016-02-01'\n end_date2 = '2016-02-29'\n\n start_date3 = '2016-03-01'\n end_date3 = '2016-03-31'\n\n start_date4 = '2016-04-01'\n end_date4 = '2016-04-30'\n\n start_date5 = '2016-05-01'\n end_date5 = '2016-05-31'\n\n start_date6 = '2016-06-01'\n end_date6 = '2016-06-30'\n\n start_date = [start_date1, start_date2, start_date3, start_date4, start_date5, start_date6]\n end_date = [end_date1, end_date2, end_date3, end_date4, end_date5, end_date6]\n\n for i in range(0,6):\n get_product_feat(start_date[i], end_date[i])\n","sub_path":"2/2_product_feat.py","file_name":"2_product_feat.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"21706875","text":"#!/usr/bin/evn python\r\n# -*- coding: utf-8 -*-\r\n# Author: gaoxq@ruijie.com.cn\r\n# Date: 2015.11.06\r\n#\r\n# test topo: \r\n# +--------+\r\n# | intf | nettester\r\n# +----|---+\r\n# |\r\n# +----|---------------------------------+\r\n# | steintf intf1 intf2 ... |\r\n# | | | | switch\r\n# | intfm intfn ... |\r\n# +--------------------------------------+ \r\n#\r\n\r\nimport time\r\nimport re\r\nfrom libcom.lib_pub.logging_drv import log_info\r\nfrom libcom.console_drv.console_drv import *\r\nfrom port_pub_lib import *\r\n\r\n__all__ = [\"port_speed_cfg\"]\r\n\r\nmedium_ability = ['copper', 'fiber']\r\nspeed_ability = ['auto', '10G', '1000', '100', '10']\r\nduplex_ability = ['auto', 'full', 'half']\r\nflow_ctrl_ability = ['auto', 'on', 'off']\r\n\r\ndef port_intf_ability_init():\r\n ability = {}\r\n s_ab = {}\r\n d_ab = {}\r\n f_ab = {}\r\n\r\n for medium in medium_ability:\r\n for speed in speed_ability:\r\n for duplex in duplex_ability:\r\n for flow_ctrl in flow_ctrl_ability:\r\n f_ab[flow_ctrl] = False\r\n d_ab[duplex] = f_ab.copy()\r\n s_ab[speed] = d_ab.copy()\r\n ability[medium] = s_ab.copy()\r\n return ability\r\n\r\ndef port_intf_ability_get(dev, intf):\r\n ability = port_intf_ability_init()\r\n intf_medium = port_intf_medium_get(dev, intf)\r\n max_speed = port_intf_max_speed_get(intf)\r\n if max_speed == '10G':\r\n for speed in speed_ability[:3]:\r\n for duplex in duplex_ability[:2]:\r\n for flow_ctrl in flow_ctrl_ability:\r\n ability[intf_medium][speed][duplex][flow_ctrl] = True\r\n else:\r\n for speed in speed_ability[speed_ability.index(max_speed):] + ['auto']:\r\n for duplex in duplex_ability:\r\n for flow_ctrl in flow_ctrl_ability:\r\n ability[intf_medium][speed][duplex][flow_ctrl] = True\r\n\r\n return ability\r\n\r\ndef port_cmd_unsupport_promt_check(promt, intf, cmd_name, cmd):\r\n if promt.find('% fail to set speed or do not support the command.') == -1 \\\r\n and promt.find('% Invalid input detected') == -1:\r\n log_info(\"\\t####interface %s not prompt fail after setting invalid %s[%s]\" \\\r\n %(intf, cmd_name, cmd))\r\n return FAIL\r\n return PASS\r\n\r\ndef port_intf_an_get(speed, duplex, flow_ctrl):\r\n if speed != 'auto' and duplex != 'auto' and flow_ctrl != 'auto':\r\n return False\r\n else:\r\n return True\r\n\r\ndef port_intf_speed_single_auto(intf1_medium, intf1_max_speed, intf2_speed, intf2_an):\r\n \"\"\"\r\n intf1 as speed auto\r\n return as: (intf1_link, intf2_link)\r\n \"\"\"\r\n if intf1_max_speed != intf2_speed:\r\n if intf1_medium == 'fiber':\r\n return (False, False)\r\n\r\n if speed_ability.index(intf1_max_speed) > speed_ability.index(intf2_speed):\r\n return (False, False)\r\n \r\n if intf2_an:\r\n return (True, True)\r\n else:\r\n if intf1_medium == 'fiber' and intf1_max_speed == '1000':\r\n return (False, True)\r\n else:\r\n return (True, True)\r\n\r\ndef port_intf_duplex_single_auto(link_speed, intf1_medium, intf2_duplex, intf2_an):\r\n \"\"\"\r\n intf1 as duplex auto\r\n return as: (link, intf1_link_duplex, intf2_link_duplex)\r\n \"\"\"\r\n if link_speed == '10G':\r\n return (False, intf2_duplex, intf2_duplex)\r\n\r\n if link_speed == '1000' and intf1_medium == 'copper':\r\n return (True, intf2_duplex, intf2_duplex)\r\n\r\n if intf2_an:\r\n return (True, intf2_duplex, intf2_duplex)\r\n else:\r\n return (True, 'half', intf2_duplex)\r\n\r\ndef port_intf_link_check(intf1_cfg, intf2_cfg):\r\n \"\"\"\r\n intf1_cfg: (medium, max_speed, speed, duplex, flow_ctrl)\r\n intf2_cfg: (medium, max_speed, speed, duplex, flow_ctrl)\r\n return as: (intf1(link, speed, duplex, flow_ctrl), intf2(link, speed, duplex, flow_ctrl))\r\n \"\"\"\r\n (intf1_medium, intf1_max_speed, intf1_speed, intf1_duplex, intf1_flowctrl) = intf1_cfg\r\n (intf2_medium, intf2_max_speed, intf2_speed, intf2_duplex, intf2_flowctrl) = intf2_cfg\r\n\r\n link_down = (False, 'none', 'none', 'none')\r\n\r\n intf1_link = True\r\n intf2_link = True\r\n link_speed = intf1_max_speed\r\n intf1_link_duplex = intf1_duplex\r\n intf2_link_duplex = intf2_duplex\r\n intf1_link_flowctrl = intf1_flowctrl\r\n intf2_link_flowctrl = intf2_flowctrl\r\n intf1_an = port_intf_an_get(intf1_speed, intf1_duplex, intf1_flowctrl)\r\n intf2_an = port_intf_an_get(intf2_speed, intf2_duplex, intf2_flowctrl)\r\n\r\n # link down when pair speed not equal\r\n if intf1_speed != 'auto' and intf2_speed != 'auto' and intf1_speed != intf2_speed:\r\n return (link_down, link_down)\r\n\r\n # link down when pair duplex not equal\r\n if intf1_duplex != 'auto' and intf2_duplex != 'auto' and intf1_duplex != intf2_duplex:\r\n return (link_down, link_down)\r\n\r\n # speed equal or 'auto' mode. duplex equal or 'auto' mode\r\n if intf1_speed == 'auto' and intf2_speed == 'auto':\r\n if intf1_max_speed != intf2_max_speed:\r\n if intf1_medium == 'fiber' or intf2_medium == 'fiber':\r\n return (link_down, link_down)\r\n link_speed = min(intf1_max_speed, intf2_max_speed)\r\n elif intf1_speed == 'auto':\r\n (intf1_link, intf2_link) = port_intf_speed_single_auto(intf1_medium, intf1_max_speed, intf2_speed, intf2_an)\r\n if not intf1_link and not intf2_link:\r\n return (link_down, link_down)\r\n link_speed = intf2_speed\r\n elif intf2_speed == 'auto':\r\n (intf2_link, intf1_link) = port_intf_speed_single_auto(intf2_medium, intf2_max_speed, intf1_speed, intf1_an)\r\n if not intf1_link and not intf2_link:\r\n return (link_down, link_down)\r\n link_speed = intf1_speed\r\n elif intf1_speed != intf2_speed:\r\n return (link_down, link_down)\r\n else:\r\n link_speed = intf1_speed\r\n\r\n if intf1_duplex == 'auto' and intf2_duplex == 'auto':\r\n intf1_link_duplex = 'full'\r\n intf2_link_duplex = 'full'\r\n elif intf1_duplex == 'auto':\r\n (link_stat, intf1_link_duplex, intf2_link_duplex) = port_intf_duplex_single_auto(link_speed, intf1_medium, intf2_duplex, intf2_an)\r\n if not link_stat:\r\n return (link_down, link_down)\r\n elif intf2_duplex == 'auto':\r\n (link_stat, intf2_link_duplex, intf2_link_duplex) = port_intf_duplex_single_auto(link_speed, intf2_medium, intf1_duplex, intf1_an)\r\n if not link_stat:\r\n return (link_down, link_down)\r\n elif intf1_duplex != intf2_duplex:\r\n return (link_down, link_down)\r\n else:\r\n intf1_link_duplex = intf1_duplex\r\n intf2_link_duplex = intf2_duplex\r\n\r\n if intf1_flowctrl == 'auto' or intf2_flowctrl == 'auto':\r\n if intf1_flowctrl != 'auto':\r\n intf1_link_flowctrl = intf1_flowctrl\r\n intf2_link_flowctrl = intf1_flowctrl\r\n elif intf2_flowctrl != 'auto':\r\n intf1_link_flowctrl = intf2_flowctrl\r\n intf2_link_flowctrl = intf2_flowctrl\r\n else:\r\n intf1_link_flowctrl = 'on'\r\n intf2_link_flowctrl = 'on'\r\n else:\r\n intf1_link_flowctrl = intf1_flowctrl\r\n intf2_link_flowctrl = intf2_flowctrl\r\n\r\n return ((intf1_link, link_speed, intf1_link_duplex, intf1_link_flowctrl), (intf2_link, link_speed, intf2_link_duplex, intf2_link_flowctrl))\r\n\r\ndef port_intf_result_check(dev, intf, cfg, link_stat):\r\n \"\"\"\r\n cfg: speed, duplex, flow_ctrl\r\n link_stat: link, speed, duplex, flow_ctrl\r\n \"\"\"\r\n duplex_show = {'auto' : 'AUTO', 'full' : 'Force Full Duplex', 'half' : 'Force Half Duplex'}\r\n speed_show = {'auto' : 'AUTO', '10G' : '10G', '1000' : '1000M', '100' : '100M', '10' : '10M'}\r\n\r\n result = run_cmd(dev, 'show int %s' %intf)\r\n if not link_stat[0]:\r\n if result.find('is DOWN , line protocol is DOWN') == -1:\r\n log_info('######interface %s should link down.' %intf)\r\n return FAIL\r\n return PASS\r\n \r\n if result.find('is UP , line protocol is UP') == -1:\r\n log_info('######interface %s should link up.' %intf)\r\n return FAIL\r\n if result.find('admin duplex mode is %s, oper duplex is %s' %(duplex_show[cfg[1]], link_stat[2].capitalize())) == -1 \\\r\n or result.find('admin speed is %s, oper speed is %s' %(speed_show[cfg[0]], speed_show[link_stat[1]])) == -1 \\\r\n or result.find('flow control admin status is %s, flow control oper status is %s' %(cfg[2].upper(), link_stat[3].upper())) == -1:\r\n log_info('######interface %s link error.' %intf)\r\n log_info('intf link cfg: %s, %s, %s. link stat: %s, %s, %s' %(cfg[0], cfg[1], cfg[2], link_stat[1], link_stat[2], link_stat[3]))\r\n return FAIL\r\n return PASS\r\n\r\ndef port_intf_pkt_check(dev, intf1, intf2):\r\n port_mode_enable(dev)\r\n run_cmd(dev, 'clear counters')\r\n\r\n port_nt_pkt_send(port_nettester_get(), port_nt_intf_list(port_nettester_get())[0])\r\n time.sleep(5)\r\n\r\n for intf in [intf1, intf2]:\r\n if not port_pkts_switch_ok(dev, intf):\r\n log_info('interface %s recv/send has no pkts.' % intf)\r\n return FAIL\r\n\r\n if port_has_error_pkts(dev, intf):\r\n log_info('interface %s recv/send error pkt.' % intf)\r\n return FAIL\r\n\r\n return PASS\r\n \r\ndef port_test_func(dev, intf_cfg, peer_cfg, test_func):\r\n \"\"\"\r\n intf_cfg: (intf, medium, max_speed, speed, duplex, flow_ctrl)\r\n peer_cfg: (peer_intf, medium, max_speed, speed, duplex, flow_ctrl)\r\n \"\"\"\r\n intf = intf_cfg[0]\r\n rv = PASS\r\n ability = port_intf_ability_get(dev, intf)\r\n medium = port_intf_medium_get(dev, intf)\r\n max_speed = port_intf_max_speed_get(intf)\r\n\r\n for speed in speed_ability:\r\n port_intf_mode(dev, intf)\r\n ret_str = run_cmd(dev, 'speed %s' %speed)\r\n time.sleep(STABLE_WAIT)\r\n if not ability[medium][speed]['auto']['auto']:\r\n rv |= port_cmd_unsupport_promt_check(ret_str, intf, 'speed', speed)\r\n continue\r\n for duplex in duplex_ability:\r\n port_intf_mode(dev, intf)\r\n ret_str = run_cmd(dev, 'duplex %s' %duplex)\r\n time.sleep(STABLE_WAIT)\r\n if not ability[medium][speed][duplex]['auto']:\r\n rv |= port_cmd_unsupport_promt_check(ret_str, intf, 'duplex', duplex)\r\n continue\r\n for flow_ctrl in flow_ctrl_ability:\r\n port_intf_mode(dev, intf)\r\n ret_str = run_cmd(dev, 'flowcontrol %s' %flow_ctrl)\r\n time.sleep(STABLE_WAIT)\r\n if not ability[medium][speed][duplex][flow_ctrl]:\r\n rv |= port_cmd_unsupport_promt_check(ret_str, intf, 'flowcontrl', flow_ctrl)\r\n continue\r\n intf_cfg = (intf, medium, max_speed, speed, duplex, flow_ctrl)\r\n rv |= test_func(dev, intf_cfg, peer_cfg)\r\n \r\n return rv\r\n\r\ndef port_single_test(dev, intf_cfg, peer_cfg):\r\n \"\"\"\r\n intf_cfg: (intf, medium, max_speed, speed, duplex, flow_ctrl)\r\n peer_cfg: (peer_intf, medium, max_speed, speed, duplex, flow_ctrl)\r\n \"\"\"\r\n rv = PASS\r\n log_info('#####interface test start:')\r\n\r\n result = port_intf_link_check(intf_cfg[1:], peer_cfg[1:])\r\n \r\n for i in range(2):\r\n if i == 0:\r\n cfg = intf_cfg\r\n else:\r\n cfg = peer_cfg\r\n log_info('interface %s, %s, speed: %s, duplex: %s, flow_ctrl: %s' \\\r\n %(cfg[0], cfg[1], cfg[3], cfg[4], cfg[5]))\r\n rv |= port_intf_result_check(dev, cfg[0], cfg[3:], result[i])\r\n\r\n if rv == PASS and result[0][0] == True and result[1][0] == True:\r\n rv |= port_intf_pkt_check(dev, intf_cfg[0], peer_cfg[0])\r\n \r\n if rv == PASS:\r\n log_info('#####test pass')\r\n else:\r\n log_info('#####test fail')\r\n\r\n return rv\r\n\r\ndef port_pair_test(dev, intf_cfg, peer_cfg):\r\n return port_test_func(dev, peer_cfg, intf_cfg, port_single_test)\r\n\r\ndef _port_speed_cfg(cb_arg):\r\n dev = cb_arg.dev_names[0]\r\n rv = PASS\r\n\r\n port_lldp_enable(dev)\r\n\r\n # get test pair\r\n test_pair_lst = port_get_test_intf_pair(dev)\r\n if len(test_pair_lst) == 0:\r\n log_info(\"Failed! 接口需要互联起来.\")\r\n return FAIL\r\n\r\n port_lldp_disable(dev)\r\n\r\n # shutdown test port\r\n for pair in test_pair_lst:\r\n port_intf_shutdown(dev, pair[0])\r\n port_intf_shutdown(dev, pair[1])\r\n\r\n # test each pair\r\n for pair in test_pair_lst:\r\n # default port\r\n port_intf_default(dev, pair[0])\r\n port_intf_default(dev, pair[1])\r\n rv |= port_test_func(dev, (pair[0], 0), (pair[1], 0), port_pair_test)\r\n port_intf_shutdown(dev, pair[0])\r\n port_intf_shutdown(dev, pair[1])\r\n\r\n for pair in test_pair_lst:\r\n port_intf_default(dev, pair[0])\r\n port_intf_default(dev, pair[1])\r\n\r\n # restore lldp\r\n port_lldp_enable(dev)\r\n\r\n return rv\r\n\r\ndef port_speed_cfg(cb_arg):\r\n if len(cb_arg.dev_names) < 1:\r\n log_info(\"Failed: Need one switch to be test.\")\r\n return FAIL\r\n\r\n dev_name = cb_arg.dev_names[0]\r\n wake_up_console(dev_name)\r\n \r\n port_nettester_add(cb_arg.nt_names[0])\r\n\r\n result = FAIL\r\n try:\r\n result = _port_speed_cfg(cb_arg)\r\n finally:\r\n exit_console(dev_name)\r\n\r\n return result\r\n\r\n","sub_path":"cases_set/dintf/l2pt/port_speed_cfg.py","file_name":"port_speed_cfg.py","file_ext":"py","file_size_in_byte":13373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"608670867","text":"\n\"\"\"\nThis is very usefull module in-case of cipher encrypting and decrypting of data.\nThis contains many cipher methods. The Best of all is the vigenere cipher which\nis also used in these modern times.\n\nThe Source code is taken from the book \"Cracking Codes with Python\". Although\nhacking methods for all the ciphers are not created, the hackers can still\nbreak the code by using different techniques.\n\"\"\"\n\n__version__ = \"2020.6.4\"\n__author__ = \"Xcodz\"\n\n# Copyright (c) 2020 Xcodz.\n# All Rights Reserved.\n\nimport math\nclass cryptomath:\n def gcd(a,b):\n while a != 0:\n a,b = b%a,a\n return b\n def findModInverse(a,m):\n if cryptomath.gcd(a,m) != 1:\n return None\n u1,u2,u3=1,0,a\n v1,v2,v3=0,1,m\n while v3!=0:\n q=u3//v3\n v1,v2,v3,u1,u2,u3 = (u1-q*v1),(u2-q*v2),(u3-q*v3),v1,v2,v3\n return u1%m\nclass cVig:\n l = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n def translateMessage(key,message,mode):\n l = cVig.l\n t =[]\n ki= 0\n k = key.upper()\n for x in message:\n n = l.find(x.upper())\n if n != -1:\n if mode == 'e':\n n+=l.find(key[ki])\n elif mode == 'd':\n n-=l.find(key[ki])\n n%=len(l)\n if x.isupper():\n t.append(l[n])\n elif x.islower():\n t.append(l[n].lower())\n ki+=1\n if ki == len(key):\n ki =0\n else:\n t.append(x)\n return ''.join(t)\nclass cSub:\n l = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n def keyIsValid(key):\n keyList = list(key)\n lettersList = list(cSub.l)\n keyList.sort()\n return keyList == lettersList\n def translateMessage(key:str,message:str,mode):\n t = ''\n ca = cSub.l\n cb = key\n if mode == 'd':\n ca,cb=cb,ca\n for x in message:\n if x.upper() in ca:\n si = ca.find(x.upper())\n if x.isupper():\n t+=cb[si].upper()\n else:\n t+=cb[si].lower()\n else:\n t+=x\n return t\nclass cAffine:\n def getKeyParts(key):\n a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'\n keyA = key//len(a)\n keyB = key%len(a)\n return keyA,keyB\n def checkKeys(keyA,keyB):\n a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'\n if keyA <0 or keyB<0 or keyB>len(a)-1:\n return False\n if cryptomath.gcd(keyA, len(a)) != 1:\n return False\n return True\nclass crypt:\n class morse:\n table = {\n '.-':'A',\n '-...':'B',\n '-.-.':'C',\n '-..':'D',\n '.':'E',\n '..-.':'F',\n '--.':'G',\n '....':'H',\n '..':'I',\n '.---':'J',\n '-.-':'K',\n '.-..':'L',\n '--':'M',\n '-.':'N',\n '---':'O',\n '.--.':'P',\n '--.-':'Q',\n '.-.':'R',\n '...':'S',\n '-':'T',\n '..-':'U',\n '...-':'V',\n '.--':'W',\n '-..-':'X',\n '-.--':'Y',\n '--..':'Z',\n '.----':'1',\n '..---':'2',\n '...--':'3',\n '....-':'4',\n '.....':'5',\n '-....':'6',\n '--...':'7',\n '---..':'8',\n '----.':'9',\n '-----':'0'\n }\n def encode(st:str):\n \"\"\"MORSE CODE ENCODER\n\nA ' ' MEANS PARTITION BETWEEN LETTERS\nA '/' MEANS PARTITION BETWEEN WORDS\"\"\"\n t = ''\n tb = {v:k for k,v in crypt.morse.table.items()}\n s = list(st.upper())\n for x in s:\n if x not in tb.keys() and x != ' ':\n s.remove(x)\n w = []\n for x in s:\n if x == ' ':\n t+=' '.join(w)+'/'\n w = []\n else:\n w.append(tb[x])\n t+=' '.join(w)\n return t\n def decode(s:str):\n tb = crypt.morse.table.copy()\n d = [x.split() for x in s.split('/')]\n t= ''\n for x in d:\n for y in x:\n t+=tb[y]\n t+= ' '\n return t[0:-1]\n class basic:\n def encode(b:bytes = b''):\n \"\"\"Encode Bytes to String\"\"\"\n d = [hex(x)[2:] for x in list(b)]\n for x in range(len(d)):\n if len(d[x]) == 1:\n d[x] = '0'+d[x]\n return ''.join(d)\n def decode(s:str):\n return bytes([int('0x'+s[x]+s[x+1], 0) for x in range(0,len(s),2)])\n class cipher:\n class reverse:\n def crypt(s:str):\n \"\"\"ENCODING AND DECODING FUNCTIONS ARE SAME\"\"\"\n t = ''\n i = len(s)-1\n while i >= 0:\n t+=s[i]\n i-=1\n return t\n class caesar:\n def encrypt(s:str,k:int):\n \"\"\"Encrypts with ceasar cipher\"\"\"\n a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'\n t = ''\n for x in s:\n if x in a:\n si = a.find(x)\n ti = si+k\n if ti >= len(a):\n ti-=len(a)\n elif ti < 0:\n ti+=len(a)\n t+=a[ti]\n else:\n t+=x\n return t\n def decrypt(s:str,k:int):\n \"\"\"Decrypts with ceasar cipher\"\"\"\n a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'\n t = ''\n for x in s:\n if x in a:\n si = a.find(x)\n ti = si-k\n if ti >= len(a):\n ti-=len(a)\n elif ti < 0:\n ti+=len(a)\n t+=a[ti]\n else:\n t+=x\n return t\n class transposition:\n def encrypt(message:str,key:int):\n # Each string in ciphertext represents a column in the grid:\n ciphertext = [''] * key\n # Loop through each column in ciphertext:\n for column in range(key):\n currentIndex = column\n # Keep looping until currentIndex goes past the message length:\n while currentIndex < len(message):\n # Place the character at currentIndex in message at the\n # end of the current column in the ciphertext list:\n ciphertext[column] += message[currentIndex]\n # Move currentIndex over:\n currentIndex += key\n # Convert the ciphertext list into a single string value and return it:\n return ''.join(ciphertext)\n def decrypt(message:str,key:int):\n numOfColumns = int(math.ceil(len(message) / float(key)))\n numOfRows = key\n numOfShadedBoxes = (numOfColumns * numOfRows) - len(message)\n plaintext = [''] * numOfColumns\n column = row = 0\n for symbol in message:\n plaintext[column] += symbol\n column+=1\n if (column == numOfColumns) or (column == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes):\n column = 0\n row+=1\n return ''.join(plaintext)\n class affine:\n def encrypt(message:str,key:int):\n a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'\n ka,kb=cAffine.getKeyParts(key)\n if cAffine.checkKeys(ka,kb):\n ct = ''\n for x in message:\n if x in a:\n si = a.find(x)\n ct+=a[(si*ka+kb)%len(a)]\n else:\n ct+= x\n return ct\n else:\n return message\n def decrypt(message:str,key:int):\n a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'\n ka,kb=cAffine.getKeyParts(key)\n if cAffine.checkKeys(ka,kb):\n pt = ''\n mioka = cryptomath.findModInverse(ka,len(a))\n for x in message:\n if x in a:\n si = a.find(x)\n pt+=a[(si-kb)*mioka%len(a)]\n else:\n pt+=x\n return pt\n else:\n return message\n class substitution:\n def encrypt(m:str,key:str):\n return cSub.translateMessage(key,m,'e')\n def decrypt(m:str,key:str):\n return cSub.translateMessage(key,m,'d')\n class vigenere:\n def encrypt(m:str,k:str):\n return cVig.translateMessage(k,m,'e')\n def decrypt(m:str,k:str):\n return cVig.translateMessage(k,m,'d')\n class hack:\n def caesar(st:str, s = 0, e = len('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.')):\n for x in range(s,e):\n print(f\"Cipher Caesar Hack; Key = {x} => \"+crypt.cipher.caesar.decrypt(st,x))","sub_path":"denver/crypt.py","file_name":"crypt.py","file_ext":"py","file_size_in_byte":9910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"99556423","text":"import pyrebase\n\nclass FireBaseUpdater():\n firebase = None\n info = None\n db = None\n\n firebase = None;\n def __init__(self, config):\n self.firebase = pyrebase.initialize_app(config)\n self.db = self.firebase.database()\n\n def get_information(self):\n self.info = self.db.child(\"OnGroundRobot\").child(\"Receive\").get().val()\n return self.info\n\n def write_information(self, ControllerLy: float, ControllerRx: float, light_on: bool):\n data = {'ControllerLy_Rx':[ControllerLy, ControllerRx], 'LightOn': light_on}\n self.db.child(\"OnGroundRobot\").child(\"Send\").set(data)\n\ndef main():\n config = {\n \"apiKey\": \"AIzaSyBBFze3rkgjPBwEkno8ZFOuHZLCWhbXstk\",\n \"authDomain\": \"synopsys2020-1.firebaseapp.com\",\n \"databaseURL\": \"https://synopsys2020-1.firebaseio.com/\",\n \"storageBucket\": \"synopsys2020-1.appspot.com\"\n }\n db = FireBaseUpdater(config)\n\n print(db.get_information())\n db.write_information(.2, .2, True)\n\nif __name__ == \"__main__\":\n main()","sub_path":"OnGroundRobot/FireBaseInterfacer.py","file_name":"FireBaseInterfacer.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"12511354","text":"import collections\n\nfrom flask import render_template\nfrom werkzeug.exceptions import abort\nimport datetime\nimport logging\nfrom uuid import UUID\n\nimport Items\nimport Regions\nfrom WebHostLib import app, cache, Room\nfrom Utils import Hint\n\n\ndef get_id(item_name):\n return Items.item_table[item_name][2]\n\n\napp.jinja_env.filters[\"location_name\"] = lambda location: Regions.lookup_id_to_name.get(location, location)\napp.jinja_env.filters['item_name'] = lambda id: Items.lookup_id_to_name.get(id, id)\n\nicons = {\n \"Progressive Sword\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/c/cc/ALttP_Master_Sword_Sprite.png?version=55869db2a20e157cd3b5c8f556097725\",\n \"Pegasus Boots\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/e/ed/ALttP_Pegasus_Shoes_Sprite.png?version=405f42f97240c9dcd2b71ffc4bebc7f9\",\n \"Progressive Glove\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/5/53/ALttP_Titan's_Mitt_Sprite.png?version=6ac54c3016a23b94413784881fcd3c75\",\n \"Flippers\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/8/88/ALttP_Zora's_Flippers_Sprite.png?version=b9d7521bb3a5a4d986879f70a70bc3da\",\n \"Moon Pearl\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/6/63/ALttP_Moon_Pearl_Sprite.png?version=d601542d5abcc3e006ee163254bea77e\",\n \"Progressive Bow\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/b/bc/ALttP_Bow_%26_Arrows_Sprite.png?version=cfb7648b3714cccc80e2b17b2adf00ed\",\n \"Blue Boomerang\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/c/c3/ALttP_Boomerang_Sprite.png?version=96127d163759395eb510b81a556d500e\",\n \"Red Boomerang\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/b/b9/ALttP_Magical_Boomerang_Sprite.png?version=47cddce7a07bc3e4c2c10727b491f400\",\n \"Hookshot\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/2/24/Hookshot.png?version=c90bc8e07a52e8090377bd6ef854c18b\",\n \"Mushroom\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/3/35/ALttP_Mushroom_Sprite.png?version=1f1acb30d71bd96b60a3491e54bbfe59\",\n \"Magic Powder\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/e/e5/ALttP_Magic_Powder_Sprite.png?version=c24e38effbd4f80496d35830ce8ff4ec\",\n \"Fire Rod\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/d/d6/FireRod.png?version=6eabc9f24d25697e2c4cd43ddc8207c0\",\n \"Ice Rod\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/d/d7/ALttP_Ice_Rod_Sprite.png?version=1f944148223d91cfc6a615c92286c3bc\",\n \"Bombos\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/8/8c/ALttP_Bombos_Medallion_Sprite.png?version=f4d6aba47fb69375e090178f0fc33b26\",\n \"Ether\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/3/3c/Ether.png?version=34027651a5565fcc5a83189178ab17b5\",\n \"Quake\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/5/56/ALttP_Quake_Medallion_Sprite.png?version=efd64d451b1831bd59f7b7d6b61b5879\",\n \"Lamp\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/6/63/ALttP_Lantern_Sprite.png?version=e76eaa1ec509c9a5efb2916698d5a4ce\",\n \"Hammer\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/d/d1/ALttP_Hammer_Sprite.png?version=e0adec227193818dcaedf587eba34500\",\n \"Shovel\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/c/c4/ALttP_Shovel_Sprite.png?version=e73d1ce0115c2c70eaca15b014bd6f05\",\n \"Flute\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/d/db/Flute.png?version=ec4982b31c56da2c0c010905c5c60390\",\n \"Bug Catching Net\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/5/54/Bug-CatchingNet.png?version=4d40e0ee015b687ff75b333b968d8be6\",\n \"Book of Mudora\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/2/22/ALttP_Book_of_Mudora_Sprite.png?version=11e4632bba54f6b9bf921df06ac93744\",\n \"Bottle\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/e/ef/ALttP_Magic_Bottle_Sprite.png?version=fd98ab04db775270cbe79fce0235777b\",\n \"Cane of Somaria\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/e/e1/ALttP_Cane_of_Somaria_Sprite.png?version=8cc1900dfd887890badffc903bb87943\",\n \"Cane of Byrna\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/b/bc/ALttP_Cane_of_Byrna_Sprite.png?version=758b607c8cbe2cf1900d42a0b3d0fb54\",\n \"Cape\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/1/1c/ALttP_Magic_Cape_Sprite.png?version=6b77f0d609aab0c751307fc124736832\",\n \"Magic Mirror\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/e/e5/ALttP_Magic_Mirror_Sprite.png?version=e035dbc9cbe2a3bd44aa6d047762b0cc\",\n \"Triforce\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/4/4e/TriforceALttPTitle.png?version=dc398e1293177581c16303e4f9d12a48\",\n \"Small Key\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/f/f1/ALttP_Small_Key_Sprite.png?version=4f35d92842f0de39d969181eea03774e\",\n \"Big Key\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/3/33/ALttP_Big_Key_Sprite.png?version=136dfa418ba76c8b4e270f466fc12f4d\",\n \"Chest\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/7/73/ALttP_Treasure_Chest_Sprite.png?version=5f530ecd98dcb22251e146e8049c0dda\",\n\n \"Light World\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/e/e7/ALttP_Soldier_Green_Sprite.png?version=d650d417934cd707a47e496489c268a6\",\n \"Dark World\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/9/94/ALttP_Moblin_Sprite.png?version=ebf50e33f4657c377d1606bcc0886ddc\",\n \"Hyrule Castle\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/d/d3/ALttP_Ball_and_Chain_Trooper_Sprite.png?version=1768a87c06d29cc8e7ddd80b9fa516be\",\n \"Agahnims Tower\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/1/1e/ALttP_Agahnim_Sprite.png?version=365956e61b0c2191eae4eddbe591dab5\",\n \"Desert Palace\":\n r\"https://www.zeldadungeon.net/wiki/images/2/25/Lanmola-ALTTP-Sprite.png\",\n \"Eastern Palace\":\n r\"https://www.zeldadungeon.net/wiki/images/d/dc/RedArmosKnight.png\",\n \"Tower of Hera\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/3/3c/ALttP_Moldorm_Sprite.png?version=c588257bdc2543468e008a6b30f262a7\",\n \"Palace of Darkness\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/e/ed/ALttP_Helmasaur_King_Sprite.png?version=ab8a4a1cfd91d4fc43466c56cba30022\",\n \"Swamp Palace\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/7/73/ALttP_Arrghus_Sprite.png?version=b098be3122e53f751b74f4a5ef9184b5\",\n \"Skull Woods\":\n r\"https://alttp-wiki.net/images/6/6a/Mothula.png\",\n \"Thieves Town\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/8/86/ALttP_Blind_the_Thief_Sprite.png?version=3833021bfcd112be54e7390679047222\",\n \"Ice Palace\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/3/33/ALttP_Kholdstare_Sprite.png?version=e5a1b0e8b2298e550d85f90bf97045c0\",\n \"Misery Mire\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/8/85/ALttP_Vitreous_Sprite.png?version=92b2e9cb0aa63f831760f08041d8d8d8\",\n \"Turtle Rock\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/9/91/ALttP_Trinexx_Sprite.png?version=0cc867d513952aa03edd155597a0c0be\",\n \"Ganons Tower\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/b/b9/ALttP_Ganon_Sprite.png?version=956f51f054954dfff53c1a9d4f929c74\"\n}\n\nlinks = {\"Bow\": \"Progressive Bow\",\n \"Silver Arrows\": \"Progressive Bow\",\n \"Silver Bow\": \"Progressive Bow\",\n \"Progressive Bow (Alt)\": \"Progressive Bow\",\n \"Bottle (Red Potion)\": \"Bottle\",\n \"Bottle (Green Potion)\": \"Bottle\",\n \"Bottle (Blue Potion)\": \"Bottle\",\n \"Bottle (Fairy)\": \"Bottle\",\n \"Bottle (Bee)\": \"Bottle\",\n \"Bottle (Good Bee)\": \"Bottle\",\n \"Fighter Sword\": \"Progressive Sword\",\n \"Master Sword\": \"Progressive Sword\",\n \"Tempered Sword\": \"Progressive Sword\",\n \"Golden Sword\": \"Progressive Sword\",\n \"Power Glove\": \"Progressive Glove\",\n \"Titans Mitts\": \"Progressive Glove\"\n }\n\nlevels = {\"Fighter Sword\": 1,\n \"Master Sword\": 2,\n \"Tempered Sword\": 3,\n \"Golden Sword\": 4,\n \"Power Glove\": 1,\n \"Titans Mitts\": 2,\n \"Bow\": 1,\n \"Silver Bow\": 2}\n\nmulti_items = {get_id(name) for name in (\"Progressive Sword\", \"Progressive Bow\", \"Bottle\", \"Progressive Glove\")}\nlinks = {get_id(key): get_id(value) for key, value in links.items()}\nlevels = {get_id(key): value for key, value in levels.items()}\n\ntracking_names = [\"Progressive Sword\", \"Progressive Bow\", \"Book of Mudora\", \"Hammer\",\n \"Hookshot\", \"Magic Mirror\", \"Flute\",\n \"Pegasus Boots\", \"Progressive Glove\", \"Flippers\", \"Moon Pearl\", \"Blue Boomerang\",\n \"Red Boomerang\", \"Bug Catching Net\", \"Cape\", \"Shovel\", \"Lamp\",\n \"Mushroom\", \"Magic Powder\",\n \"Cane of Somaria\", \"Cane of Byrna\", \"Fire Rod\", \"Ice Rod\", \"Bombos\", \"Ether\", \"Quake\",\n \"Bottle\", \"Triforce\"] # TODO make sure this list has what we need and sort it better\n\ndefault_locations = {\n 'Light World': {1572864, 1572865, 60034, 1572867, 1572868, 60037, 1572869, 1572866, 60040, 59788, 60046, 60175,\n 1572880, 60049, 60178, 1572883, 60052, 60181, 1572885, 60055, 60184, 191256, 60058, 60187, 1572884,\n 1572886, 1572887, 1572906, 60202, 60205, 59824, 166320, 1010170, 60208, 60211, 60214, 60217, 59836,\n 60220, 60223, 59839, 1573184, 60226, 975299, 1573188, 1573189, 188229, 60229, 60232, 1573193,\n 1573194, 60235, 1573187, 59845, 59854, 211407, 60238, 59857, 1573185, 1573186, 1572882, 212328,\n 59881, 59761, 59890, 59770, 193020, 212605},\n 'Dark World': {59776, 59779, 975237, 1572870, 60043, 1572881, 60190, 60193, 60196, 60199, 60840, 1573190, 209095,\n 1573192, 1573191, 60241, 60244, 60247, 60250, 59884, 59887, 60019, 60022, 60028, 60031},\n 'Desert Palace': {1573216, 59842, 59851, 59791, 1573201, 59830},\n 'Eastern Palace': {1573200, 59827, 59893, 59767, 59833, 59773},\n 'Hyrule Castle': {60256, 60259, 60169, 60172, 59758, 59764, 60025, 60253},\n 'Agahnims Tower': {60082, 60085},\n 'Tower of Hera': {1573218, 59878, 59821, 1573202, 59896, 59899},\n 'Swamp Palace': {60064, 60067, 60070, 59782, 59785, 60073, 60076, 60079, 1573204, 60061},\n 'Thieves Town': {59905, 59908, 59911, 59914, 59917, 59920, 59923, 1573206},\n 'Skull Woods': {59809, 59902, 59848, 59794, 1573205, 59800, 59803, 59806},\n 'Ice Palace': {59872, 59875, 59812, 59818, 59860, 59797, 1573207, 59869},\n 'Misery Mire': {60001, 60004, 60007, 60010, 60013, 1573208, 59866, 59998},\n 'Turtle Rock': {59938, 59941, 59944, 1573209, 59947, 59950, 59953, 59956, 59926, 59929, 59932, 59935},\n 'Palace of Darkness': {59968, 59971, 59974, 59977, 59980, 59983, 59986, 1573203, 59989, 59959, 59992, 59962, 59995,\n 59965},\n 'Ganons Tower': {60160, 60163, 60166, 60088, 60091, 60094, 60097, 60100, 60103, 60106, 60109, 60112, 60115, 60118,\n 60121, 60124, 60127, 1573217, 60130, 60133, 60136, 60139, 60142, 60145, 60148, 60151, 60157},\n 'Total': set()}\n\nkey_only_locations = {\n 'Light World': set(),\n 'Dark World': set(),\n 'Desert Palace': {0x140031, 0x14002b, 0x140061, 0x140028},\n 'Eastern Palace': {0x14005b, 0x140049},\n 'Hyrule Castle': {0x140037, 0x140034, 0x14000d, 0x14003d},\n 'Agahnims Tower': {0x140061, 0x140052},\n 'Tower of Hera': set(),\n 'Swamp Palace': {0x140019, 0x140016, 0x140013, 0x140010, 0x14000a},\n 'Thieves Town': {0x14005e, 0x14004f},\n 'Skull Woods': {0x14002e, 0x14001c},\n 'Ice Palace': {0x140004, 0x140022, 0x140025, 0x140046},\n 'Misery Mire': {0x140055, 0x14004c, 0x140064},\n 'Turtle Rock': {0x140058, 0x140007},\n 'Palace of Darkness': set(),\n 'Ganons Tower': {0x140040, 0x140043, 0x14003a, 0x14001f},\n 'Total': set()\n}\n\nkey_locations = {\"Desert Palace\", \"Eastern Palace\", \"Hyrule Castle\", \"Agahnims Tower\", \"Tower of Hera\", \"Swamp Palace\",\n \"Thieves Town\", \"Skull Woods\", \"Ice Palace\", \"Misery Mire\", \"Turtle Rock\", \"Palace of Darkness\",\n \"Ganons Tower\"}\n\nbig_key_locations = {\"Desert Palace\", \"Eastern Palace\", \"Tower of Hera\", \"Swamp Palace\", \"Thieves Town\", \"Skull Woods\",\n \"Ice Palace\", \"Misery Mire\", \"Turtle Rock\", \"Palace of Darkness\", \"Ganons Tower\"}\nlocation_to_area = {}\nfor area, locations in default_locations.items():\n for location in locations:\n location_to_area[location] = area\n\nfor area, locations in key_only_locations.items():\n for location in locations:\n location_to_area[location] = area\n\nchecks_in_area = {area: len(checks) for area, checks in default_locations.items()}\nchecks_in_area[\"Total\"] = 216\n\nordered_areas = ('Light World', 'Dark World', 'Hyrule Castle', 'Agahnims Tower', 'Eastern Palace', 'Desert Palace',\n 'Tower of Hera', 'Palace of Darkness', 'Swamp Palace', 'Skull Woods', 'Thieves Town', 'Ice Palace',\n 'Misery Mire', 'Turtle Rock', 'Ganons Tower', \"Total\")\n\ntracking_ids = []\n\nfor item in tracking_names:\n tracking_ids.append(get_id(item))\n\nsmall_key_ids = {}\nbig_key_ids = {}\n\nfor item_name, data in Items.item_table.items():\n if \"Key\" in item_name:\n area = item_name.split(\"(\")[1][:-1]\n if \"Small\" in item_name:\n small_key_ids[area] = data[2]\n else:\n big_key_ids[area] = data[2]\n\nfrom MultiServer import get_item_name_from_id\n\n\ndef attribute_item(inventory, team, recipient, item):\n target_item = links.get(item, item)\n if item in levels: # non-progressive\n inventory[team][recipient][target_item] = max(inventory[team][recipient][target_item], levels[item])\n else:\n inventory[team][recipient][target_item] += 1\n\n\n@app.template_filter()\ndef render_timedelta(delta: datetime.timedelta):\n hours, minutes = divmod(delta.total_seconds() / 60, 60)\n hours = str(int(hours))\n minutes = str(int(minutes)).zfill(2)\n return f\"{hours}:{minutes}\"\n\n\n_multidata_cache = {}\n\ndef get_location_table(checks_table: dict) -> dict:\n loc_to_area = {}\n for area, locations in checks_table.items():\n if area == \"Total\":\n continue\n for location in locations:\n loc_to_area[location] = area\n return loc_to_area\n\ndef get_static_room_data(room: Room):\n result = _multidata_cache.get(room.seed.id, None)\n if result:\n return result\n multidata = room.seed.multidata\n # in > 100 players this can take a bit of time and is the main reason for the cache\n locations = {tuple(k): tuple(v) for k, v in multidata['locations']}\n names = multidata[\"names\"]\n seed_checks_in_area = checks_in_area.copy()\n\n use_door_tracker = False\n if \"tags\" in multidata:\n use_door_tracker = \"DR\" in multidata[\"tags\"]\n if use_door_tracker:\n for area, checks in key_only_locations.items():\n seed_checks_in_area[area] += len(checks)\n seed_checks_in_area[\"Total\"] = 249\n if \"checks_in_area\" not in multidata:\n player_checks_in_area = {playernumber: (seed_checks_in_area if use_door_tracker and\n (0x140031, playernumber) in locations else checks_in_area)\n for playernumber in range(1, len(names[0]) + 1)}\n player_location_to_area = {playernumber: location_to_area\n for playernumber in range(1, len(names[0]) + 1)}\n\n else:\n player_checks_in_area = {playernumber: {areaname: len(multidata[\"checks_in_area\"][f'{playernumber}'][areaname])\n if areaname != \"Total\" else multidata[\"checks_in_area\"][f'{playernumber}'][\"Total\"]\n for areaname in ordered_areas}\n for playernumber in range(1, len(names[0]) + 1)}\n player_location_to_area = {playernumber: get_location_table(multidata[\"checks_in_area\"][f'{playernumber}'])\n for playernumber in range(1, len(names[0]) + 1)}\n result = locations, names, use_door_tracker, player_checks_in_area, player_location_to_area\n _multidata_cache[room.seed.id] = result\n return result\n\n\n@app.route('/tracker/')\n@cache.memoize(timeout=30) # update every 30 seconds\ndef getTracker(tracker: UUID):\n room = Room.get(tracker=tracker)\n if not room:\n abort(404)\n locations, names, use_door_tracker, seed_checks_in_area, player_location_to_area = get_static_room_data(room)\n\n inventory = {teamnumber: {playernumber: collections.Counter() for playernumber in range(1, len(team) + 1)}\n for teamnumber, team in enumerate(names)}\n\n checks_done = {teamnumber: {playernumber: {loc_name: 0 for loc_name in default_locations}\n for playernumber in range(1, len(team) + 1)}\n for teamnumber, team in enumerate(names)}\n precollected_items = room.seed.multidata.get(\"precollected_items\", None)\n hints = {team: set() for team in range(len(names))}\n if \"hints\" in room.multisave:\n for key, hintdata in room.multisave[\"hints\"]:\n for hint in hintdata:\n hints[key[0]].add(Hint(*hint))\n\n for (team, player), locations_checked in room.multisave.get(\"location_checks\", {}):\n if precollected_items:\n precollected = precollected_items[player - 1]\n for item_id in precollected:\n attribute_item(inventory, team, player, item_id)\n for location in locations_checked:\n if (location, player) not in locations or location not in player_location_to_area[player]:\n continue\n\n item, recipient = locations[location, player]\n attribute_item(inventory, team, recipient, item)\n checks_done[team][player][player_location_to_area[player][location]] += 1\n checks_done[team][player][\"Total\"] += 1\n\n for (team, player), game_state in room.multisave.get(\"client_game_state\", []):\n if game_state:\n inventory[team][player][106] = 1 # Triforce\n\n activity_timers = {}\n now = datetime.datetime.utcnow()\n for (team, player), timestamp in room.multisave.get(\"client_activity_timers\", []):\n activity_timers[team, player] = now - datetime.datetime.utcfromtimestamp(timestamp)\n\n player_names = {}\n for team, names in enumerate(names):\n for player, name in enumerate(names, 1):\n player_names[(team, player)] = name\n long_player_names = player_names.copy()\n for (team, player), alias in room.multisave.get(\"name_aliases\", []):\n player_names[(team, player)] = alias\n long_player_names[(team, player)] = f\"{alias} ({long_player_names[(team, player)]})\"\n\n video = {}\n for (team, player), data in room.multisave.get(\"video\", []):\n video[(team, player)] = data\n\n return render_template(\"tracker.html\", inventory=inventory, get_item_name_from_id=get_item_name_from_id,\n lookup_id_to_name=Items.lookup_id_to_name, player_names=player_names,\n tracking_names=tracking_names, tracking_ids=tracking_ids, room=room, icons=icons,\n multi_items=multi_items, checks_done=checks_done, ordered_areas=ordered_areas,\n checks_in_area=seed_checks_in_area, activity_timers=activity_timers,\n key_locations=key_locations, small_key_ids=small_key_ids, big_key_ids=big_key_ids,\n video=video, big_key_locations=key_locations if use_door_tracker else big_key_locations,\n hints=hints, long_player_names = long_player_names)\n","sub_path":"WebHostLib/tracker.py","file_name":"tracker.py","file_ext":"py","file_size_in_byte":19910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"430387076","text":"\"\"\"\"Week 5 exercises regarding knapsack problem\"\"\"\n\nimport datetime\n\ndef knapsack(items, max_weight):\n \"\"\"\n Classical DP solution to knapsack problem\n items -- an iterable containing tuples (weight, value)\n max_weight -- integer indicating the max weight the knapsack can hold\n \"\"\"\n solutions = [0 for x in range(max_weight+1)]\n for i in range(0, max_weight + 1):\n for (weight, value) in items:\n if weight <= i:\n solutions[i] = max(solutions[i], solutions[i - weight] + value)\n\n return solutions\n\ndef get_solution(solutions, weight):\n \"\"\"\"Gets the solution from the given map\"\"\"\n if weight in solutions:\n return solutions[weight]\n return 0\n\ndef knapsack_map(items, max_weight):\n \"\"\"Same as the traditional DP solution but uses a map instead of an array\"\"\"\n solutions = {}\n for i in range(0, max_weight + 1):\n for (weight, value) in items:\n if weight <= i:\n solutions[i] = max(\n get_solution(solutions, weight),\n get_solution(solutions, i - weight) + value\n )\n return solutions\n\n# (weight, value)\nitems_arr = ((1, 10), (3, 40), (4, 50), (5, 70))\n\nprint(knapsack(items_arr, 8))\n\n","sub_path":"week5/unbounded_knapsack.py","file_name":"unbounded_knapsack.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"157386876","text":"# imports\n# end imports\n\n\nclass Constants:\n def __init__(self):\n self.DATA_IDX = 0\n self.LABEL_IDX = 1\n\n self.NO_MORE_SAMPLES = -1\n self.LEAF_CREATED_SUCCESSFULLY = 1\n\n self.TP_IDX = 0\n self.FP_IDX = 1\n self.TN_IDX = 2\n self.FN_IDX = 3","sub_path":"HW4/code/Constants.py","file_name":"Constants.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"451666828","text":"#================================================================\n#Importing Libraries\nimport turtle \nimport random\n\n#head orientation\nh = [0]\n\n#score\na = [0]\nb = [0]\n\n#food coord\nfcoord = [0,0,0]\n\n#position\npos = []\n\n#===================================================================\n#homimg function\n\ndef home(x=0,y=0):\n a[0] = 0\n b[0] = 0\n h[0] = 0\n fcoord[2] = 0\n pos[:] = []\n turtle.hideturtle()\n turtle.clear()\n turtle.pu()\n turtle.color(\"black\")\n turtle.goto(0,0)\n turtle.write(\"Press Enter to Play\",align=\"center\",font=(50))\n turtle.title(\"SNAKE\")\n \n\n turtle.onkey(start, 'Return')\n \n turtle.listen()\n \n turtle.mainloop()\n\n #====================================================================\n#Define to Playable Area\n \ndef boundary_area():\n turtle.clear()\n turtle.pu()\n turtle.speed(0)\n turtle.pensize(20)\n turtle.color(\"grey\")\n turtle.goto(-300,300)\n turtle.pd()\n turtle.goto(300,300)\n turtle.goto(300,-300)\n turtle.goto(-300,-300)\n turtle.goto(-300,300)\n turtle.pu()\n turtle.goto(+100,0)\n\n#===================================================================\n#Controller Function\n \ndef start(x=0,y=0): \n\n boundary_area()\n\n tfood = turtle.Turtle()\n tfood.hideturtle()\n tfood.pu()\n tfood.speed(0)\n tfood.shape(\"square\")\n tfood.color(\"red\")\n\n tscore = turtle.Turtle()\n tscore.hideturtle()\n tscore.pu()\n tscore.speed(0)\n tscore.goto(250,-290)\n tscore.write(\"Score:\" + str(a[0]), align=\"center\",font=(10))\n \n while x > -290 and x < 290 and y > -290 and y <290:\n if fcoord[2] == 0:\n food(tfood)\n fcoord[2] = 1\n turtle.onkey(u,\"Up\")\n turtle.onkey(l,\"Left\")\n turtle.onkey(r,\"Right\")\n turtle.onkey(d,\"Down\")\n turtle.listen()\n move()\n x = turtle.xcor()\n y = turtle.ycor() \n if x > fcoord[0]*20-5 and x < fcoord[0]*20+5 and y > fcoord[1]*20-5 and y < fcoord[1]*20+5:\n fcoord[2] = 0\n tfood.clear()\n a[0] += 1\n tscore.clear()\n tscore.write(\"Score:\" + str(a[0]), align=\"center\",font=(10))\n \n if len(pos) > 1:\n for i in range(1,len(pos)):\n if x < pos[i][0]+5 and x > pos[i][0]-5 and y < pos[i][1]+5 and y > pos[i][1]-5:\n tscore.clear()\n tfood.clear()\n gameover()\n tscore.clear()\n tfood.clear()\n gameover()\n\n#===================================================================\n#Food\n \ndef food(tfood):\n x = random.randrange(-8,8,1)\n y = random.randrange(-8,8,1)\n fcoord[0] = x\n fcoord[1] = y\n tfood.hideturtle()\n tfood.pu()\n tfood.shape(\"square\")\n tfood.color(\"red\")\n tfood.goto(x*20,y*20)\n tfood.stamp()\n\n\n#===================================================================\n#Change Directions\n \ndef u():\n if h[0] == 270:\n pass\n else:\n h[0] = 90\n\ndef d():\n if h[0] == 90:\n pass\n else:\n h[0] = 270\n\ndef l():\n if h[0] == 0:\n pass\n else:\n h[0] = 180\n\ndef r():\n if h[0] == 180:\n pass\n else:\n h[0] = 0\n\n\n#===================================================================\n#movement of snake\n \ndef move():\n turtle.pensize(1)\n turtle.color(\"black\")\n turtle.pu()\n turtle.speed(5)\n turtle.setheading(h[0])\n turtle.shape(\"square\")\n turtle.stamp()\n turtle.fd(20)\n x = turtle.xcor()\n y = turtle.ycor()\n if b[0] > a[0]: \n turtle.clearstamps(1)\n pos.insert(0,[round(x),round(y)])\n pos.pop(-1)\n else:\n pos.insert(0,[round(x),round(y)]) \n b[0] += 1 \n\n\n\n#====================================================================\n#Game ending\n \ndef gameover():\n \n turtle.speed(0)\n turtle.pu()\n turtle.goto(0,150)\n turtle.color(\"red\")\n turtle.write(\"GAME OVER\",align=\"center\", font=(100))\n turtle.goto(0,50)\n turtle.write(\"Score:\" + str(a[0]),align=\"center\",font=(70))\n turtle.goto(0,-150)\n turtle.write(\"(Press 'ENTER' to Play Again)\",align=\"center\",font=(30))\n \n turtle.onkey(home, 'Return')\n \n turtle.listen()\n \n turtle.mainloop()\n\n#===================================================================\n#Main Function\n# Game Start\n\nhome()\n","sub_path":"snake v2.py","file_name":"snake v2.py","file_ext":"py","file_size_in_byte":4399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"368898777","text":"def knapsack(items, weight):\n results = {i: {} for i in range(len(items) + 1)}\n calculated_results = {i: {} for i in range(len(items) + 1)}\n\n def knapsack_rec(n, w):\n if n == 0 or w == 0:\n return 0\n\n if w in calculated_results[n]:\n return calculated_results[n][w]\n\n it = items[n - 1]\n\n if it[1] > w:\n a = knapsack_rec(n - 1, w)\n calculated_results[n][w] = a\n return a\n\n else:\n a = it[0] + knapsack_rec(n - 1, w - it[1])\n b = knapsack_rec(n - 1, w)\n\n if a > b:\n results[n][w] = a\n calculated_results[n][w] = a\n return a\n\n else:\n calculated_results[n][w] = b\n return b\n\n total_value = knapsack_rec(len(items), weight)\n\n result_items = []\n w = weight\n\n for i in range(len(items), 0, -1):\n if w in results[i]:\n result_items.append(i - 1)\n w -= items[i-1][1]\n\n return total_value, result_items\n\n\nif __name__ == \"__main__\":\n it = [[7, 5], [8, 4], [9, 3], [10, 2], [1, 10], [3, 15], [8, 10], [6, 4], [5, 3], [7, 3]] # [9, 8, 3, 2, 1, 0]\n w = 20\n k = knapsack(it, w)\n res = k[1]\n s = 0\n print(k)\n for el in res:\n s += it[el][1]\n print(k, s)\n","sub_path":"optimized_knapsack.py","file_name":"optimized_knapsack.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"163847613","text":"\"\"\"\nAuthor: \nDate: \nClass:\nSection Leader: \n\nDescription:\nThis program uses turtle graphics to draw some polygons.\n\"\"\"\n\nimport turtle\n\ndef polygon(a_turtle, side_number, side_length):\n \"\"\"Draw a regular polygon of the given number of sides and given size with the given turtle.\"\"\"\n for i in range(side_number):\n a_turtle.forward(side_length)\n a_turtle.left(360/side_number)\n return None\n\ndef main():\n num = int(input(\"Enter the number of polygons you'd like to see: \"))\n for i in range(num):\n side_number = int(input(\"Enter the number of sides: \"))\n color = input(\"Enter the color: \")\n side_length = int(input(\"Enter the side length for your polygon: \"))\n a_turtle = turtle.Turtle()\n a_turtle.pencolor(color)\n a_turtle.speed(0)\n a_turtle.pensize(5)\n polygon(a_turtle, side_number, side_length)\n\n input('Press enter to end.') # keeps the turtle graphics window open\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n\n","sub_path":"HW_3/shapechooser.py","file_name":"shapechooser.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"117611704","text":"#! /usr/bin/env python\n\n\"\"\"\n A test program completely separate from main chronostar for astr3005,\n in order to test out the performance of swig and suitability of\n the code to find overlap in a simple test.\n\"\"\"\n\nimport sys\nsys.path.insert(0,'..')\nimport time\nimport argparse\n\nif sys.version[0] == '2':\n timer = time.clock\nelif sys.version[0] == '3':\n timer = time.perf_counter\n\nimport numpy as np\nimport chronostar._overlap as overlap\nfrom chronostar.component import SphereComponent\nfrom chronostar.traceorbit import trace_cartesian_orbit, trace_epicyclic_orbit\n\ndef timings(comp, noverlaps=10000):\n \"\"\"\n Executes each function a fixed number of times, timing for how\n long it takes.\n \"\"\"\n comp.trace_orbit_func = trace_cartesian_orbit\n\n galpystart = timer()\n for i in range(noverlaps):\n comp.get_currentday_projection()\n comp.update_attribute({'age':comp.get_age()+1.e-10})\n\n galpy_time = timer() - galpystart\n print(\"GALPY\")\n print(\"Time: %.5f s\"%galpy_time)\n print(\"Time per projection: %.5f micros\"%(galpy_time/nprojections * 1e6))\n\n comp.trace_orbit_func = trace_epicyclic_orbit\n epicycstart = timer()\n for i in range(noverlaps):\n comp.get_currentday_projection()\n comp.update_attribute({'age':comp.get_age()+1.e-10})\n epicyctime = timer() - epicycstart\n print(\"EPICYCLIC\")\n print(\"Time: \" + str(epicyctime))\n print(\"Time per projection: %.3f micros\"%(epicyctime/nprojections * 1e6))\n\n\n# ------------- MAIN PROGRAM -----------------------\nif __name__ == '__main__':\n\n print(\"___ Testing swig module ___\")\n #Parsing arguments\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument('-o', '--over', dest='o', default=10000,\n help='number of overlaps, def: 10000')\n # parser.add_argument('-b', '--batch', dest='b', default=10000,\n # help='batch size, must be <= and factor of noverlaps, def: 10000')\n args = parser.parse_args()\n\n nprojections = int(args.o)\n\n pars = np.hstack((np.zeros(6),[10.,5,100]))\n my_comp = SphereComponent(pars)\n\n print(\"Testing timings\")\n print(\"# of projections: {}\".format(nprojections))\n timings(my_comp, nprojections)\n\n\n","sub_path":"benchmarks/bm_orbital_methods.py","file_name":"bm_orbital_methods.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"447613394","text":"import vasp\nimport json\nimport time\na_users = {'jake':\n {'name':'Jake Tarnow',\n 'address':'42 Significance Pl, San Jose CA 95050',\n 'account':'J1111111111'},\n 'alice':\n {\"name\":\"Alice Lastnamersson\",\n \"address\":\"1234 Road Rd, City XY 01234\",\n \"account\":\"A0123456789\"},\n 'bob':\n {\"name\":\"Bob McSurname\",\n \"address\":\"4321 Shellcorp Ave, Town YZ 54321\",\n \"account\":\"B9876543210\"},\n}\n\nb_users = {'jake':\n {'name':'Jake Tarnow',\n 'address':'42 Significance Pl, San Jose CA 95050',\n 'account':'J1111111111'},\n 'alice':\n {\"name\":\"lice Lastnamersson\",\n \"address\":\"234 Road Rd, City XY 01234\",\n \"account\":\"0123456789\"},\n 'bob':\n {\"name\":\"ob McSurname\",\n \"address\":\"321 Shellcorp Ave, Town YZ 54321\",\n \"account\":\"9876543210\"},\n}\n\nprint(\"Example VASP PII Exchange between alice(sender) and bob(receiver)\")\ninput()\nprint(\"Initializing VASP A as sending VASP\")\nsender = vasp.VASPServer(\"A\", users=a_users)\nprint(\"Initializing VASP B as receiving VASP\")\nreceiver = vasp.VASPServer(\"B\", users=b_users)\n\ninput()\n\nprint(\"VASP A bit committing alice's PII on VASP B\")\nrec_result = json.loads(receiver.bit_commit(\"alice\", rcv=True))\nrec_hash = rec_result['hash']\nprint(\"Received hash of alice's PII from VASP B \" + rec_hash)\n\nprint(\"Saving VASP B's hash of alice's PII on VASP A\")\nsender.save_hash(\"alice\", rec_hash)\ninput()\n\nprint(\"VASP B bit committing bob's PII on VASP A\")\nsend_result = json.loads(sender.bit_commit(\"bob\"))\nsend_hash = send_result['hash']\nprint(\"Received hash of bob's PII from VASP A \" + send_hash)\n\nprint(\"Saving VASP A's hash of alice's PII on VASP B\")\nreceiver.save_hash(\"bob\", send_hash)\ninput()\n\nprint(\"Now that hashes have been exchanged, salts can be exchanged\")\nrec_salt = json.loads(receiver.reveal_salt(\"alice\"))\nsend_salt = json.loads(sender.reveal_salt(\"bob\"))\ninput()\n\nprint(\"Confirmation by VASP A of bob's PII\")\nsend_confirm = sender.confirm(\"bob\", send_salt['salt'])\nprint(send_confirm)\nprint(\"Confirmation by VASP B of alice's PII\")\nrec_confirm = receiver.confirm(\"alice\", rec_salt['salt'])\nprint(rec_confirm)\n","sub_path":"neg_demo.py","file_name":"neg_demo.py","file_ext":"py","file_size_in_byte":2290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"321521379","text":"from src.Stack import Stack2\n\n\ndef calc(x, y, op):\n \"\"\"\n Returns the basic calculation result\n on x and y for the given operator.\n\n Complexity: O(1)\n \"\"\"\n if op == \"+\":\n return y + x\n elif op == \"-\":\n return y - x\n elif op == \"*\":\n return y * x\n elif op == \"/\":\n return y / x\n\n\ndef evaluate(expression):\n \"\"\"\n Evaluates the given math expression.\n\n Complexity: O(n), where n is the number of characters\n \"\"\"\n operands = Stack2.Stack()\n operators = Stack2.Stack()\n\n for i in expression:\n if i == \"(\" or i == \" \":\n pass\n elif i == \")\":\n op_to_use = operators.pop()\n x, y = operands.pop(), operands.pop()\n operands.push(calc(x, y, op_to_use))\n else:\n if i == \"+\" or i == \"-\" or i == \"*\" or i == \"/\":\n operators.push(i)\n elif float(i):\n operands.push(float(i))\n if operands.num_items > 1:\n op_to_use = operators.pop()\n x, y = operands.pop(), operands.pop()\n operands.push(calc(x, y, op_to_use))\n return operands.pop()","sub_path":"src/Stack/Dijkstra_2_Stack_Calculator.py","file_name":"Dijkstra_2_Stack_Calculator.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"571428301","text":"# coding: UTF-8\n\nimport csv\nimport numpy as np \nimport math\nimport statistics\nimport copy\n\n'''\n csvファイルへの書き込み\n'''\ndef write_csv(data, filename):\n header = []\n \n for dimention in range(1, len(data[0])):\n header.append('次元%i' % (dimention))\n header.append('平均')\n \n with open(filename + '.csv', 'w') as csv_file:\n writer = csv.writer(csv_file)\n writer.writerow(header)\n for row in data:\n writer.writerow(row)\n\n'''\n +1か-1をそれぞれ1/2の確率で出力する\n'''\ndef noise():\n return 1 if np.random.rand() >= 0.5 else -1\n\n'''\n ランダムベクトルの生成\n 要素は全て[-1, 1]の範囲\n'''\ndef make_random_vector(num_dimentions):\n random_vector = []\n for dimention in range(num_dimentions):\n random_vector.append(np.random.rand() * noise())\n\n return random_vector\n\n'''\n ランダム行列の生成\n 要素は全て[-1, 1]の範囲\n'''\ndef make_random_matrix(num_elements, num_dimentions):\n random_matrix = []\n for element in range(num_elements):\n random_matrix.append(make_random_vector(num_dimentions))\n return random_matrix\n\n'''\n ユークリッド距離\n'''\ndef euclid_distance(vector1, vector2):\n distance = 0\n for index in range(len(vector1)):\n distance += (vector1[index] - vector2[index]) * (vector1[index] - vector2[index])\n \n return math.sqrt(distance)\n\n'''\n 各要素と他の要素との距離の行列を返す\n'''\ndef get_distance_matrix(data):\n distance_matrix = []\n\n for vector1 in data:\n distance_vector = []\n for vector2 in data:\n distance_vector.append(euclid_distance(vector1, vector2))\n distance_matrix.append(distance_vector)\n\n return distance_matrix\n\n'''\n 各ベクトルのユークリッド距離を取って各ベクトルと他のベクトルとの距離の平均を出し\n 最小のもののインデックスを返す。\n 各ベクトルの平均と全体の平均と分散も出す。\n'''\ndef each_distance(distance_matrix):\n all_vecotors_mean = []\n for vector in distance_matrix:\n all_vecotors_mean.append(sum(vector) / len(vector))\n \n minimum = all_vecotors_mean[0]\n index = 0\n for current_index in range(1, len(distance_matrix)):\n if minimum > all_vecotors_mean[current_index]:\n minimum = all_vecotors_mean[current_index]\n index = current_index\n\n all_means = statistics.mean(all_vecotors_mean)\n # all_variance = statistics.variance(all_vecotors_mean)\n all_vecotors_mean.append(all_means)\n # all_vecotors_mean.append(all_variance)\n\n return index, all_vecotors_mean\n\n'''\n 指定したindexの要素を入れ替える\n'''\ndef replace_element(matrix, index, new_vector):\n matrix[index] = new_vector\n return matrix\n\n'''\n 指定したindexの要素と他の要素とのユークリッド距離を更新する\n'''\ndef update_distance(data, distance_matrix, index):\n new_distances_matrix = copy.deepcopy(distance_matrix)\n # 横成分の更新\n for vector in range(len(data)):\n distance = euclid_distance(data[index], data[vector])\n new_distances_matrix[index][vector] = distance\n\n # 縦成分の更新\n for vector in range(len(data)):\n new_distances_matrix[vector][index] = euclid_distance(data[vector], data[index])\n \n return new_distances_matrix\n\n'''\n ユークリッド距離の履歴のcsvファイル用のヘッダーを返す\n'''\ndef header(num_elements):\n header = []\n header.append('試行回数')\n for element in range(num_elements):\n header.append('要素%i' % (element))\n \n header.append('全体の平均')\n header.append('全体の分散')\n return header\n\n'''\n それぞれの要素にランダムになるようにリストの末尾に順位をつける\n'''\ndef add_ranking(random_matrix):\n rank = []\n for index in range(len(random_matrix)):\n rank.append(index + 1)\n \n for swap in range(len(random_matrix)):\n element_index1 = np.random.randint(0, len(random_matrix) - 1)\n element_index2 = np.random.randint(0, len(random_matrix) - 1)\n rank[element_index1], rank[element_index2] = rank[element_index2], rank[element_index1]\n\n for index in range(len(random_matrix)):\n random_matrix[index].append(rank[index])\n\n return random_matrix\n\n'''\n Main\n'''\n# 個体数\nnum_elements = 100\n# 次元数\nnum_dimentions = 100\n# ユークリッド距離の小さい要素を連続で入れ替えなかった回数\nnum_noreplace = 0\n\n\n\n# ユークリッド距離の履歴\neuclid_history = []\n\n# [-1, 1]の範囲でランダム行列を作成\nrandom_matrix = make_random_matrix(num_elements, num_dimentions)\n \n# ユークリッド距離の行列\neuclid_matrix = get_distance_matrix(random_matrix)\n\nindex, distances = each_distance(euclid_matrix)\nfor num in range(1, 2):\n while num_noreplace < 1000:\n print(num_noreplace)\n temp = euclid_matrix\n # ユークリッド距離の平均のリストと最も小さい距離のインデックスの取得\n index, distances = each_distance(euclid_matrix)\n # ユークリッド距離に関するリストの更新\n euclid_history.append(distances)\n # 差し替え候補のベクトルを作成\n new_vector = make_random_vector(num_dimentions)\n # 仮に差し替えた後の個体群行列の作成\n temp_matrix = replace_element(random_matrix, index, new_vector)\n # 仮に差し替えた行列のユークリッド距離の行列を取得\n temp_euclid_matrix = update_distance(temp_matrix, euclid_matrix, index)\n # 仮に差し替えた行列のユークリッド距離の平均のリストと最も小さい距離のインデックスの取得\n new_index, new_distances = each_distance(temp_euclid_matrix)\n\n # 差し替えた方が距離が大きい場合は個体群行列を差し替えて更新し、num_noreplaceをリセットする\n if distances[100] < new_distances[100]:\n random_matrix = temp_matrix\n num_noreplace = 0\n # ユークリッド距離行列を更新する\n euclid_matrix = temp_euclid_matrix\n # 差し替えない方が良い場合、個体群行列を更新せずnum_noreplaceを+1する\n else:\n num_noreplace += 1\n '''\n # 重み付け(解空間用)\n for row in random_matrix:\n row.append(np.random.rand() * 20)\n '''\n\n # それぞれの個体にランダムでランキングを割り振る\n # add_ranking(random_matrix)\n\n # 書き込むファイル\n filename = 'csv_files/mock_initial_individuals'\n\n # 結果をcsvに書き込む\n write_csv(random_matrix, filename)\n\n # ユークリッド距離の履歴をcsvファイルに書き込む\n write_csv(euclid_history, 'csv_files/euclid_history')\n","sub_path":"pre_experiment/search_alpha/random_matrix.py","file_name":"random_matrix.py","file_ext":"py","file_size_in_byte":6943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"598854758","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Aug 31 12:43:07 2019\r\n\r\n@author: Administrator\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport math\r\nfrom datetime import datetime\r\nfrom sklearn import preprocessing\r\n\r\n#1.变量预处理\r\n#将描述变量存储到cont_vars 这个list中去\r\n\r\nclass feature_preprocessing(object):\r\n def __init__(self,data,y):\r\n self.n_df=data.shape[0]\r\n self.n1_df=data[y].sum()\r\n self.n0_df=self.n_df-self.n1_df\r\n print(\"共有{row}行{col}列数据,{n1}个坏客户,{n0}个好客户\".format(\r\n row=data.shpae[0],\r\n col=data.shape[1],\r\n n1=self.n1_df,\r\n n0=self.n0_df\r\n ))\r\n self.cols=data.columns.to_list()\r\n self.cols.remove(y)\r\n del self.cols[0]\r\n self.num_vars_valid=[]\r\n self.char_vars_valid=[]\r\n self.num_vars_novalid=[]\r\n self.char_vars_novalid=[]\r\n self.null_count=[]\r\n self.sim_count=[]\r\n print(\"\\n单一变量和缺失值分析:\")\r\n for col in self.cols:\r\n if data[col].dtype!=\"object\":\r\n missing=self.n_df-np.count_nonzero(data[col].isnull().values)\r\n mis_perc=100-float(missing)/self.n_df*100\r\n self.null_count.append([col,mis_perc])\r\n value_cnt=data[col].value_counts()\r\n sim_perc=float(max(value_cnt,default=100))/self.n_df*100\r\n self.sim_count.append([col,sim_perc])\r\n if mis_perc<99 and sim_perc<99:self.num_vars_valid.append(col)\r\n else:\r\n print(\"{col}的缺失值比例是{miss}%,单一值比例是{simple}%\".format(col=col,miss=mis_perc,simple=sim_perc))\r\n self.num_vars_novalid.append(col)\r\n \r\n print (\"\\n连续有效变量有\\n:\")\r\n print(len(self.num_vars_valid))\r\n print(self.num_vars_valid)\r\n print (\"\\n连续无效变量有\\n:\")\r\n print(len(self.num_vars_novalid))\r\n print(self.num_vars_novalid)\r\n for col in self.cols:\r\n if data[col].dtype==\"object\":\r\n missing=self.n_df-np.count_nonzero(data[col].isnull().values)\r\n mis_perc=100-float(missing)/self.n_df*100\r\n self.null_count.append([col,mis_perc])\r\n value_cnt=data[col].value_counts()\r\n sim_perc=float(max(value_cnt,default=100))/self.n_df*100\r\n self.sim_count.append([col,sim_perc]) \r\n if mis_perc<99 and sim_perc<99:self.char_vars_valid.append(col)\r\n else:\r\n print(\"{col}的缺失值比例是{miss}%,单一值比例是{simple}%\".format(col=col,miss=mis_perc,simple=sim_perc))\r\n self.char_vars_novalid.append(col)\r\n print (\"\\n分类有效变量有\\n:\")\r\n print(len(self.char_vars_valid))\r\n print(self.char_vars_valid)\r\n print (\"\\n分类无效变量有\\n:\")\r\n print(len(self.char_vars_novalid))\r\n print(self.char_vars_novalid)\r\n print(self.null_count)\r\n print(self.sim_count)\r\n data.drop(self.num_vars_novalid,axis=1,inplace=True)\r\n data.drop(self.char_vars_novalid,axis=1,inplace=True)\r\n #获取有效的数值变量和文本变量\r\n def get_vars(self):\r\n return self.num_vars_valid,self.char_vars_valid\r\n","sub_path":"auto/cont_feature_discretization.py","file_name":"cont_feature_discretization.py","file_ext":"py","file_size_in_byte":3377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"116512926","text":"#!/usr/bin/env python \n# -*- coding: utf-8 -*-\n\"\"\"\nProblem 3. \nThe prime factors of 13195 are 5, 7, 13 and 29.\nWhat is the largest prime factor of the number 600851475143 ?\"\"\"\n\nimport math\nall_prime = [2, 3, 5 ]\n\ndef isPrime( num ):\n\tmax_try = math.sqrt( num ) + 1\n\tfor prime in ( v for v in all_prime if v < max_try ):\n\t\tif num % prime == 0:\n\t\t\treturn False\n\treturn True\n\ndef genPrime( num ):\n\tfor i in xrange( all_prime[-1], int(math.sqrt(num)) + 1 ):\n\t\tif i is all_prime[-1]:\n\t\t\tcontinue\n\n\t\tif isPrime( i ):\n\t\t\tall_prime.append( i )\n\ndef getForceLargestPrimeFactor( num ):\n\tgenPrime( num )\n\n\tfor i in xrange( len(all_prime) - 1, -1, -1):\n\t\tprime = all_prime[i]\n\t\tif num % prime == 0:\n\t\t\treturn prime\n\n\n#print getForceLargestPrimeFactor( 600851475143 )\n\n\ndef getFermatFactor( num ):\n\ta = math.ceil( math.sqrt( num ) )\n\tb = math.sqrt( a * a - num )\n\n\twhile b - int( b ) > 0.000000001:\n\t\ta += 1\n\t\tb = math.sqrt( a * a - num )\n\n\treturn a + b, a - b\n\n\n#print getFermatFactor( 13195 )\n\ndef getMaxPrime( num ):\n\td = 2\n\n\twhile num != d:\n\t\twhile num % d == 0:\n\t\t\tnum /= d\n\n\t\td += 1\n\treturn num\n\nDEFAULT_ARG = 600851475143\n\ndef solve( num ):\n return getMaxPrime( num )\n","sub_path":"solutions/p3.py","file_name":"p3.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"102670564","text":"import json\n\ndef detect(det):\n\n buffer = det['buffers']\n response = []\n expected_sections=['.text','.data','.rsrc']\n section_name=''\n\n for file in buffer:\n entryPoint=file['oh']['ep']\n sectionCount=1\n NumberOfSections=file['fh']['ns']\n md5=file['md5']\n print(NumberOfSections)\n for sec in file['sec']:\n virtualAdress=sec['va']\n sizeOfRawData=sec['s']\n\n if(entryPoint< virtualAdress+sizeOfRawData):\n section_name=sec['n']\n break\n else:\n sectionCount=sectionCount+1\n\n if sectionCount==int(NumberOfSections, 16) and section_name not in expected_sections:\n status='malware'\n else:\n\n status='clean'\n\n item = {'md5': md5, 'status': status}\n response.append(item)\n\n return response\n\n\n","sub_path":"server/workers/scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"91235914","text":"\nimport sys\nsys.path.append(\"../\")\n\nimport pyskynet\nimport pyskynet.cluster as cluster\nimport pyskynet.foreign as foreign\nimport numpy as np\nimport time\n\n@foreign.dispatch(\"dosth\")\ndef dosth(a):\n print(a)\n return a\n\npyskynet.start()\n\n\ncluster.open(8080)\n\n\n\na1 = np.arange(100)\nt1 = time.time()\na2, = cluster.call(\"127.0.0.1:8080\", \".python\", \"dosth\", a1)\nt2 = time.time()\nprint(t2-t1)\n\nt1 = time.time()\na2, = cluster.call(\"127.0.0.1:8080\", \".python\", \"dosth\", a1)\nt2 = time.time()\nprint(t2-t1)\n\npyskynet.join()\n","sub_path":"test/test_cluster.py","file_name":"test_cluster.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"255647464","text":"import pandas\nimport Quandl\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\nimport numpy\n\nnow = datetime.now()\ndef last_n_rows(n, df, start=\"\"):\n\t\"\"\"Returns the last n rows of a Pandas dataframe object.\n\n\tKeyword arguments:\n\tn \t\t-- the number of rows to be returned. If n is greater than the total number of rows in the datafrma, then the method will return the entire dataframe\n\tstart \t-- the start date of the rows to be returned. Defaults to current date\n\t\"\"\"\n\n\tif start == \"\":\n\t\tstart = now\n\tstart = date_to_string(start)\n\tstart_index = df.index.searchsorted(start)\n\tsliced_df = df.iloc[-n:start_index, :]\n\treturn sliced_df\ndef last_n_periods(dataframe, n, period_type, start_date=\"\"):\n\t\"\"\"Returns a dataframe whose index is n periods in the past from the start date\n\n\tKeyword arguments:\n\tdataframe -- the dataframe to be sliced\n\tn -- the number of periods to go back\n\tstart_date -- the start date of the dataframe. Defaults to current date\n\tperiod_type -- valid choices are \"years\", \"days\", \"monhts\", and \"weeks\"\n\t\"\"\"\n\tif start_date == \"\":\n\t\tstart_date = now\n\tend_date = last_n_date(n, start_date , period_type)\n\tdataframe = dataframe[date_to_string(end_date):start_date]\n\treturn dataframe\ndef last_n_date(n, period_type, start_date=\"\"):\n\t\"\"\"Returns a datetime that is n periods from the start date\n\n\tKeyword arguments:\n\tn -- the number of periods to go back\n\tperiod_type -- valid choices are \"years\", \"days\", \"months\", and \"weeks\"\n\tstart_date -- the start date of the dataframe. Defaults to current date\n\t\"\"\"\n\tif start_date == \"\":\n\t\tstart_date = now\n\t\t\n\tstart_date = string_to_date(start_date)\n\tif period_type == \"years\":\n\t\tend_date = start_date - relativedelta(years=n)\n\tif period_type == \"days\":\n\t\tend_date = start_date - relativedelta(days=n)\n\tif period_type == \"months\":\n\t\tend_date = start_date - relativedelta(months=n)\n\tif period_type == \"weeks\":\n\t\tend_date == start_date - relativedelta(days=7)\n\treturn end_date\n\ndef rows_between(df, start_date, end_date):\n\t\"\"\"Returns a dataframe whose index is between (and inclusive) the start and end dates entered.\n\n\tKeyword arguments:\n\tstar_date \t-- either a datetime or a string in the following format \"yyyy-mm-dd\"\n\tend_date \t-- either a datetime or a string in the following format \"yyyy-mm-dd\"\n\t\"\"\"\n\n\tstart_date = date_to_string(start_date)\n\tend_date = date_to_string(end_date)\n\tif start_date not in df.index:\n\t\tstart_date = df.head(1).index[0]\n\tif end_date not in df.index:\n\t\tend_date = df.tail(1).index[0]\n\treturn df.loc[start_date : end_date, :]\ndef year_to_date():\n\t\"\"\"Returns a dataframe whose index ranges from last trade date of last year to today\"\"\"\n\n\treturn rows_between(last_year_trade_date(), now)\ndef last_year_trade_date(dataframe, year=\"\"):\n\t\"\"\"Returns a datetime.datetime object of the last trade date of last year (or specifiec year)\"\"\"\n\tlast_year=None\n\tif year == \"\":\n\t\tlast_year = (now - relativedelta(years=1)).year\n\telse:\n\t\tthis_year_datetime = datetime(year, 1, 1)\n\t\tlast_year = (this_year_datetime - relativedelta(years=1)).year\n\tlast_year_trade_date = datetime(last_year,12 ,31)\n\twhile(last_year_trade_date not in dataframe.index):\n\t\tlast_year_trade_date = (last_year_trade_date - relativedelta(days=1))\n\treturn last_year_trade_date\n\ndef date_to_string(date_to_string):\n\t\"\"\"Returns a string representation of datetime formatted \"yyyy-mm-dd\"\"\"\n\n\tif type(date_to_string) is datetime:\n\t\treturn date_to_string.strftime(\"%Y-%m-%d\")\n\treturn date_to_string\ndef string_to_date(string_to_date):\n\tif type(string_to_date) is str:\n\t\treturn datetime.strptime(string_to_date,\"%Y-%m-%d\")\n\treturn string_to_date\n\n\n\n","sub_path":"Prometheus/CherryPy/test/dataframe_utils.py","file_name":"dataframe_utils.py","file_ext":"py","file_size_in_byte":3609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"430696228","text":"# !/usr/bin/env python3\n# @Time : 2020-02-14\n# @Author : caicai\n# @File : es_export.py\nfrom elasticsearch import helpers\nfrom elasticsearch import Elasticsearch\nimport base64\nimport copy\nimport time\n\n\nclass plugin():\n def __init__(self, dictdata):\n self.dictdata = dictdata\n self.es = Elasticsearch()\n\n def run(self):\n dictdata=self.dictdata\n # 把请求体和响应体 base64解码,便于搜索\n dictdata[\"request\"][\"raw\"] = base64.b64decode(self.dictdata.get(\"request\").get(\"raw\")).decode(\"utf-8\",\n errors=\"ignore\")\n dictdata[\"response\"][\"raw\"] = base64.b64decode(self.dictdata.get(\"response\").get(\"raw\")).decode(\"utf-8\",\n errors=\"ignore\")\n if \"others\" in dictdata.keys():\n del dictdata[\"others\"]\n if \"filter\" in dictdata.keys():\n del dictdata[\"filter\"]\n dictdata[\"ts\"]=int(time.time())\n actions = []\n action = {\n \"_index\": \"burpdata\",\n \"_type\": \"doc\",\n \"_source\": dictdata\n }\n actions.append(action)\n helpers.bulk(self.es, actions)\n","sub_path":"myscan/plugins/es_export.py","file_name":"es_export.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"497159259","text":"import numpy as np\nimport torch\nfrom torch import nn, optim\nfrom torch.version import cuda\n\nfrom gcommand_loader import GCommandLoader\n\n\ndef loadData(path, size):\n x1 = torch.utils.data.DataLoader(\n path, batch_size=size, shuffle=True,\n num_workers=20, pin_memory=True, sampler=None)\n return x1\n\n\ndef getDictionnary():\n labels = dict()\n labels.__setitem__(\"bed\", 0), labels.__setitem__(\"bird\", 1), labels.__setitem__(\"cat\", 2), labels.__setitem__(\n \"dog\", 3),labels.__setitem__(\"down\", 4),\n labels.__setitem__(\"eight\", 5), labels.__setitem__(\"five\", 6), labels.__setitem__(\"four\", 7), labels.__setitem__(\n \"go\", 8),\n labels.__setitem__(\"happy\", 9), labels.__setitem__(\"house\", 10), labels.__setitem__(\"left\", 11), labels.__setitem__(\n \"marvin\", 12),\n labels.__setitem__(\"nine\", 13), labels.__setitem__(\"no\", 14), labels.__setitem__(\"off\", 15), labels.__setitem__(\"on\",\n 16), labels.__setitem__(\n \"one\", 17)\n labels.__setitem__(\"right\", 18), labels.__setitem__(\"seven\", 19), labels.__setitem__(\"sheila\",\n 20), labels.__setitem__(\"six\",\n 21), labels.__setitem__(\n \"stop\", 22),\n labels.__setitem__(\"three\", 23), labels.__setitem__(\"tree\", 24), labels.__setitem__(\"two\", 25), labels.__setitem__(\n \"up\", 26), labels.__setitem__(\"wow\", 27),\n labels.__setitem__(\"yes\", 28), labels.__setitem__(\"zero\", 29)\n return labels\n\n\nclass ConvNet(nn.Module):\n\n def __init__(self):\n super(ConvNet, self).__init__()\n self.layer1 = nn.Sequential(\n nn.Conv2d(1, 30, kernel_size=4, stride=1, padding=1),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2))\n #self.layer2 = nn.Sequential(\n #nn.Conv2d(32, 64, kernel_size=5, stride=1, padding=2),\n #nn.ReLU(),\n #nn.MaxPool2d(kernel_size=2, stride=2))\n self.drop_out = nn.Dropout()\n self.fc1 = nn.Linear(80 * 50 * 30, 1000)\n self.fc2 = nn.Linear(1000, 30)\n\n def forward(self, x):\n out = self.layer1(x)\n #out = self.layer2(out)\n out = out.reshape(out.size(0), -1)\n out = self.drop_out(out)\n out = self.fc1(out)\n out = self.fc2(out)\n return out\n\n def validation_model(self, set_validation):\n self.eval()\n with torch.no_grad():\n correct = 0\n total = 0\n for examples, labels in set_validation:\n outputs = self(examples)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n print(\"accuracy : {} %\".format((correct/total)*100))\n\ndef main():\n\n dataSetTest = GCommandLoader(\"/home/herold55/PycharmProjects/ex4ML/Test\")\n dataSetTrain = GCommandLoader(\"/home/herold55/PycharmProjects/ex4ML/Train2\")\n dataSetValid = GCommandLoader(\"/home/herold55/PycharmProjects/ex4ML/Valid\")\n print(len(dataSetTest))\n print(len(dataSetTrain))\n print(len(dataSetValid))\n x_test = loadData(dataSetTest, 100)\n x_train = loadData(dataSetTrain, 100)\n x_valid = loadData(dataSetValid, 100)\n epochs = 5\n learning_rate = np.exp(-23)\n model = ConvNet()\n # Loss and optimizer\n criterion = nn.NLLLoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n # Train the model\n total_step = len(x_train)\n loss_list = []\n acc_list = []\n for epoch in range(epochs):\n for (images, labels) in x_train:\n # Run the forward pass\n outputs = model(images)\n loss = criterion(outputs, labels)\n loss_list.append(loss.item())\n\n # Backprop and perform Adam optimisation\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # Track the accuracy\n total = labels.size(0)\n _, predicted = torch.max(outputs.data, 1)\n correct = (predicted == labels).sum().item()\n acc_list.append(correct / total)\n\n #if (True):\n # print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}, Accuracy: {:.2f}%'\n # .format(epoch + 1, epochs, total_step, loss.item(),\n # (correct / total) * 100))\n model.validation_model(x_valid)\n\nmain()\n","sub_path":"Pytorch Model/Classifier.py","file_name":"Classifier.py","file_ext":"py","file_size_in_byte":4594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"144133045","text":"\"\"\"\nThis module demonstrates the ACCUMULATOR pattern in three classic forms:\n SUMMING: total = total + number\n COUNTING: count = count + 1\n IN GRAPHICS: x = x + pixels\n\nAuthors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher, Mark Hays,\n Aaron Wilkin, their colleagues, and Ben Hawkins.\n\"\"\" # Done: 1. PUT YOUR NAME IN THE ABOVE LINE.\n\n###############################################################################\n#\n# Done: 2.\n# RUN this program, then READ its code.\n# Then answer the following, GETTING HELP AS NEED! (Ask questions!!!)\n# Write your answers in any reasonable way (your choice).\n#\n# For the first several questions, some students find the following\n# picture helpful. (Your instructor may explain it in whole-group.)\n#\n# 0 1 2 3 4 ... r-1 r r+1 r+2 r+3 ... s\n# |..... r numbers .....|\n# |................ s+1 numbers ..................|\n# Hence: |... (s+1)-r numbers ...|\n#\n# a. If you want a loop that runs r times,\n# which of the following three choices would you use?\n#\n# for k in range(r - 1):\n# for k in range(r): <-- This one\n# for k in range(r + 1):\n#\n# b. If you want a loop that runs from 0 to s, inclusive,\n# what expression would you use in the _____ below?\n#\n# for k in range(s+1):\n#\n# c. If you want a loop that runs from r to s, inclusive, assuming s >= r,\n# what expression would you use in the ______below?\n#\n# for k in range(s-r+1):\n#\n# d. If you want a loop that runs from (r + 4) to (s - 10),\n# including the (r + 4) but not including the (s - 10),\n# what expression would you use in the _____ below?\n#\n# for k in range(s+r-6):\n#\n# e. The following code snippet attempts to return the number\n# of integers from r to s, inclusive, whose cosines are positive.\n# It has at least 5 distinct errors (one per line). What are they?\n#\n# for k in range(r - s):\n# count = 0\n# if math.cos(r) > 0:\n# count = 1\n# return count\n#\n# The range of the for loop is wrong (should be s-r+1), the count is within the for loop so it'll\n# constantly be reset,the math.cos uses r instead of k, it then sets count equal to 1 instead of adding\n# one, and then it returns everytime the loop runs, which is pointless and can be kept outside it.\n#\n# f. The code in the \"graphics accumulation\" example below includes:\n# for _ in range(n):\n# What does the _ (underscore) mean?\n#\n# Which iteration of the loop it is currently on when the index variable doesn't matter for the loop.\n#\n# g. The code in the \"graphics accumulation\" example below includes:\n#\n# x = starting_point.x\n# for _ in range(n):\n# center = rg.Point(x, y)\n# circle = rg.Circle(point, radius)\n# circle.attach_to(window)\n# x = x + diameter\n#\n# If you want the row-of-circles that the above creates,\n# one of the following two attempts is a CORRECT attempt\n# (i.e., is equivalent in its functionality to the above)\n# and one is WRONG. Which is the WRONG one?\n#\n# x = starting_point.x\n# for k in range(n):\n# center = rg.Point(x + (k * diameter), y)\n# circle = rg.Circle(point, radius)\n# circle.attach_to(window)\n#\n# x = starting_point.x\n# for k in range(n):\n# center = rg.Point(x + (k * diameter), y)\n# circle = rg.Circle(point, radius)\n# circle.attach_to(window)\n# x = x + (2 * radius)\n#\n# The second is correct\n#\n#\n###############################################################################\n# *** MAKE SURE YOU UNDERSTAND THE 3 ACCUMULATOR PATTERNS ***\n# *** shown in this module: SUMMING, COUNTING, and IN GRAPHICS ***\n###############################################################################\n#\n# When you are confident that you understand the 3 accumulator patterns\n# and have correct answers to the above questions (ASK QUESTIONS AS NEEDED!),\n# check your work by asking a student assistant to look at your answers.\n#\n# After checking your work (making corrections as needed),\n# change the above _TODO_ to DONE.\n#\n###############################################################################\n\nimport rosegraphics as rg\nimport math\n\n\ndef main():\n \"\"\" Calls the TEST functions in this module. \"\"\"\n run_test_summing_example()\n run_test_counting_example()\n run_test_draw_row_of_circles()\n\n\ndef run_test_summing_example():\n \"\"\" Tests the summing_example function. \"\"\"\n print()\n print('--------------------------------------------------')\n print('Testing the summing_example function:')\n print('--------------------------------------------------')\n\n # Test 1:\n expected = 100\n answer = summing_example(4)\n print('Test 1 expected:', expected)\n print(' actual: ', answer)\n\n # Test 2:\n expected = 44100\n answer = summing_example(20)\n print('Test 2 expected:', expected)\n print(' actual: ', answer)\n\n # Test 3:\n expected = 0\n answer = summing_example(0)\n print('Test 3 expected:', expected)\n print(' actual: ', answer)\n\n\ndef summing_example(n):\n \"\"\"\n What comes in: The sole argument is a non-negative integer n.\n What goes out: Returns the sum\n (1 cubed) + (2 cubed) + (3 cubed) + ... + (n cubed).\n Side effects: None.\n Examples:\n -- If the integer is 4,\n this function returns (1 + 8 + 27 + 64), which is 100.\n -- If the integer is 20, this function returns 44,100.\n \"\"\"\n total = 0 # Initialize to 0 BEFORE the loop\n for k in range(n): # Loop\n total = total + ((k + 1) ** 3) # Accumulate INSIDE the loop.\n\n return total # Return the result AFTER the loop\n\n\ndef run_test_counting_example():\n \"\"\" Tests the counting_example function. \"\"\"\n print()\n print('--------------------------------------------------')\n print('Testing the counting_example function:')\n print('--------------------------------------------------')\n\n # Test 1:\n expected = 2\n answer = counting_example(2)\n print('Test 1 expected:', expected)\n print(' actual: ', answer)\n\n # Test 2:\n expected = 12\n answer = counting_example(20)\n print('Test 2 expected:', expected)\n print(' actual: ', answer)\n\n # Test 3:\n expected = 1\n answer = counting_example(0)\n print('Test 3 expected:', expected)\n print(' actual: ', answer)\n\n\ndef counting_example(n):\n \"\"\"\n What comes in: The sole argument is a non-negative integer n.\n What goes out: Returns the number of integers from 0 to n,\n inclusive, whose cosine is positive.\n Side effects: None.\n Examples:\n -- counting_example(2) returns 2\n since the cosine(0) is 1 (positive)\n and the cosine(1) is about 0.54 (positive)\n and the cosine(2) is about -0.42 (negative)\n\n -- counting_example(20) returns 12\n since the cosines of 0, 1, 5, 6, 7, 11, 12, 13, 14, 18, 19 and 20\n are positive\n\n -- counting_example(0) returns 1\n since the cosine(0) is positive.\n \"\"\"\n count = 0 # Initialize to 0 BEFORE the loop\n for k in range(n + 1): # Loop\n if math.cos(k) > 0: # If the condition holds:\n count = count + 1 # Increment INSIDE the loop.\n\n return count # Return the result AFTER the loop\n\n\ndef run_test_draw_row_of_circles():\n \"\"\" Tests the draw_row_of_circles function. \"\"\"\n print()\n print('--------------------------------------------------')\n print('Testing the draw_row_of_circles function:')\n print(' See the graphics windows that pop up.')\n print('--------------------------------------------------')\n\n # -------------------------------------------------------------------------\n # TWO tests on ONE window.\n # -------------------------------------------------------------------------\n title = 'Tests 1 and 2 of DRAW_ROW_OF_CIRCLES:'\n title = title + ' 7 GREEN circles, 4 BLUE circles!'\n window1 = rg.RoseWindow(500, 250, title)\n\n # Test 1:\n center = rg.Point(50, 50)\n draw_row_of_circles(7, center, 'green', window1)\n\n # Test 2:\n center = rg.Point(100, 150)\n draw_row_of_circles(4, center, 'blue', window1)\n window1.close_on_mouse_click()\n\n # -------------------------------------------------------------------------\n # A third test on ANOTHER window.\n # -------------------------------------------------------------------------\n title = 'Test 3 of DRAW_ROW_OF_CIRCLES: Row of 12 RED circles!'\n window2 = rg.RoseWindow(600, 150, title)\n\n # Test 3:\n center = rg.Point(50, 50)\n draw_row_of_circles(12, center, 'red', window2)\n\n window2.close_on_mouse_click()\n\n\ndef draw_row_of_circles(n, starting_point, color, window):\n \"\"\"\n What comes in: The four arguments are:\n -- A positive integer n.\n -- An rg.Point.\n -- A color appropriate for rosegraphics (e.g. 'red')\n -- An rg.RoseWindow.\n What goes out: Nothing (i.e., None).\n Side effects:\n Draws n rg.Circle objects in a row,\n all on the given rg.RoseWindow, such that:\n -- The first rg.Circle is centered at the given starting_point.\n -- Each rg.Circle just touches the previous one (to its left).\n -- Each rg.Circle has radius 20.\n -- Each rg.Circle is filled with the given color.\n Must ** render ** but ** NOT close ** the rg.RoseWindow.\n\n Type hints:\n :type n: int\n :type starting_point: rg.Point\n :type color: str\n :type window: rg.RoseWindow\n \"\"\"\n # -------------------------------------------------------------------------\n # The example below shows one way to solve problems using\n # HELPER variables (aka AUXILIARY variables)\n # In this approach:\n # 1. You determine all the variables that you need\n # to construct/draw whatever the problem calls for.\n # We call these HELPER variables.\n # 2. You initialize them BEFORE the loop, choosing values that\n # make them just right for constructing and drawing the\n # FIRST object to be drawn, in the FIRST time through the loop.\n # For example, x = starting_point.x in the example below.\n # 3. You determine how many times the loop should run\n # (generally, however many objects you want to draw)\n # and write the FOR statement for the loop.\n # For example, for _ in range(n): in the example below.\n # 4. Inside the loop you write the statements to construct and\n # draw the FIRST object to be drawn, using your helper\n # variables. This is easy because you chose just the right\n # values for those helper variables for this FIRST object.\n # 5. Test: Make sure the FIRST object appears.\n # (It will be redrawn many times, that is OK).\n # 6. Add code at the BOTTOM of the loop that changes the helper\n # variables appropriately for the NEXT time through the loop.\n # For example, x = x + diameter in the example below.\n # 7. Test and fix as needed.\n #\n # Many students (and professionals) find this technique less\n # error-prone that using the loop variable to do all the work.\n # -------------------------------------------------------------------------\n\n radius = 20\n diameter = 2 * radius\n\n x = starting_point.x # Initialize x and y BEFORE the loop. Choose ...\n y = starting_point.y # ... values that make the FIRST object easy to draw.\n\n for _ in range(n): # Loop that does NOT use its index variable\n\n # ---------------------------------------------------------------------\n # Construct the relevant object(s),\n # based on the current x, y and other variables.\n # ---------------------------------------------------------------------\n center = rg.Point(x, y)\n circle = rg.Circle(center, radius)\n circle.fill_color = color\n\n # Attach the object(s) to the window.\n circle.attach_to(window)\n\n # ---------------------------------------------------------------------\n # Increment x (and in other problems, other variables)\n # for the thing(s) to draw in the NEXT iteration of the loop.\n # ---------------------------------------------------------------------\n x = x + diameter\n\n window.render()\n\n\n# -----------------------------------------------------------------------------\n# Calls main to start the ball rolling.\n# -----------------------------------------------------------------------------\nmain()\n","sub_path":"src/m1r_accumulator_examples.py","file_name":"m1r_accumulator_examples.py","file_ext":"py","file_size_in_byte":13120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"382556454","text":"#!/usr/bin/env python\r\n\r\nimport vtk\r\n\r\nx = [(0.5, 0.5, 0.5),\r\n (-0.5, 0.5, 0.5),\r\n (0.5, -0.5, 0.5),\r\n (-0.5, -0.5, 0.5),\r\n (0.5, 0.5, -0.5),\r\n (-0.5, 0.5, -0.5),\r\n (0.5, -0.5, -0.5),\r\n (-0.5, -0.5, -0.5)]\r\n\r\nsquares = [(0, 2, 6, 4),\r\n (4, 5, 1, 0),\r\n (1, 3, 2, 0),\r\n (1, 5, 7, 3),\r\n (2, 3, 7, 6),\r\n (7, 5, 4, 6)]\r\n\r\ntriangles = [(0, 2, 4),\r\n (2, 6, 4),\r\n (4, 5, 0),\r\n (5, 1, 0),\r\n (1, 3, 2),\r\n (1, 2, 0),\r\n (1, 5, 3),\r\n (5, 7, 3),\r\n (2, 3, 6),\r\n (3, 7, 6),\r\n (7, 5, 6),\r\n (5, 4, 6)]\r\n\r\ntriangleStrips = [[0, 1, 2, 3, 6, 7, 4, 5],\r\n [2, 6, 0, 4, 1, 5, 3, 7]]\r\n\r\n\r\ndef writeFile(filename, polydata):\r\n\twriter = vtk.vtkPolyDataWriter()\r\n\twriter.SetFileName(filename)\r\n\twriter.SetInputData(polydata)\r\n\twriter.Write()\r\n\r\n\r\n# Use squares\r\ncube = vtk.vtkPolyData()\r\npoints = vtk.vtkPoints()\r\npolys = vtk.vtkCellArray()\r\nscalars = vtk.vtkFloatArray()\r\n\r\nfor i in range(0, 8):\r\n\tpoints.InsertPoint(i, x[i])\r\n\r\nfor face in squares:\r\n\tpolys.InsertNextCell(4, face)\r\n\r\nfor i in range(0, 8):\r\n\tscalars.InsertTuple1(i, i)\r\n\r\ncube.SetPoints(points)\r\ncube.SetPolys(polys)\r\ncube.GetPointData().SetScalars(scalars)\r\n\r\nwriteFile('data/cubeSquares.vtk', cube)\r\n\r\n# Use triangles\r\npolys = vtk.vtkCellArray()\r\n\r\nfor face in triangles:\r\n\tpolys.InsertNextCell(3, face)\r\n\r\ncube.SetPolys(polys)\r\n\r\nwriteFile('data/cubeTriangles.vtk', cube)\r\n\r\n# Using two triangle strips\r\nstrip = vtk.vtkCellArray()\r\nfor s in triangleStrips:\r\n\tstrip.InsertNextCell(len(s))\r\n\tfor i in s:\r\n\t\tstrip.InsertCellPoint(i)\r\n\r\ncube = vtk.vtkPolyData()\r\ncube.SetPoints(points)\r\ncube.SetStrips(strip)\r\ncube.GetPointData().SetScalars(scalars)\r\n\r\nwriteFile('data/cubeStrip.vtk', cube)\r\n","sub_path":"src/polydata/writer.py","file_name":"writer.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"560328911","text":"from django.utils.translation import ugettext as _\n\nfrom .constants import ABSENT, BHS, BHS_ELIGIBLE, BHS_SCREEN, HTC, HTC_ELIGIBLE, NOT_ELIGIBLE, NOT_REPORTED, REFUSED, UNDECIDED, REFUSED_HTC, BHS_LOSS\n\noptions = list(set([ABSENT, BHS, BHS_ELIGIBLE, BHS_SCREEN, HTC, HTC_ELIGIBLE, NOT_ELIGIBLE, NOT_REPORTED, REFUSED, UNDECIDED, REFUSED_HTC, BHS_LOSS]))\n\nHOUSEHOLD_MEMBER_PARTICIPATION = [(item, item) for item in options]\n\nFEMALE_RELATIONS = [\n ('wife', 'Wife'),\n ('daughter', 'Daughter'),\n ('mother', 'Mother'),\n ('sister', 'Sister'),\n ('grandmother', 'Grandmother'),\n ('granddaughter', 'Granddaughter'),\n ('great-Grandmother', 'Great-Grandmother'),\n ('great-Granddaughter', 'Great-Granddaughter'),\n ('aunt', 'Aunt'),\n ('niece', 'Niece'),\n ('mother-in-law', 'Mother-in-law'),\n ('daughter-in-law', 'Daughter-in-law'),\n ('sister-in-law', 'Sister-in-law'),\n ('housemaid', 'Housemaid'),\n ]\n\nANY_RELATIONS = [\n ('partner', 'Partner'),\n ('housemate', 'Housemate'),\n ('cousin', 'Cousin'),\n ('family_friend', 'Family friend'),\n ('friend', 'Friend'),\n ('helper', 'Helper'),\n ('employee', 'Employee'),\n ]\nMALE_RELATIONS = [\n ('husband', 'Husband'),\n ('son', 'Son'),\n ('father', 'Father'),\n ('brother', 'Brother'),\n ('grandfather', 'Grandfather'),\n ('grandson', 'Grandson'),\n ('great-Grandfather', 'Great-Grandfather'),\n ('great-Grandson', 'Great-Grandson'),\n ('uncle', 'Uncle'),\n ('nephew', 'Nephew'),\n ('father-in-law', 'Father-in-law'),\n ('son-in-law', 'Son-in-law'),\n ('brother-in-law', 'Brother in-law'),\n ]\n\n\nrelations = FEMALE_RELATIONS + MALE_RELATIONS + ANY_RELATIONS\nrelations.sort()\nRELATIONS = [('Head', 'HEAD of HOUSEHOLD')] + relations + [('UNKNOWN', 'UNKNOWN')]\n\nABSENTEE_STATUS = (\n ('ABSENT', _('Absent')),\n ('NOT_ABSENT', _('No longer absent')),\n)\n\nABSENTEE_REASON = (\n ('gone visiting (relatives,holidays,weddings,funerals)', _('Gone visiting')),\n ('stays at lands or cattlepost ', _('Stays at Lands/Cattlepost ')),\n ('stepped out(shops, errands etc) ', _('Stepped out (shops, errands, ) ')),\n ('works in village and comes home daily', _('Works in the village, home daily')),\n ('goes to school in village and comes home daily', _('Schools in this village, home daily')),\n ('works outside village and comes home daily', _('Works outside the village, home daily')),\n ('goes to school outside village and comes home daily', _('Schools outside village, home daily')),\n ('works outside village and comes home irregularly ', _('Works outside the village, home irregularly ')),\n ('goes to school outside village and comes home irregularly ', _('Schools outside village, home irregularly ')),\n ('works outside village and comes home monthly ', _('Works outside the village, home monthly ')),\n ('goes to school outside village and comes home monthly ', _('Schools outside village, home monthly ')),\n ('works outside village and comes home on weekends ', _('Works outside the village, home on weekends ')),\n ('goes to school outside village and comes home on weekends ', _('Schools outside village, home on weekends ')),\n ('OTHER', _('Other...')),\n)\n\nNEXT_APPOINTMENT_SOURCE = (\n ('participant', _('Participant')),\n ('household member', _('household member')),\n ('hbc', _('HBC')),\n ('other', _('Other'))\n)\n\nMOVED_REASON = (\n ('TRANSFER', _('Job Transfer')),\n ('MARRIAGE', _('Marriage')),\n ('INDEPENDENT', _('Independence')),\n ('OTHER', _('Other')),\n)\n\nPLACE_SUBJECT_MOVED = (\n ('IN_VILLAGE', _('Within Village')),\n ('OUT_VILLAGE', _('Outside Village')),\n)\n\nUNDECIDED_REASON = (\n ('afraid_to_test', _('afraid_to_test')),\n ('not ready to test', _('not ready to test')),\n ('wishes to test with partner', _('wishes to test with partner')),\n ('OTHER', _('Other...')),\n)","sub_path":"apps/bcpp_household_member/choices.py","file_name":"choices.py","file_ext":"py","file_size_in_byte":3867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"564754384","text":"#Модуль по сборке и выводу собранных данных об использова��ии различных команд пользователями\n\n#Подключаем бд\nfrom modules.db import Connection\n\n#ВРЕМЕЧКО\nimport time\n\n#Основной функционал\n\ndef addStat(command, user_id):\n cursor = Connection.db.cursor()\n sql = \"INSERT INTO stats VALUES (null, %s, %s, %s)\"\n cursor.execute(sql, (int(user_id), str(command), int(time.time())))\n Connection.db.commit()\n","sub_path":"modules/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"432812678","text":"import re\nimport datetime\n\nfrom django.core.urlresolvers import reverse\nfrom django.db.models import get_model\nfrom django.http import HttpResponse, HttpResponseBadRequest\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.template.defaultfilters import escape\nfrom django.utils import feedgenerator\nfrom django.db.models import Q\n\nfrom fedregsite.annotations.forms import SearchForm\nfrom fedregsite.annotations.models import Document\nfrom fedregsite.annotations.utils import get_doc_url, feed_to_response, days_ago, MIDNIGHT_EST\n\n\n# Django performs MySQL fulltext searches in \"Boolean Mode\". This means that \n# search terms can be preceded by operators with special meanings. By default, \n# Boolean Mode performs a search on the OR of the search terms. This function \n# prepends the '+' operator to each term to ensure that the search is done on \n# the AND of the terms unless the term is already preceded by an operator.\n#\n# See http://dev.mysql.com/doc/refman/5.0/en/fulltext-boolean.html\n#\ndef prep_fulltext(query, wildcard_last=False):\n qparts = re.split('\\s+', query)\n\n operators = set(['+', '-', '<', '>', '~'])\n qparts = map(lambda qp: qp[0] in operators and qp or '+' + qp, qparts)\n\n group_closers = set([')', '\"'])\n if wildcard_last and not qparts[-1] in group_closers:\n qparts[-1] = qparts[-1] + '*'\n \n return ' '.join(qparts)\n\n\ndef parse_query(form, is_rss=False):\n if not form.is_valid():\n return None\n \n docs = Document.objects\n\n # fields requiring fulltext search\n #fields = ['text', 'action', 'subject', 'rin']\n fields = ['text', 'action', 'subject'] \n for field in fields:\n f = form.cleaned_data[field]\n if f:\n if field == 'rin':\n f = '\"' + f + '\"'\n docs = docs.filter(**{field + '__search':prep_fulltext(f)})\n\n if not is_rss:\n date_range = form.cleaned_data['date_range']\n if date_range and date_range[0]:\n if date_range[1]:\n docs = docs.filter(dailyIssue__date__range=(date_range[0], date_range[1]))\n else:\n docs = docs.filter(dailyIssue__date__exact=date_range[0])\n\n types = form.cleaned_data['type']\n if types:\n q = Q()\n for type in types:\n if type.lower() != 'presidential':\n q = q | Q(type__xmlTag__iexact=type)\n else:\n types.extend(['DETERM', 'EXECORD', 'PRMEMO', 'PRNOTICE', 'PROCLA', 'PRORDER'])\n docs = docs.filter(q)\n\n agency = form.cleaned_data['agency']\n if agency:\n docs = docs.filter(agencies__name__search=prep_fulltext(agency))\n subagency = form.cleaned_data['subagency']\n if subagency:\n docs = docs.filter(subagencies__name__search=prep_fulltext(subagency))\n\n cfr_title = form.cleaned_data['cfr_title']\n if cfr_title:\n docs = docs.filter(cfr_affected__title__exact=cfr_title)\n cfr_part = form.cleaned_data['cfr_part']\n if cfr_part:\n docs = docs.filter(cfr_affected__part__exact=cfr_part)\n \n if docs == Document.objects:\n docs = None\n else:\n docs = docs.defer('xml', 'xmlHash')\n docs = docs.select_related('dailyIssue', 'type')\n # can't sort, too slow\n #docs = docs.order_by('-dailyIssue__date')\n \n return docs\n\ndef ajax_lookup(request, model=None):\n \n try:\n query = request.GET[\"q\"]\n except KeyError:\n return HttpResponseBadRequest()\n if len(query) < 3 or (model != 'agency' and model != 'subagency'):\n return HttpResponseBadRequest()\n\n query_model = get_model('annotations', model)\n qset = query_model.objects.filter(name__search=prep_fulltext(query, wildcard_last=True))[:10]\n results = [ x.name.title() for x in qset ]\n return HttpResponse(\"\\n\".join(results))\n\n\ndef new_search(request):\n form = SearchForm(request.GET)\n docs = parse_query(form)\n \n query_dict = request.GET.copy()\n try:\n del query_dict['page']\n except KeyError: pass\n\n query_str = query_dict.urlencode()\n if docs == None:\n query_str = u''\n\n return render_to_response('search/index.html',\n {'form': form,\n 'docs': docs, \n 'query_str': query_str, \n 'search_term': query_dict.get('text','')},\n context_instance=RequestContext(request))\n\ndef search(request):\n form = SearchForm(request.GET)\n docs = parse_query(form)\n \n query_dict = request.GET.copy()\n try:\n del query_dict['page']\n except KeyError: pass\n\n query_str = query_dict.urlencode()\n if docs == None:\n query_str = u''\n\n return render_to_response('search.html',\n {'form': form,\n 'docs': docs, \n 'query_str': query_str, \n 'search_term': query_dict.get('text','')},\n context_instance=RequestContext(request))\n\n\ndef feed(request):\n form = SearchForm(request.GET)\n docs = parse_query(form, is_rss=True)\n if docs == None:\n return HttpResponseBadRequest()\n\n # See: http://code.djangoproject.com/ticket/7074\n # docs = docs.filter(dailyIssue__date__gt=days_ago(5)).order_by('-dailyIssue__date')\n d = days_ago(5)\n docs = docs.extra(where=['`annotations_dailyissue`.`date` > DATE(%s)'], params=[d]).order_by('-dailyIssue__date')\n \n feed = feedgenerator.Rss201rev2Feed(title=u'Search Results Feed',\n link=request.build_absolute_uri(reverse('search-form') + '?' + request.GET.urlencode()),\n description='',\n language=u\"en\",\n ttl=u'1440') # Set a TTL of 1 day\n\n for doc in docs:\n pubdate = datetime.datetime.combine(doc.dailyIssue.date, MIDNIGHT_EST)\n feed.add_item(title=escape(doc.subject), \n link=request.build_absolute_uri(get_doc_url(doc)),\n description=escape(doc.snippet()),\n pubdate=pubdate)\n \n return feed_to_response(feed)\n","sub_path":"site/fedregsite/annotations/views/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":6172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"416910840","text":"import os\nimport string\nimport random\nimport hashlib\nimport json\nimport datetime,time\nimport pytz\nfrom collections import OrderedDict\nfrom bson import json_util, ObjectId\nimport collections\n\n\nfrom glygen.db import get_mongodb\nfrom glygen.util import cache_record_list, get_errors_in_query\n\n\ndef search_init(config_obj):\n \n dbh, error_obj = get_mongodb()\n if error_obj != {}:\n return error_obj\n\n collection = \"c_searchinit\"\n doc = dbh[collection].find_one({})\n\n doc[\"idmapping\"][\"glycan\"][\"organism\"] = doc[\"glycan\"][\"organism\"]\n doc[\"idmapping\"][\"protein\"][\"organism\"] = doc[\"protein\"][\"organism\"] \n\n\n res_obj = doc[\"idmapping\"]\n for k in res_obj:\n if \"namespace\" in res_obj[k]:\n tmp_dict = {}\n for obj in res_obj[k][\"namespace\"]:\n tmp_dict[obj[\"source\"]] = {\"target_list\":obj[\"targetlist\"], \"example_id_list\":obj[\"example_id_list\"]}\n res_obj[k][\"namespace\"] = tmp_dict\n \n return res_obj\n\n\n\ndef search(query_obj, config_obj):\n \n dbh, error_obj = get_mongodb()\n if error_obj != {}:\n return error_obj\n\n q_list = []\n for q in query_obj[\"input_idlist\"]:\n q_list.append(q)\n\n\n mongo_query = {\"crossref.id\":{\"$in\": q_list}}\n record_id_field = config_obj[\"record_type_info\"][query_obj[\"recordtype\"]][\"field\"]\n record_id_label = config_obj[\"record_type_info\"][query_obj[\"recordtype\"]][\"label\"]\n\n\n \n coll = \"c_\" + query_obj[\"recordtype\"]\n prj_obj = {\"crossref\":1, record_id_field:1}\n\n\n\n mapping_dict = {}\n for doc in dbh[coll].find(mongo_query,prj_obj):\n in_list, out_list = [], []\n for obj in doc[\"crossref\"]:\n if obj[\"id\"].strip() == \"\":\n continue\n if obj[\"database\"] == query_obj[\"input_namespace\"] and obj[\"id\"] in q_list:\n in_list.append(obj[\"id\"])\n if obj[\"database\"] == query_obj[\"output_namespace\"]:\n out_list.append(obj[\"id\"])\n for in_id in in_list:\n if in_id not in mapping_dict:\n mapping_dict[in_id] = []\n\n for out_id in out_list:\n if out_id not in mapping_dict[in_id]:\n i_id = int(in_id) if in_id.isdigit() == True else in_id\n o_id = int(out_id) if out_id.isdigit() == True else out_id\n o = {\"anchor\":doc[record_id_field], \"from\":i_id, \"to\":o_id,\"category\":\"mapped\"}\n mapping_dict[in_id].append(o)\n \n\n\n all_glytoucan_dict = {}\n #If input_namespace is GlyToucan, check all glytoucan_idlist\n if query_obj[\"input_namespace\"].lower() == \"glytoucan\":\n for doc in dbh[\"c_glytoucan\"].find({}):\n for ac in doc[\"aclist\"]:\n all_glytoucan_dict[ac] = True\n\n record_list = []\n for in_id in mapping_dict:\n for o in mapping_dict[in_id]:\n record_list.append(o)\n\n for in_id in q_list:\n if in_id not in mapping_dict:\n reason = \"Invalid ID\"\n if in_id in all_glytoucan_dict:\n reason = \"Valid GlyTouCan accession but not in GlyGen\"\n record_list.append({\"input_id\":in_id, \"reason\": reason, \"category\":\"unmapped\"})\n elif mapping_dict[in_id] == []:\n reason = \"Valid ID, no mapping found\"\n record_list.append({\"input_id\":in_id, \"reason\": reason, \"category\":\"unmapped\"})\n \n\n mapped_legends = {\n \"from\":query_obj[\"input_namespace\"],\n \"to\":query_obj[\"output_namespace\"],\n \"anchor\":record_id_label\n }\n unmapped_legends = {\n \"input_id\":\"Input ID\",\n \"reason\":\"Reason\"\n }\n record_type = \"idmap\"\n ts_format = \"%Y-%m-%d %H:%M:%S %Z%z\"\n ts = datetime.datetime.now(pytz.timezone('US/Eastern')).strftime(ts_format)\n cache_coll = \"c_cache\"\n \n cache_info = {\n \"query\":query_obj,\n \"mapped_legends\":mapped_legends,\n \"unmapped_legends\":unmapped_legends, \n \"ts\":ts\n }\n list_id = \"\"\n if len(record_list) != 0:\n hash_str = record_type + \"_\" + \",\".join(query_obj[\"input_idlist\"]).strip()\n hash_obj = hashlib.md5(hash_str.encode('utf-8'))\n list_id = hash_obj.hexdigest()\n cache_record_list(dbh,list_id,record_list,cache_info,cache_coll,config_obj)\n res_obj = {\"list_id\":list_id}\n\n return res_obj\n\n","sub_path":"build/lib/glygen/idmapping_apilib.py","file_name":"idmapping_apilib.py","file_ext":"py","file_size_in_byte":4325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"138300724","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 1 11:16:50 2019\r\n\r\n@author: sallejaune\r\n\"\"\"\r\n\r\n#%%Import\r\nfrom PyQt6 import QtCore\r\nfrom PyQt6.QtWidgets import QApplication\r\nfrom PyQt6.QtWidgets import QWidget,QMessageBox,QLineEdit,QToolButton\r\nfrom PyQt6.QtWidgets import QVBoxLayout,QHBoxLayout,QPushButton,QGridLayout,QDoubleSpinBox,QCheckBox\r\nfrom PyQt6.QtWidgets import QComboBox,QLabel\r\nfrom PyQt6.QtGui import QIcon\r\nfrom PyQt6.QtCore import QRect\r\n\r\nimport sys,time,os\r\nimport qdarkstyle\r\nimport pathlib\r\n\r\n \r\nfrom scanMotor import SCAN\r\n\r\nimport TirGui\r\n#__version__=__init__.__version__\r\n\r\n\r\n\r\nclass ONEMOTORGUI(QWidget) :\r\n \"\"\"\r\n User interface Motor class : \r\n MOTOGUI(str(mot1), str(motorTypeName),, nomWin,nomTilt, )\r\n mot0= 'name of the motor ' (child group of the ini file)\r\n \r\n nonWin= windows name\r\n\r\n motorTypeName= Controler name : 'RSAI' or 'A2V' or 'NewFocus' or 'SmartAct' or 'Newport' , Servo\r\n showRef =True show refrence widget\r\n unit : 0: step 1: um 2: mm 3: ps 4: °\r\n \r\n \r\n \r\n fichier de config des moteurs : 'configMoteurRSAI.ini' 'configMoteurA2V.ini' 'configMoteurNewFocus.ini' 'configMoteurSmartAct.ini'\r\n \"\"\"\r\n\r\n def __init__(self, mot='',motorTypeName='',nomWin='',showRef=False,unit=2,jogValue=1,parent=None):\r\n \r\n super(ONEMOTORGUI, self).__init__(parent)\r\n \r\n p = pathlib.Path(__file__)\r\n sepa=os.sep\r\n self.icon=str(p.parent) + sepa + 'icons' +sepa\r\n self.motor=[str(mot)]\r\n self.motorTypeName=[motorTypeName]\r\n self.motorType=[0]\r\n self.MOT=[0]\r\n self.configMotName=[0]\r\n self.conf=[0]\r\n self.path=str(p.parent)+sepa\r\n self.configPath=str(p.parent / \"fichiersConfig\")+sepa\r\n self.isWinOpen=False\r\n self.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyqt6'))\r\n self.refShowId=showRef\r\n self.indexUnit=unit\r\n self.jogValue=jogValue\r\n self.etat='ok'\r\n self.tir=TirGui.TIRGUI()\r\n self.setWindowIcon(QIcon(self.icon+'LOA.png'))\r\n\r\n self.iconPlay=self.icon+\"playGreen.PNG\"\r\n self.iconPlay=pathlib.Path(self.iconPlay)\r\n self.iconPlay=pathlib.PurePosixPath(self.iconPlay)\r\n\r\n self.iconMoins=self.icon+\"moinsBleu.PNG\"\r\n self.iconMoins=pathlib.Path(self.iconMoins)\r\n self.iconMoins=pathlib.PurePosixPath(self.iconMoins)\r\n\r\n self.iconPlus=self.icon+\"plusBleu.PNG\"\r\n self.iconPlus=pathlib.Path(self.iconPlus)\r\n self.iconPlus=pathlib.PurePosixPath(self.iconPlus)\r\n\r\n self.iconStop=self.icon+\"close.PNG\"\r\n self.iconStop=pathlib.Path(self.iconStop)\r\n self.iconStop=pathlib.PurePosixPath(self.iconStop)\r\n \r\n for zi in range (0,1): # list configuration et motor types \r\n \r\n if self.motorTypeName[zi]=='RSAI':\r\n self.configMotName[zi]=self.configPath+'configMoteurRSAI.ini'\r\n import moteurRSAI as RSAI\r\n \r\n self.motorType[zi]=RSAI\r\n self.MOT[zi]=self.motorType[zi].MOTORRSAI(self.motor[zi])\r\n \r\n elif self.motorTypeName[zi]=='SmartAct':\r\n self.configMotName[zi]=self.configPath+'configMoteurSmartAct.ini'\r\n import smartactmot as SmartAct\r\n self.motorType[zi]=SmartAct\r\n self.MOT[zi]=self.motorType[zi].MOTORSMART(self.motor[zi])\r\n \r\n elif self.motorTypeName[zi]=='A2V':\r\n self.configMotName[zi]=self.configPath+'configMoteurA2V.ini'\r\n import moteurA2V as A2V\r\n self.motorType[zi]=A2V\r\n self.MOT[zi]=self.motorType[zi].MOTORA2V(self.motor[zi])\r\n \r\n elif self.motorTypeName[zi]=='NewFocus':\r\n self.configMotName[zi]=self.configPath+'configMoteurNewFocus.ini'\r\n import moteurNewFocus as NewFoc\r\n self.motorType[zi]=NewFoc\r\n self.MOT[zi]=self.motorType[zi].MOTORNEWFOCUS(self.motor[zi])\r\n \r\n elif self.motorTypeName[zi]=='newport':\r\n self.configMotName[zi]=self.configPath+'confNewport.ini'\r\n import newportMotors as Newport\r\n self.motorType[zi]=Newport\r\n self.MOT[zi]=self.motorType[zi].MOTORNEWPORT(self.motor[zi])\r\n \r\n elif self.motorTypeName[zi]=='Servo':\r\n self.configMotName[zi]=self.configPath+'configMoteurServo.ini'\r\n import servo as servo\r\n self.motorType[zi]=servo\r\n self.MOT[zi]=self.motorType[zi].MOTORSERVO(self.motor[zi])\r\n \r\n elif self.motorTypeName[zi]=='Arduino':\r\n self.configMotName[zi]=self.configPath+'configMoteurArduino.ini'\r\n import moteurArduino as arduino\r\n self.motorType[zi]=arduino\r\n self.MOT[zi]=self.motorType[zi].MOTORARDUINO(self.motor[zi])\r\n \r\n else:\r\n print('Error config motor Type name')\r\n self.configMotName[zi]=self.configPath+'configMoteurTest.ini'\r\n import moteurtest as test\r\n self.motorType[zi]=test\r\n self.MOT[zi]=self.motorType[zi].MOTORTEST(self.motor[zi])\r\n print(self.configMotName[zi])\r\n \r\n self.conf[zi]=QtCore.QSettings(self.configMotName[zi], QtCore.QSettings.Format.IniFormat) # fichier config motor fichier .ini\r\n \r\n self.scanWidget=SCAN(MOT=self.MOT[0],motor=self.motor[0],configMotName=self.configMotName[0]) # for the scan\r\n \r\n self.stepmotor=[0,0,0]\r\n self.butePos=[0,0,0]\r\n self.buteNeg=[0,0,0]\r\n self.name=[0,0,0]\r\n \r\n for zzi in range(0,1):\r\n \r\n self.stepmotor[zzi]=float(self.conf[zzi].value(self.motor[zzi]+\"/stepmotor\")) #list of stepmotor values for unit conversion\r\n self.butePos[zzi]=float(self.conf[zzi].value(self.motor[zzi]+\"/buteePos\")) # list \r\n self.buteNeg[zzi]=float(self.conf[zzi].value(self.motor[zzi]+\"/buteeneg\"))\r\n self.name[zzi]=str(self.conf[zzi].value(self.motor[zzi]+\"/Name\"))\r\n \r\n self.setWindowTitle(nomWin+' : '+ self.name[0]+' V.')\r\n \r\n self.thread=PositionThread(self,mot=self.MOT[0],motorType=self.motorType[0]) # thread for displaying position\r\n self.thread.POS.connect(self.Position)\r\n self.thread.ETAT.connect(self.Etat)\r\n \r\n \r\n \r\n ## initialisation of the jog value \r\n if self.indexUnit==0: # step\r\n self.unitChange=1\r\n self.unitName='step'\r\n \r\n if self.indexUnit==1: # micron\r\n self.unitChange=float((1*self.stepmotor[0])) \r\n self.unitName='um'\r\n if self.indexUnit==2: # mm \r\n self.unitChange=float((1000*self.stepmotor[0]))\r\n self.unitName='mm'\r\n if self.indexUnit==3: # ps double passage : 1 microns=6fs\r\n self.unitChange=float(1*self.stepmotor[0]/0.0066666666) \r\n self.unitName='ps'\r\n if self.indexUnit==4: # en degres\r\n self.unitChange=1 *self.stepmotor[0]\r\n self.unitName='°' \r\n \r\n self.setup()\r\n \r\n self.unit()\r\n self.jogStep.setValue(self.jogValue)\r\n \r\n def startThread2(self):\r\n self.thread.ThreadINIT()\r\n self.thread.start()\r\n time.sleep(0.1)\r\n \r\n \r\n def setup(self):\r\n \r\n vbox1=QVBoxLayout() \r\n hboxTitre=QHBoxLayout()\r\n self.nom=QLabel(self.name[0])\r\n self.nom.setStyleSheet(\"font: bold 20pt;color:yellow\")\r\n hboxTitre.addWidget(self.nom)\r\n \r\n self.enPosition=QLineEdit()\r\n #self.enPosition.setMaximumWidth(50)\r\n self.enPosition.setStyleSheet(\"font: bold 15pt\")\r\n self.enPosition.setAlignment(QtCore.Qt.AlignmentFlag.AlignHCenter | QtCore.Qt.AlignmentFlag.AlignVCenter)\r\n hboxTitre.addWidget(self.enPosition)\r\n self.butNegButt=QCheckBox('But Neg',self)\r\n hboxTitre.addWidget(self.butNegButt)\r\n \r\n self.butPosButt=QCheckBox('But Pos',self)\r\n hboxTitre.addWidget(self.butPosButt)\r\n vbox1.addLayout(hboxTitre)\r\n #vbox1.addSpacing(10)\r\n \r\n hShoot=QHBoxLayout()\r\n self.shootCibleButton=QPushButton('Shot')\r\n self.shootCibleButton.setStyleSheet(\"font: 12pt;background-color: red\")\r\n self.shootCibleButton.setMaximumWidth(100)\r\n self.shootCibleButton.setMinimumWidth(100)\r\n hShoot.addWidget(self.shootCibleButton)\r\n vbox1.addLayout(hShoot)\r\n \r\n \r\n hbox0=QHBoxLayout()\r\n self.position=QLabel('1234567')\r\n self.position.setMaximumWidth(300)\r\n self.position.setStyleSheet(\"font: bold 40pt\" )\r\n \r\n self.unitBouton=QComboBox()\r\n self.unitBouton.addItem('Step')\r\n self.unitBouton.addItem('um')\r\n self.unitBouton.addItem('mm')\r\n self.unitBouton.addItem('ps')\r\n self.unitBouton.addItem('°')\r\n self.unitBouton.setMaximumWidth(100)\r\n self.unitBouton.setMinimumWidth(100)\r\n self.unitBouton.setStyleSheet(\"font: bold 12pt\")\r\n self.unitBouton.setCurrentIndex(self.indexUnit)\r\n \r\n \r\n self.zeroButton=QPushButton('Zero')\r\n self.zeroButton.setMaximumWidth(50)\r\n \r\n hbox0.addWidget(self.position)\r\n hbox0.addWidget(self.unitBouton)\r\n hbox0.addWidget(self.zeroButton)\r\n vbox1.addLayout(hbox0)\r\n #vbox1.addSpacing(10)\r\n \r\n hboxAbs=QHBoxLayout()\r\n absolueLabel=QLabel('Absolue mouvement')\r\n# absolueLabel.setStyleSheet(\"background-color: green\")\r\n self.MoveStep=QDoubleSpinBox()\r\n self.MoveStep.setMaximum(1000000)\r\n self.MoveStep.setMinimum(-1000000)\r\n #self.MoveStep.setStyleSheet(\"background-color: green\")\r\n \r\n self.absMvtButton=QToolButton()\r\n \r\n self.absMvtButton.setStyleSheet(\"QToolButton:!pressed{border-image: url(%s);background-color: transparent ;border-color: gray;}\"\"QToolButton:pressed{image: url(%s);background-color: gray ;border-color: gray}\"%(self.iconPlay,self.iconPlay))\r\n \r\n self.absMvtButton.setMinimumHeight(50)\r\n self.absMvtButton.setMaximumHeight(50)\r\n self.absMvtButton.setMinimumWidth(50)\r\n self.absMvtButton.setMaximumWidth(50)\r\n #self.absMvtButton.setStyleSheet(\"background-color: green\")\r\n hboxAbs.addWidget(absolueLabel)\r\n hboxAbs.addWidget(self.MoveStep)\r\n hboxAbs.addWidget(self.absMvtButton)\r\n vbox1.addLayout(hboxAbs)\r\n vbox1.addSpacing(10)\r\n hbox1=QHBoxLayout()\r\n self.moins=QToolButton()\r\n self.moins.setStyleSheet(\"QToolButton:!pressed{border-image: url(%s);background-color: transparent ;border-color: gray;}\"\"QToolButton:pressed{image: url(%s);background-color: gray ;border-color: gray}\"%(self.iconMoins,self.iconMoins))\r\n \r\n self.moins.setMinimumHeight(70)\r\n self.moins.setMaximumHeight(70)\r\n self.moins.setMinimumWidth(70)\r\n self.moins.setMaximumWidth(70)\r\n \r\n #self.moins.setStyleSheet(\"border-radius:20px\")\r\n hbox1.addWidget(self.moins)\r\n \r\n self.jogStep=QDoubleSpinBox()\r\n self.jogStep.setMaximum(1000000)\r\n self.jogStep.setMaximumWidth(130)\r\n self.jogStep.setStyleSheet(\"font: bold 12pt\")\r\n self.jogStep.setValue(self.jogValue)\r\n \r\n hbox1.addWidget(self.jogStep)\r\n \r\n \r\n self.plus=QToolButton()\r\n self.plus.setStyleSheet(\"QToolButton:!pressed{border-image: url(%s);background-color: transparent ;border-color: gray;}\"\"QToolButton:pressed{image: url(%s);background-color: gray ;border-color: gray}\"%(self.iconPlus,self.iconPlus))\r\n self.plus.setMinimumHeight(70)\r\n self.plus.setMaximumHeight(70)\r\n self.plus.setMinimumWidth(70)\r\n self.plus.setMaximumWidth(70)\r\n #self.plus.setStyleSheet(\"border-radius:20px\")\r\n hbox1.addWidget(self.plus)\r\n \r\n vbox1.addLayout(hbox1)\r\n #vbox1.addStretch(10)\r\n vbox1.addSpacing(10)\r\n \r\n hbox2=QHBoxLayout()\r\n self.stopButton=QToolButton()\r\n self.stopButton.setStyleSheet(\"QToolButton:!pressed{border-image: url(%s);background-color: transparent ;border-color: gray;}\"\"QToolButton:pressed{image: url(%s);background-color: gray ;border-color: gray}\"%(self.iconStop,self.iconStop))\r\n \r\n #self.stopButton.setStyleSheet(\"border-radius:20px;background-color: red\")\r\n self.stopButton.setMaximumHeight(70)\r\n self.stopButton.setMaximumWidth(70)\r\n self.stopButton.setMinimumHeight(70)\r\n self.stopButton.setMinimumWidth(70)\r\n hbox2.addWidget(self.stopButton)\r\n vbox2=QVBoxLayout()\r\n \r\n self.showRef=QPushButton('Show Ref')\r\n self.showRef.setMaximumWidth(90)\r\n vbox2.addWidget(self.showRef)\r\n self.scan=QPushButton('Scan')\r\n self.scan.setMaximumWidth(90)\r\n vbox2.addWidget(self.scan)\r\n hbox2.addLayout(vbox2)\r\n \r\n vbox1.addLayout(hbox2)\r\n vbox1.addSpacing(10)\r\n \r\n self.REF1 = REF1M(num=1)\r\n \r\n self.REF2 = REF1M(num=2)\r\n \r\n self.REF3 = REF1M(num=3)\r\n \r\n self.REF4 = REF1M(num=4)\r\n \r\n self.REF5 = REF1M(num=5)\r\n \r\n self.REF6 = REF1M(num=6)\r\n \r\n grid_layoutRef = QGridLayout()\r\n grid_layoutRef.setVerticalSpacing(4)\r\n grid_layoutRef.setHorizontalSpacing(4)\r\n grid_layoutRef.addWidget(self.REF1,0,0)\r\n grid_layoutRef.addWidget(self.REF2,0,1)\r\n grid_layoutRef.addWidget(self.REF3,1,0)\r\n grid_layoutRef.addWidget(self.REF4,1,1)\r\n grid_layoutRef.addWidget(self.REF5,2,0)\r\n grid_layoutRef.addWidget(self.REF6,2,1)\r\n \r\n self.widget6REF=QWidget()\r\n self.widget6REF.setLayout(grid_layoutRef)\r\n vbox1.addWidget(self.widget6REF)\r\n # vbox1.setContentsMargins(0,0,0,0)\r\n self.setLayout(vbox1)\r\n \r\n \r\n self.absRef=[self.REF1.ABSref,self.REF2.ABSref,self.REF3.ABSref,self.REF4.ABSref,self.REF5.ABSref,self.REF6.ABSref] \r\n self.posText=[self.REF1.posText,self.REF2.posText,self.REF3.posText,self.REF4.posText,self.REF5.posText,self.REF6.posText]\r\n self.POS=[self.REF1.Pos,self.REF2.Pos,self.REF3.Pos,self.REF4.Pos,self.REF5.Pos,self.REF6.Pos]\r\n self.Take=[self.REF1.take,self.REF2.take,self.REF3.take,self.REF4.take,self.REF5.take,self.REF6.take]\r\n \r\n self.actionButton()\r\n self.jogStep.setFocus()\r\n self.refShow()\r\n \r\n \r\n \r\n \r\n def actionButton(self):\r\n '''\r\n buttons action setup \r\n '''\r\n \r\n self.unitBouton.currentIndexChanged.connect(self.unit) # unit change\r\n self.absMvtButton.clicked.connect(self.MOVE)\r\n self.plus.clicked.connect(self.pMove) # jog + foc\r\n self.plus.setAutoRepeat(False)\r\n self.moins.clicked.connect(self.mMove)# jog - fo\r\n self.moins.setAutoRepeat(False) \r\n self.scan.clicked.connect(lambda:self.open_widget(self.scanWidget) ) \r\n self.zeroButton.clicked.connect(self.Zero) # reset display to 0\r\n \r\n #self.refZeroButton.clicked.connect(self.RefMark) # todo\r\n \r\n self.stopButton.clicked.connect(self.StopMot)#stop motors \r\n self.showRef.clicked.connect(self.refShow) # show references widgets\r\n self.shootCibleButton.clicked.connect(self.ShootAct)\r\n iii=1\r\n for saveNameButton in self.posText: # reference name\r\n nbRef=str(iii)\r\n saveNameButton.textChanged.connect(self.savName)\r\n saveNameButton.setText(str(self.conf[0].value(self.motor[0]+\"/ref\"+nbRef+\"Name\"))) # print ref name\r\n iii+=1 \r\n for posButton in self.POS: # button GO\r\n posButton.clicked.connect(self.ref) # go to reference value\r\n eee=1 \r\n for absButton in self.absRef: \r\n nbRef=str(eee)\r\n absButton.setValue(float(self.conf[0].value(self.motor[0]+\"/ref\"+nbRef+\"Pos\"))/self.unitChange) # save reference value\r\n absButton.editingFinished.connect(self.savRef) # sauv value\r\n eee+=1\r\n \r\n for takeButton in self.Take:\r\n takeButton.clicked.connect(self.take) # take the value \r\n \r\n \r\n def open_widget(self,fene):\r\n \r\n \"\"\" open new widget \r\n \"\"\"\r\n \r\n if fene.isWinOpen==False:\r\n #New widget\"\r\n fene.show()\r\n fene.isWinOpen=True\r\n \r\n else:\r\n #fene.activateWindow()\r\n fene.raise_()\r\n fene.showNormal()\r\n \r\n \r\n \r\n def refShow(self):\r\n \r\n if self.refShowId==True:\r\n #self.resize(368, 345)\r\n self.widget6REF.show()\r\n self.refShowId=False\r\n self.showRef.setText('Hide Ref')\r\n self.setFixedSize(430,800)\r\n \r\n else:\r\n #print(self.geometry())\r\n \r\n self.widget6REF.hide()\r\n self.refShowId=True\r\n #self.setGeometry(QRect(107, 75, 429, 315))\r\n #self.setMaximumSize(368, 345)\r\n self.showRef.setText('Show Ref')\r\n# print(self.sizeHint())\r\n# self.minimumSizeHint()\r\n# print(self.sizeHint())\r\n# self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)\r\n #self.setMaximumSize(300,300)\r\n self.setFixedSize(430,380)\r\n \r\n #self.updateGeometry()\r\n \r\n def MOVE(self):\r\n '''\r\n absolue mouvment\r\n '''\r\n \r\n a=float(self.MoveStep.value())\r\n a=float(a*self.unitChange) # changement d unite\r\n if aself.butePos[0] :\r\n print( \"STOP : Butée Positive\")\r\n self.butPosButt.setChecked(True)\r\n self.MOT[0].stopMotor()\r\n else :\r\n self.MOT[0].move(a)\r\n self.butNegButt.setChecked(False)\r\n self.butPosButt.setChecked(False)\r\n \r\n def pMove(self):\r\n '''\r\n action jog + foc \r\n '''\r\n a=float(self.jogStep.value())\r\n a=float(a*self.unitChange)\r\n b=self.MOT[0].position()\r\n \r\n if b+a>self.butePos[0] :\r\n print( \"STOP : Positive switch\")\r\n self.MOT[0].stopMotor()\r\n self.butPosButt.setChecked(True)\r\n else :\r\n self.MOT[0].rmove(a)\r\n self.butNegButt.setChecked(False)\r\n self.butPosButt.setChecked(False)\r\n def mMove(self): \r\n '''\r\n action jog - foc\r\n '''\r\n a=float(self.jogStep.value())\r\n a=float(a*self.unitChange)\r\n b=self.MOT[0].position()\r\n if b-aself.butePos[i] :\r\n print( \"STOP : positive switch\")\r\n self.butPosButt.setChecked(True)\r\n self.MOT[i].stopMotor()\r\n else :\r\n self.MOT[i].move(vref)\r\n self.butNegButt.setChecked(False)\r\n self.butPosButt.setChecked(False) \r\n#\r\n def savName(self) :\r\n '''\r\n Save reference name\r\n '''\r\n sender=QtCore.QObject.sender(self)\r\n nbRef=sender.objectName()[0] #PosTExt1\r\n vname=self.posText[int(nbRef)-1].text()\r\n for i in range (0,1):\r\n self.conf[i].setValue(self.motor[i]+\"/ref\"+nbRef+\"Name\",str(vname))\r\n self.conf[i].sync()\r\n#\r\n def savRef (self) :\r\n '''\r\n save reference value\r\n '''\r\n sender=QtCore.QObject.sender(self)\r\n nbRef=sender.objectName()[0] # nom du button ABSref1\r\n \r\n vref=int(self.absRef[int(nbRef)-1].value())*self.unitChange\r\n self.conf[0].setValue(self.motor[0]+\"/ref\"+nbRef+\"Pos\",vref) # on sauvegarde en step dans le fichier ini\r\n self.conf[0].sync()\r\n \r\n def ShootAct(self):\r\n try: \r\n self.tir.TirAct() \r\n except: pass\r\n \r\n def closeEvent(self, event):\r\n \"\"\" \r\n When closing the window\r\n \"\"\"\r\n self.fini()\r\n time.sleep(0.1)\r\n event.accept()\r\n \r\n def fini(self): \r\n '''\r\n a the end we close all the thread \r\n '''\r\n self.thread.stopThread()\r\n self.isWinOpen=False\r\n time.sleep(0.1) \r\n if self.scanWidget.isWinOpen==True:\r\n self.scanWidget.close()\r\n \r\nclass REF1M(QWidget):\r\n \r\n def __init__(self,num=0, parent=None):\r\n super(REF1M, self).__init__()\r\n self.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyqt6'))\r\n self.wid=QWidget()\r\n self.id=num\r\n self.vboxPos=QVBoxLayout()\r\n p = pathlib.Path(__file__)\r\n sepa=os.sep\r\n self.icon=str(p.parent) + sepa + 'icons' +sepa\r\n self.posText=QLineEdit('ref')\r\n self.posText.setAlignment(QtCore.Qt.AlignmentFlag.AlignHCenter | QtCore.Qt.AlignmentFlag.AlignVCenter)\r\n self.posText.setStyleSheet(\"font: bold 15pt\")\r\n self.posText.setObjectName('%s'%self.id)\r\n# self.posText.setMaximumWidth(80)\r\n self.vboxPos.addWidget(self.posText)\r\n self.iconTake=self.icon+\"disquette.PNG\"\r\n self.iconTake=pathlib.Path(self.iconTake)\r\n self.iconTake=pathlib.PurePosixPath(self.iconTake)\r\n self.take=QToolButton()\r\n self.take.setObjectName('%s'%self.id)\r\n self.take.setStyleSheet(\"QToolButton:!pressed{border-image: url(%s);background-color: transparent ;border-color: gray;}\"\"QToolButton:pressed{image: url(%s);background-color: gray ;border-color: gray}\"%(self.iconTake,self.iconTake))\r\n self.take.setMaximumWidth(30)\r\n self.take.setMinimumWidth(30)\r\n self.take.setMinimumHeight(30)\r\n self.take.setMaximumHeight(30)\r\n self.takeLayout=QHBoxLayout()\r\n self.takeLayout.addWidget(self.take)\r\n\r\n self.iconGo=self.icon+\"go.PNG\"\r\n self.iconGo=pathlib.Path(self.iconGo)\r\n self.iconGo=pathlib.PurePosixPath(self.iconGo)\r\n self.Pos=QToolButton()\r\n self.Pos.setStyleSheet(\"QToolButton:!pressed{border-image: url(%s);background-color: transparent ;border-color: gray;}\"\"QToolButton:pressed{image: url(%s);background-color: gray ;border-color: gray}\"%(self.iconGo,self.iconGo))\r\n self.Pos.setMinimumHeight(30)\r\n self.Pos.setMaximumHeight(30)\r\n self.Pos.setMinimumWidth(30)\r\n self.Pos.setMaximumWidth(30)\r\n self.PosLayout=QHBoxLayout()\r\n self.PosLayout.addWidget(self.Pos)\r\n self.Pos.setObjectName('%s'%self.id)\r\n #○self.Pos.setStyleSheet(\"background-color: rgb(85, 170, 255)\")\r\n Labelref=QLabel('Pos :')\r\n Labelref.setMaximumWidth(30)\r\n Labelref.setStyleSheet(\"font: 9pt\" )\r\n self.ABSref=QDoubleSpinBox()\r\n self.ABSref.setMaximum(500000000)\r\n self.ABSref.setMinimum(-500000000)\r\n self.ABSref.setValue(123456)\r\n self.ABSref.setMaximumWidth(80)\r\n self.ABSref.setObjectName('%s'%self.id)\r\n self.ABSref.setStyleSheet(\"font: 9pt\" )\r\n \r\n grid_layoutPos = QGridLayout()\r\n grid_layoutPos.setVerticalSpacing(5)\r\n grid_layoutPos.setHorizontalSpacing(10)\r\n grid_layoutPos.setAlignment(QtCore.Qt.AlignmentFlag.AlignHCenter | QtCore.Qt.AlignmentFlag.AlignVCenter)\r\n grid_layoutPos.addLayout(self.takeLayout,0,0)\r\n grid_layoutPos.addLayout(self.PosLayout,0,1)\r\n grid_layoutPos.addWidget(Labelref,1,0)\r\n grid_layoutPos.addWidget(self.ABSref,1,1)\r\n \r\n \r\n self.vboxPos.addLayout(grid_layoutPos)\r\n self.wid.setStyleSheet(\"background-color: rgb(60, 77, 87);border-radius:10px\")\r\n \r\n self.wid.setLayout(self.vboxPos)\r\n mainVert=QVBoxLayout()\r\n mainVert.addWidget(self.wid)\r\n mainVert.setContentsMargins(0,0,0,0)\r\n self.setLayout(mainVert)\r\n\r\n\r\nclass PositionThread(QtCore.QThread):\r\n '''\r\n Secon thread to display the position\r\n '''\r\n import time #?\r\n POS=QtCore.pyqtSignal(float) # signal of the second thread to main thread to display motors position\r\n ETAT=QtCore.pyqtSignal(str)\r\n def __init__(self,parent=None,mot='',motorType=''):\r\n super(PositionThread,self).__init__(parent)\r\n self.MOT=mot\r\n self.motorType=motorType\r\n self.parent=parent\r\n self.motorTypeName=self.parent.motorTypeName\r\n self.stop=False\r\n# print('motor type',self.motorTypeName)\r\n def run(self):\r\n while True:\r\n if self.stop==True:\r\n break\r\n else:\r\n \r\n Posi=(self.MOT.position())\r\n time.sleep(0.5)\r\n \r\n try :\r\n self.POS.emit(Posi)\r\n \r\n time.sleep(0.1)\r\n \r\n except:\r\n print('error emit')\r\n if self.motorTypeName[0]=='RSAI': \r\n try :\r\n etat=self.MOT.etatMotor()\r\n# print(etat)\r\n self.ETAT.emit(etat)\r\n except: pass\r\n #print('error emit etat') \r\n \r\n def ThreadINIT(self):\r\n self.stop=False \r\n \r\n def stopThread(self):\r\n self.stop=True\r\n time.sleep(0.1)\r\n self.terminate()\r\n \r\n\r\n\r\nif __name__ =='__main__':\r\n \r\n appli=QApplication(sys.argv)\r\n \r\n \r\n mot5=ONEMOTORGUI( mot='tiltLat',motorTypeName='A2V',showRef=False,unit=1,jogValue=1)\r\n mot5.show()\r\n mot5.startThread2()\r\n appli.exec_()","sub_path":"oneMotorGuiNew.py","file_name":"oneMotorGuiNew.py","file_ext":"py","file_size_in_byte":31499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"106347852","text":"# issue #1847\n\nfrom threading import Thread\nimport faulthandler\n\nimport gym\n\nfaulthandler.enable()\n\n\ndef make_t2():\n print(1)\n\n\ndef make_t1():\n th = Thread(target=make_t2)\n th.start()\n\n\n# env = gym.make('MsPacman-v4')\n# env = gym.make('CartPole-v0')\n\nt = Thread(target=make_t1)\nt.start()\n","sub_path":"issues/individual_issue.py","file_name":"individual_issue.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"572187389","text":"from lmfit import Parameter, Parameters, minimize\n\nfrom larch import Group, isgroup, parse_group_args\n\nfrom larch.utils import index_of\nfrom larch_plugins.xray import xray_edge, xray_line, f1_chantler, f2_chantler, f1f2\nfrom larch_plugins.xafs import set_xafsGroup, find_e0, preedge\n\nimport numpy as np\nfrom scipy.special import erfc\n\nMAXORDER = 6\n\ndef match_f2(p, en=0, mu=1, f2=1, e0=0, em=0, weight=1, theta=1, order=None,\n leexiang=False):\n \"\"\"\n Objective function for matching mu(E) data to tabulated f''(E) using the MBACK\n algorithm and, optionally, the Lee & Xiang extension.\n \"\"\"\n pars = p.valuesdict()\n eoff = en - e0\n\n norm = p['a']*erfc((en-em)/p['xi']) + p['c0'] # erfc function + constant term of polynomial\n for i in range(order): # successive orders of polynomial\n j = i+1\n attr = 'c%d' % j\n if attr in p:\n norm += p[attr] * eoff**j\n func = (f2 + norm - p['s']*mu) * theta / weight\n if leexiang:\n func = func / p['s']*mu\n return func\n\n\ndef mback(energy, mu=None, group=None, order=3, z=None, edge='K', e0=None, emin=None, emax=None,\n whiteline=None, leexiang=False, tables='chantler', fit_erfc=False, return_f1=False,\n _larch=None):\n \"\"\"\n Match mu(E) data for tabulated f''(E) using the MBACK algorithm and,\n optionally, the Lee & Xiang extension\n\n Arguments:\n energy, mu: arrays of energy and mu(E)\n order: order of polynomial [3]\n group: output group (and input group for e0)\n z: Z number of absorber\n edge: absorption edge (K, L3)\n e0: edge energy\n emin: beginning energy for fit\n emax: ending energy for fit\n whiteline: exclusion zone around white lines\n leexiang: flag to use the Lee & Xiang extension\n tables: 'chantler' (default) or 'cl'\n fit_erfc: True to float parameters of error function\n return_f1: True to put the f1 array in the group\n\n Returns:\n group.f2: tabulated f2(E)\n group.f1: tabulated f1(E) (if return_f1 is True)\n group.fpp: matched data\n group.mback_params: Group of parameters for the minimization\n\n References:\n * MBACK (Weng, Waldo, Penner-Hahn): http://dx.doi.org/10.1086/303711\n * Lee and Xiang: http://dx.doi.org/10.1088/0004-637X/702/2/970\n * Cromer-Liberman: http://dx.doi.org/10.1063/1.1674266\n * Chantler: http://dx.doi.org/10.1063/1.555974\n \"\"\"\n order=int(order)\n if order < 1: order = 1 # set order of polynomial\n if order > MAXORDER: order = MAXORDER\n\n ### implement the First Argument Group convention\n energy, mu, group = parse_group_args(energy, members=('energy', 'mu'),\n defaults=(mu,), group=group,\n fcn_name='mback')\n if len(energy.shape) > 1:\n energy = energy.squeeze()\n if len(mu.shape) > 1:\n mu = mu.squeeze()\n\n group = set_xafsGroup(group, _larch=_larch)\n\n if e0 is None: # need to run find_e0:\n e0 = xray_edge(z, edge, _larch=_larch)[0]\n if e0 is None:\n e0 = group.e0\n if e0 is None:\n find_e0(energy, mu, group=group)\n\n\n ### theta is an array used to exclude the regions emax, and\n ### around white lines, theta=0.0 in excluded regions, theta=1.0 elsewhere\n (i1, i2) = (0, len(energy)-1)\n if emin is not None: i1 = index_of(energy, emin)\n if emax is not None: i2 = index_of(energy, emax)\n theta = np.ones(len(energy)) # default: 1 throughout\n theta[0:i1] = 0\n theta[i2:-1] = 0\n if whiteline:\n pre = 1.0*(energye0+float(whiteline))\n theta = theta * (pre + post)\n if edge.lower().startswith('l'):\n l2 = xray_edge(z, 'L2', _larch=_larch)[0]\n l2_pre = 1.0*(energyl2+float(whiteline))\n theta = theta * (l2_pre + l2_post)\n\n\n ## this is used to weight the pre- and post-edge differently as\n ## defined in the MBACK paper\n weight1 = 1*(energye0)\n weight = np.sqrt(sum(weight1))*weight1 + np.sqrt(sum(weight2))*weight2\n ## get the f'' function from CL or Chantler\n if tables.lower() == 'chantler':\n f1 = f1_chantler(z, energy, _larch=_larch)\n f2 = f2_chantler(z, energy, _larch=_larch)\n else:\n (f1, f2) = f1f2(z, energy, edge=edge, _larch=_larch)\n group.f2=f2\n if return_f1:\n group.f1=f1\n\n em = xray_line(z, edge.upper(), _larch=_larch)[0] # erfc centroid\n\n params = Parameters()\n params.add(name='s', value=1, vary=True) # scale of data\n params.add(name='xi', value=50, vary=fit_erfc, min=0) # width of erfc\n params.add(name='a', value=0, vary=False) # amplitude of erfc\n if fit_erfc:\n params['a'].value = 1\n params['a'].vary = True\n\n for i in range(order): # polynomial coefficients\n params.add(name='c%d' % i, value=0, vary=True)\n\n out = minimize(match_f2, params, method='leastsq',\n gtol=1.e-5, ftol=1.e-5, xtol=1.e-5, epsfcn=1.e-5,\n kws = dict(en=energy, mu=mu, f2=f2, e0=e0, em=em,\n order=order, weight=weight, theta=theta, leexiang=leexiang))\n\n opars = out.params.valuesdict()\n eoff = energy - e0\n\n norm_function = opars['a']*erfc((energy-em)/opars['xi']) + opars['c0']\n for i in range(order):\n j = i+1\n attr = 'c%d' % j\n if attr in opars:\n norm_function += opars[attr]* eoff**j\n\n group.e0 = e0\n group.fpp = opars['s']*mu - norm_function\n group.mback_params = opars\n tmp = Group(energy=energy, mu=group.f2-norm_function, e0=0)\n\n # calculate edge step from f2 + norm_function: should be very smooth\n pre_f2 = preedge(energy, group.f2+norm_function, e0=e0, nnorm=2, nvict=0)\n group.edge_step = pre_f2['edge_step'] / opars['s']\n\n pre_fpp = preedge(energy, mu, e0=e0, nnorm=2, nvict=0)\n\n group.norm = (mu - pre_fpp['pre_edge']) / group.edge_step\n\n\ndef registerLarchPlugin(): # must have a function with this name!\n return ('_xafs', { 'mback': mback })\n","sub_path":"plugins/xafs/mback.py","file_name":"mback.py","file_ext":"py","file_size_in_byte":6255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"369267003","text":"\"\"\"\nOverview\n========\n\nHighlight html lines where errors/warnings were encountered by Html Tidy.\n\nWhen the plugin is installed in your vyrc, whenever an event\nof the type in BETA mode happens it runs tidy against the file\nand tags all regions where tidy found errors. \n\nIt is possible to jump to these regions by using the keycommands implemented by\nthe core text_spots plugin. \n\nOne would just jump back/next by pressing or \nin NORMAL mode. \n\nThe html checker plugin writes to sys.stdout all the errours\nthat were encountered in the html file. it is necessary\nto set an output target on areavi instance in order to check\nthe errors/warnings.\n\nFor more information see: vyapp.plugins.text_spots\n\nPlugin dependencies: \n vyapp.plugins.text_spots\n\nExtern dependencies:\n Html Tidy\n\nKey-Commands\n============\n\nNamespace: html-checker\n\n\"\"\"\n\nfrom subprocess import Popen, STDOUT, PIPE\nfrom vyapp.areavi import AreaVi\nfrom vyapp.plugins import ENV\nfrom vyapp.app import root\nfrom re import findall\nimport sys\n\nclass HtmlChecker(object):\n def __init__(self, area, path='tidy'):\n self.area = area\n # The path that tidy stays, in some\n # systems it may not be available in the\n # PATH variable.\n self.path = path\n\n area.install('html-checker', (-1, '<>', lambda event: \n self.area.hook('BETA', '', self.check)),\n (-1, '<>', lambda event: \n self.area.unhook('BETA', '')),\n (-1, '<>', lambda event: \n self.area.hook('BETA', '', self.check)),\n (-1, '<>', lambda event: \n self.area.unhook('BETA', '')))\n\n def check(self, event):\n child = Popen([self.path, '-e', '-quiet', \n self.area.filename], stdout=PIPE, stderr=STDOUT)\n output = child.communicate()[0]\n regex = 'line ([0-9]+) column ([0-9]+) - (.+)'\n ranges = findall(regex, output)\n\n sys.stdout.write('Errors:\\n%s\\n' % output)\n for line, col, error in ranges:\n self.area.tag_add('(SPOT)', '%s.0' % line, \n '%s.0 lineend' % line)\n\n if child.returncode:\n root.status.set_msg('Errors were found!')\n else:\n root.status.set_msg('No errors!')\n self.area.chmode('NORMAL')\n\ninstall = HtmlChecker\n\n\n\n\n","sub_path":"vyapp/plugins/html_checker.py","file_name":"html_checker.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"392551191","text":"# -*- coding: utf-8 -*-\n#---------------------------------------\n# Programming:QiuShiBaiKe\n# version:0.1\n# author:wyy\n# data:2017-01-06\n# language:Python 3.5.2\n# tools : requests\n# function:get text\n#---------------------------------------\n\nimport urllib.parse\nimport requests\nfrom bs4 import BeautifulSoup\nimport time\n\n\nurl = \"http://www.qiushibaike.com/text/\"\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}\n\nflag = True\ni = 1\nwhile flag:\n html = requests.get(url, headers=headers)\n soup = BeautifulSoup(html.text, 'lxml')\n\n # get text\n qsbkText = soup.findAll('div', {'class': 'content'})\n with open('./Data/qsbkReq.txt', 'a+', encoding='utf-8') as textFile:\n textFile.write('\\n' + str(i) + '\\n')\n for item in qsbkText:\n textFile.write(item.text)\n textFile.write('\\n' + '---' * 30 + '\\n')\n time.sleep(3)\n\n # exist next url\n if soup.find('span', {'class': 'next'}) == None:\n flag = False\n\n # get link\n qsbkIndex = soup.find('ul', {'class': 'pagination'}).findAll('a')\n linkList = []\n for link in qsbkIndex:\n linkList.append(link['href'])\n url = 'http://' + urllib.parse.urlparse(url)[1] + linkList[-1]\n\n i = i + 1\n print(flag)\n","sub_path":"05Web/pachong/QSBK/QSBKRequests.py","file_name":"QSBKRequests.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"579854350","text":"#\n# meteo-station obv BME280 Digitale Barometer Druk en Vochtigheid Sensor Module\n#\n# bron: https://www.tinytronics.nl/shop/nl/sensoren/temperatuur-lucht-vochtigheid/bme280-digitale-barometer-druk-en-vochtigheid-sensor-module\n# Een zeer compacte barometer die werkt via I2C of SPI. De BME280 is een 3-in-1 module\n# die temperatuur, druk en vochtigheid kan meten.\n#\n# De module kan alleen gevoed worden met 3.3VDC. De I2C/SPI werkt dus ook met 3.3V en\n# je hebt dus een level converter nodig bij gebruik van bijv. een 5V Arduino Uno.\n#\n# Het standaard I2C adres van deze module is 0x76. Dit moet mogelijk in de\n# voorbeeldcode/library veranderd worden van 0x77 naar 0x76. Indien je de SDO pin\n# verbind met Vcc, dan wordt het I2C adres 0x77.\n#\n# (Arduino) project met de ESP2866 en BME280 (nuttig voor aansluitingen) is te vinden op\n# https://core-electronics.com.au/projects/thingspeak-temperature-pressure-logger\n#\n# MicroPython library voor de BME280 en ESP2866 gevonden op GitHub:\n# https://github.com/triplepoint/micropython_bme280_i2c\n#\n# upload files to device:\n# ampy --port /dev/ttyUSB0 put main.py\n# ampy --port /dev/ttyUSB0 put bme280_i2c.py\n#\n# open console en start programma\n# screen /dev/ttyUSB0 115200\n# type enter-toets\n# en type cntrl-D\n#\n# BvH, 26-05-2019\n#\n\n\n# LIBRARIES:\n#\n# We start by importing the Pin class from the machine library, as this will enable us to use\n# the GPIO pins. We need to use a wait-time in the loop and import the sleep function from the\n# time library.\nfrom machine import Pin, I2C\nfrom time import sleep\n# using mqtt for exchanging data\nfrom umqttsimple import MQTTClient\n#\n# The bme280_i2c library assumes the default connection of the I2C bus\n# On Wymos D1 mini devices that is SCL-to-D1 (pin5), SDA-to-D2 (pin4).\n#\nimport bme280_i2c\n\n# Variabelen:\n#temp_min = 100\n#temp_max = 0\n#pres_min = 10000\n#pres_max = 0\n#humi_min = 100\n#humi_max = 0\n\n# Functies:\ndef do_tripple_blink(n=3):\n # tripple blink\n for x in range(n):\n led.on()\n sleep(0.5)\n led.off()\n\ndef update_measurements():\n # how to deal with a 'dict'?\n # Example from https://www.tutorialspoint.com/python/python_dictionary.htm\n # dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\n # print \"dict['Name']: \", dict['Name']\n values = bme.read_compensated_data(result = None)\n\n# INITIALISATIE:\n#\n# Next we create an object called led which will store the GPIO pin that we wish to use, and\n# whether it is an input or an output. In this case it is an output as we wish to light up the LED.\n#\n# see pinout on https://escapequotes.net/esp8266-wemos-d1-mini-pins-and-diagram/\n# pin 16 = D0 (naar LED)\nled = Pin(16, Pin.OUT)\n# show succesfull\ndo_tripple_blink()\n\n# Initialise the i2c interface.\n# pin 5 (= D1) SCL naar BME280-SCL.\n# pin 4 (= D2) SDA naar BME280-SDA.\ni2cbus = I2C(sda=Pin(4), scl=Pin(5))\ni2cbus.scan()\n# Initialise the Bosch temperature/humidity/pressure sensor.\nbme = BME280_I2C(i2c=i2cbus)\n# show succesfull\ndo_tripple_blink()\n\n# setup MQTT connection\ndef sub_cb(topic, msg):\n print((topic, msg))\n if topic == b'notification' and msg == b'received':\n print('ESP8266-wijngaar-Achthoeven received a mqtt-message!')\n\ndef connect_and_subscribe():\n global client_id, mqtt_server, topic_sub\n client = MQTTClient(client_id, mqtt_server)\n client.set_callback(sub_cb)\n client.connect()\n client.subscribe(topic_sub)\n print('Connected to %s mqtt-broker, subscribed to %s topic' % (mqtt_server, topic_sub))\n return client\n\ndef restart_and_reconnect():\n print('Failed to connect to mqtt-broker. Reconnecting...')\n time.sleep(10)\n machine.reset()\n\ntry:\n client = connect_and_subscribe()\nexcept OSError as e:\n print('Failed connecting to mqtt-broker. Error=' + e)\n restart_and_reconnect()\n\n\n# All in an endless loop:\nwhile True:\n # So now we need to turn on the LED, and it is as easy as this!\n led.on()\n # retrieve BME280-measurements:\n update_measurements()\n # show BME280-measurements\n print('temperature : ' + values['temperature'])\n print('humidity : ' + values['humidity'])\n print('pressure : ' + values['pressure'])\n payload = values['temperature'] + ',' + values['humidity'] + ',' + values['pressure']\n # better version:\n #values = read_compensated_data(result = None)\n # wait\n sleep(0.5)\n # and turn off the LED\n led.off()\n # once a minute, send a message with the data to the mqtt broker\n try:\n client.check_msg()\n if (time.time() - last_message) > message_interval:\n msg = b'measurement #%d' % counter\n# msg = b'measurement #%d' + payload % counter\n client.publish(topic_pub, msg)\n last_message = time.time()\n counter += 1\n except OSError as e:\n restart_and_reconnect()\n\n # wait and measure approx. every 15 secs\n sleep(measure_interval-0.5)\n","sub_path":"esp8266_Wemos_d1_mini/temp_humi_pres_bme280_i2c_lib/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"442698926","text":"import configparser\nimport pymongo\nimport os\n\n# Get env variables for database configuration\nMONGODB_URL = os.environ.get('MONGODB_URL', None)\nDATABASE_NAME = os.environ.get('DATABASE_NAME', None)\nDATASET_COLLECTION_NAME = os.environ.get(\n 'DATASET_COLLECTION_NAME', 'future_trends')\n\nclass MongoDatabase:\n def __init__(self):\n print(\"Establishing connection to the database\")\n if MONGODB_URL is None or DATABASE_NAME is None:\n raise Exception(\n 'Database could not be identified. Make sure they are added to environment variables')\n\n self.connection_string = MONGODB_URL\n self.client = pymongo.MongoClient(self.connection_string)\n self.database = self.client[DATABASE_NAME]\n\n self.verify_connection()\n\n def reset_connection(self):\n self.client = pymongo.MongoClient(self.connection_string)\n\n def verify_connection(self):\n for _ in range(5):\n try:\n self.client.server_info()\n print(\"Connected to the database\")\n return\n except:\n self.reset_connection()\n\n raise \"Failed to connect to the database\"\n\n\nclass FutureTrendsDatabase(MongoDatabase):\n def __init__(self):\n MongoDatabase.__init__(self)\n\n def get_future_trends_collection(self) -> pymongo.collection:\n return self.database[DATASET_COLLECTION_NAME]\n\n def get_future_trends_by_filter(self, filter):\n return list(self.get_future_trends_collection().find(filter))\n","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"616975068","text":"import time\nimport pandas as pd\nimport numpy as np\nimport statistics\n\n\"\"\"\nTO_DO:\n- handle extraneous user input later for city and date filtering\n(see lesson referenced in 3.code walkthrough)\n\"\"\"\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Hello! Let\\'s explore some US bikeshare data!')\n # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n cities = ['chicago', 'new york', 'washington']\n city = input(\"Would you like to see information for Chicago, New York, or Washington?\\n\")\n city = city.lower()\n while (city not in cities):\n city = input(\"Sorry, that is not a valid city, please check your spelling and enter a valid city to proceed.\\n\")\n city = city.lower()\n\n # get user input for month (all, january, february, ... , june)\n date = input(\"Would you like to filter your data by month? (yes or no)\\n\")\n date = date.lower()\n\n elig_input = ['yes', 'y', 'no', 'n']\n while (date not in elig_input):\n date = input(\"Sorry, that is not a valid response, please respond 'yes' or 'no':\")\n date = date.lower()\n\n month = 'all'\n if date == 'yes' or date == 'y':\n month = input(\"Which month, January, February, March, April, May, or June?\\n\")\n months = ['january', 'february', 'march', 'april', 'may', 'june']\n month = month.lower()\n while (month not in months):\n month = input(\"Sorry, that is an invalid month, please input one of the following months:['January', 'February', 'March', 'April', 'May', 'June']:\\n\")\n month = month.lower()\n\n # get user input for day of week (all, monday, tuesday, ... sunday)\n\n date = 'new'\n date = input(\"Would you like to filter your data by day of the week? (yes or no)\\n\")\n date = date.lower()\n\n elig_input = ['yes', 'y', 'no', 'n']\n while (date not in elig_input):\n date = input(\"Sorry, that is not a valid response, please respond 'yes' or 'no':\")\n date = date.lower()\n\n day = 'all'\n if date == 'yes' or date == 'y':\n day = input(\"Which day of the week (please input as 'Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday')\\n\")\n days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']\n day = day.lower()\n while(day not in days):\n day = input(\"Sorry, that is an invalid day, please input a valid day of the week:\")\n day = day.lower()\n day = day.lower()\n\n print (city, month, day)\n\n print('-'*40)\n return city, month, day\n\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - pandas DataFrame containing city data filtered by month and day\n \"\"\"\n\n # load data file into a dataframe\n df = pd.read_csv(CITY_DATA[city])\n\n # convert the Start Time column to datetime\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n\n # extract month and day of week from Start Time to create new columns\n df['month'] = df['Start Time'].dt.month\n df['weekday_name'] = df['Start Time'].dt.weekday_name\n df['hour'] = df['Start Time'].dt.hour\n\n # filter by month if applicable\n if month != 'all':\n # use the index of the months list to get the corresponding int\n months = ['january', 'february', 'march', 'april', 'may', 'june']\n month = months.index(month) + 1\n\n # filter by month to create the new dataframe\n df = df[df['month'] == month]\n\n # filter by day of week if applicable\n if day != 'all':\n # filter by day of week to create the new dataframe\n df = df[df['weekday_name'] == day.title()]\n\n return df\n\n\n\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n # display the most common month\n print(\"The most common month is: %i.\" % statistics.mode(df['month']))\n\n # display the most common day of week\n print(\"The most common day of the week is: %s.\" % statistics.mode(df['weekday_name']))\n\n # display the most common start hour\n print(\"The most common hour is: %i.\" % statistics.mode(df['hour']))\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n # display most commonly used start station\n print(\"The most common start station is: %s\" % statistics.mode(df['Start Station']))\n\n\n # display most commonly used end station\n print(\"The most common end station is: %s\" % statistics.mode(df['End Station']))\n\n\n # display most frequent combination of start station and end station trip\n df['Round Trip'] = df['Start Station'] + \", \" + df['End Station']\n print(\"The most common combination of start and end station is: %s\" % statistics.mode(df['Round Trip']))\n\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n # display total travel time\n print(\"The total travel time for these rides is: %i minutes\" % (df['Trip Duration'].sum()/60 + df['Trip Duration'].sum() % 60))\n\n\n # display mean travel time\n print(\"The mean travel time for these rides is %i minutes\" % (df['Trip Duration'].mean()/60 + df['Trip Duration'].mean() % 60))\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n # Display counts of user types\n print(\"Total users by type:\\n\")\n print(df['User Type'].value_counts())\n print(\"\\n\")\n\n # Display counts of gender\n print(\"Total users by gender:\\n\")\n print(df['Gender'].value_counts())\n print(\"\\n\")\n\n\n # Display earliest, most recent, and most common year of birth\n print(\"The earliest, most recent, and most common year of birth is %i, %i, and %i, respectively\"\n % (df['Birth Year'].min(), df['Birth Year'].max(), statistics.mode(df['Birth Year'])))\n print(\"\\n\")\n\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef main():\n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":7719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"569262307","text":"#!/usr/bin/python\n# coding=utf-8\nimport zipfile\nimport shutil\nimport os\nimport xlrd\nimport sys\n\nreload(sys) \nsys.setdefaultencoding('utf8') \n\n#当前目录\ncur_dir = sys.path[0]\n\n#输出目录\nout_dir = 'laka-apks'\n\ntmp_dir = os.path.abspath(os.path.join(cur_dir,os.path.pardir))\n\nout_dir = os.path.abspath(os.path.join(tmp_dir,os.path.pardir)) + '/' + out_dir\n\n# 目录不存在则创建\nif not os.path.exists(out_dir):\n os.mkdir(out_dir)\n\n# 空文件 便于写入此空文件到apk包中作为channel文件\nsrc_empty_file = cur_dir + '/info/czt.txt'\n# 创建一个空文件(不存在则创建)\nf = open(src_empty_file, 'w') \nf.close()\n\nprint('cur_dir : ' + cur_dir)\n\n# 获取当前目录中所有的apk源包\nsrc_apks = []\n# python3 : os.listdir()即可,这里使用兼容Python2的os.listdir('.')\nfor file in os.listdir(cur_dir):\n fulldirfile = os.path.join(cur_dir, file)\n print('file : ' + file)\n if os.path.isfile(fulldirfile):\n extension = os.path.splitext(file)[1][1:]\n print('extension : ' + extension)\n if extension in 'apk':\n src_apks.append(fulldirfile)\n\n# 获取渠道列表\n# channel_file = 'info/channel.txt'\n# f = open(channel_file)\n# lines = f.readlines()\n# f.close()\n\n#读渠道excel\nchannel_file = cur_dir + '/info/channels.xls'\ndata = xlrd.open_workbook(channel_file)\ntable = data.sheets()[0]\nnrows = table.nrows\n\n\nfor src_apk in src_apks:\n # file name (with extension)\n src_apk_file_name = os.path.basename(src_apk)\n # 分割文件名与后缀\n temp_list = os.path.splitext(src_apk_file_name)\n # name without extension\n src_apk_name = temp_list[0]\n # 后缀名,包含. 例如: \".apk \"\n src_apk_extension = temp_list[1]\n \n # 创建生成目录,与文件名相关\n output_dir = out_dir + '/' + src_apk_name + '/'\n\n print('output_dir : ' + output_dir)\n \n # 目录不存在则创建\n if not os.path.exists(output_dir):\n os.mkdir(output_dir)\n \n # 遍历渠道号并创建对应渠道号的apk文件\n # for line in lines:\n # 获取当前渠道号,因为从渠道文件中获得带有\\n,所有strip一下\n # target_channel = line.strip()\n # 拼接对应渠道号的apk\n # target_apk = output_dir + src_apk_name + \"-\" + target_channel + src_apk_extension \n # 拷贝建立新apk\n # shutil.copy(src_apk, target_apk)\n # zip获取新建立的apk文件\n # zipped = zipfile.ZipFile(target_apk, 'a', zipfile.ZIP_DEFLATED)\n # 初始化渠道信息\n # empty_channel_file = \"META-INF/cztchannel_{channel}\".format(channel = target_channel)\n # 写入渠道信息\n # zipped.write(src_empty_file, empty_channel_file)\n # 关闭zip流\n # zipped.close()\n \n # 遍历渠道号并创建对应渠道号的apk文件\n for i in range(1, nrows):\n # 获取当前渠道id\n target_channel_id = str(table.cell(i,0).value)\n\n # 获取当前渠道名\n target_channel_name = str(table.cell(i,1).value)\n # 拼接对应渠道号的apk\n target_apk = output_dir + src_apk_name + \"-\" + target_channel_id + \"-\" + target_channel_name + src_apk_extension\n # 拷贝建立新apk\n shutil.copy(src_apk, target_apk)\n # zip获取新建立的apk文件\n zipped = zipfile.ZipFile(target_apk, 'a', zipfile.ZIP_DEFLATED)\n # 初始化渠道信息\n empty_channel_file = \"META-INF/cztchannel_{channel}\".format(channel = target_channel_id)\n # 写入渠道信息\n zipped.write(src_empty_file, empty_channel_file)\n # 关闭zip流\n zipped.close()\n\n \n","sub_path":"channel/MultiChannelBuildTool.py","file_name":"MultiChannelBuildTool.py","file_ext":"py","file_size_in_byte":3660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"131108856","text":"# Author: Harsh Kohli\n# Date created: 5/24/2018\n\nimport yaml\nfrom utils.ioutils import read_word_embeddings, read_marco_train_data, read_marco_dev_data\nimport pickle\n\nconfig = yaml.safe_load(open('config.yml', 'r'))\nword_to_id_lookup, embeddings = read_word_embeddings(config['embedding_path'])\n\nprimary_train_data = read_marco_train_data(config['train_path'], word_to_id_lookup)\ndev_data = read_marco_dev_data(config['dev_path'], word_to_id_lookup)\n\nall_data = {'train_data': primary_train_data, 'dev_data': dev_data, 'word_to_id_lookup': word_to_id_lookup,\n 'embeddings': embeddings}\npickle_file = open(config['preprocessed_data_path'], 'wb')\npickle.dump(all_data, pickle_file, protocol=pickle.HIGHEST_PROTOCOL)\npickle_file.close()\n","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"128759659","text":"\r\nwith open(\"data/day5.txt\") as data:\r\n\tfull_input=data.read().rstrip()\r\n\r\n\r\ndef reduce(long,remove_char):\r\n\treturn long.replace((remove_char)+(remove_char.upper()),\"\").replace((remove_char.upper())+(remove_char),\"\")\r\n\r\ndef polymer_reduction(polymer):\r\n\twhile True:\r\n\t\tlen_before = len(polymer)\r\n\t\tfor ch in range(ord(\"a\"),ord(\"z\")+1):\r\n\t\t\tpolymer = reduce(polymer,chr(ch))\r\n\t\tif(len(polymer)==len_before):\r\n\t\t\treturn polymer\r\n\r\nreduced_length = len(polymer_reduction(full_input))\r\n\r\nprint(f\"pt1: {reduced_length}\")\r\n\r\n# pt2\r\n\r\nmin_length = reduced_length\r\n\r\nfor ch in range(ord(\"a\"),ord(\"z\")+1):\r\n\tchar_stripped_polymer = full_input.replace(chr(ch),\"\").replace(chr(ch).upper(),\"\")\r\n\tchar_stripped_reduced = polymer_reduction(char_stripped_polymer)\r\n\tif(len(char_stripped_reduced) < min_length):\r\n\t\tmin_length = len(char_stripped_reduced)\r\n\r\nprint(f\"pt2: {min_length}\")\r\n\r\n","sub_path":"day5.py","file_name":"day5.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"23607691","text":"from django.conf.urls.defaults import *\nfrom django.views.generic import TemplateView\nfrom tastypie.api import Api\nfrom cart.resources import SocialCartResource, PersonalCartResource\nfrom cart import views\n\n\nv1_api = Api(api_name='v1')\nv1_api.register(SocialCartResource())\nv1_api.register(PersonalCartResource())\n\nurlpatterns = patterns('',\n (r'^api/', include(v1_api.urls)),\n\n url(r'^social_mockup/$', TemplateView.as_view(template_name='cart/social_mockup.j.html')),\n\n url(r'^personal/$', views.personal_cart, name='cart.personal_cart'),\n url(r'^social/$', views.social_cart, name='cart.social_cart'),\n\n url(r'^preview_social_cart/$', views.preview_social_cart, name='cart.preview_social_cart'),\n url(r'^preview_personal_cart/$', views.preview_personal_cart, name='cart.preview_personal_cart'),\n\n url(r'^approve_social_cart/$', views.approve_cart, { 'cart': 'social' }, name='cart.approve_social_cart'),\n url(r'^approve_personal_cart/$', views.approve_cart, { 'cart': 'personal' }, name='cart.approve_personal_cart'),\n\n url(r'^cancel_pending_transaction/$', views.cancel_pending_transaction, name='cart.cancel_pending_transaction'),\n\n #url(r'^approved/$', views.approved_tags, name='cart.approved_tags'),\n)\n","sub_path":"apps/cart/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"43876309","text":"#!/usr/bin/env python3.6\n# Daydreamer.py\n# Author: Shawn Beaulieu\n# August 7th, 2018\n\n\nfrom Daydreamer import Daydreamer\n\ndef main():\n\n\n params = {\n\n 'render': True,\n 'phi_length': 4,\n 'epochs': 20,\n 'environments': {0:'MontezumaRevenge-v0', 1:'Frostbite-v0'},\n 'latent_dim': 32,\n 'gamma': 0.9,\n 'epsilon': 1.0,\n 'action_space': 18,\n 'vae_params': {\n\n 'blueprint': [84*84, 200, 100, 32], #105*80 after flattening\n 'convolutions': 0,\n \"batch_size\": 4000,\n \"regularizer\": 1E-6,\n \"learning_rate\": 3E-4,\n \"dropout\": True,\n \"dropout_rate\": 0.50,\n \"num_classes\": 0\n\n }\n\n }\n\n Daydreamer(params)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Run_Daydreamer.py","file_name":"Run_Daydreamer.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"20741505","text":"_base_ = [\n '../_base_/datasets/imagenet_bs64_swin_224.py',\n '../_base_/schedules/imagenet_bs1024_adamw_swin.py',\n '../_base_/default_runtime.py',\n]\n\nmodel = dict(\n type='ImageClassifier',\n backbone=dict(\n type='XCiT',\n patch_size=8,\n embed_dims=512,\n depth=24,\n num_heads=8,\n mlp_ratio=4,\n qkv_bias=True,\n layer_scale_init_value=1e-5,\n tokens_norm=True,\n out_type='cls_token',\n ),\n head=dict(\n type='LinearClsHead',\n num_classes=1000,\n in_channels=512,\n loss=dict(type='CrossEntropyLoss', loss_weight=1.0),\n ),\n train_cfg=dict(augments=[\n dict(type='Mixup', alpha=0.8),\n dict(type='CutMix', alpha=1.0),\n ]),\n)\n\n# dataset settings\ntrain_dataloader = dict(batch_size=128)\n","sub_path":"configs/xcit/xcit-medium-24-p8_8xb128_in1k.py","file_name":"xcit-medium-24-p8_8xb128_in1k.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"438483641","text":"import heapq\ndef djikstra(graph,start,final,n):\n costs = {}\n pq = []\n heapq.heappush(pq,(0,start))\n while pq:\n cur_cost , cur_v = heapq.heappop(pq)\n if costs[cur_v] < cur_cost:\n continue\n if cur_v not in costs:\n costs[cur_v] = cur_cost\n for cost, next_v in graph[cur_v]:\n next_cost = cur_cost + cost\n heapq.heappush(pq,(next_cost,next_v))\n \n if len(costs) == start:\n return costs[final]\n else:\n return -1","sub_path":"DataStructures/Priority_Queue_and_HEAP/dijkstra.py","file_name":"dijkstra.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"25187883","text":"main = input('Please enter a number: ')\ni = len(main)\ntry:\n main = int(main)\n calc = []\n a = 0\n while i != 1:\n a = (main // 10 ** (i-1)) % 10\n calc.append(a)\n i -= 1\n b = main % 10\n calc.append(b)\n print(max(calc))\nexcept ValueError:\n print('Number should be entered')\n\n\n","sub_path":"lesson_1/lesson1_task4.py","file_name":"lesson1_task4.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"114084740","text":"from vedo import *\n\nman = Mesh(dataurl+'man.vtk').c('k9').lighting('glossy')\nfloor = Box(length=9, width=9, height=0.1).z(-1.6).c('white')\ncube = Cube().pos(2,-2,-0.4)\n\np1 = Point([1,0,1], c='red5')\np2 = Point([0,1,2], c='green5')\np3 = Point([-1,-0.5,1], c='blue5')\n\n# Add light sources at the given positions\nl1 = Light(p1)\nl2 = Light(p2)\nl3 = Light(p3)\n\nplt = Plotter(bg='blackboard')\nplt.addShadows()\nplt.show(man, floor, cube, l1, l2, l3, p1, p2, p3)\n\n\n\n","sub_path":"examples/basic/shadow2.py","file_name":"shadow2.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"72051522","text":"\"\"\"\nPlace news articles into the following 7 categories:\n\n Society (includes Politics, Elections, Legislation, Incidents, Crime)\n Economy (includes Markets, Finance, Business)\n Technology (includes Gadgets, Auto, Apps, Internet services)\n Sports (includes E-Sports)\n Entertainment (includes Movies, Music, Games, Books, Arts)\n Science (includes Health, Biology, Physics, Genetics)\n Other (news articles that don't fall into any of the above categories)\nFake implementation\n\"\"\"\nimport random\nfrom tgnews.etl import get_file\n\ndef category(file):\n\n return random.choice([\"society\", \"economy\", \"technology\", \"sports\", \n \"entertainment\", \"science\", \"other\"])\n\n\ndef categories(file_list):\n\n category_list = {\n \"society\": [],\n \"economy\": [],\n \"technology\": [],\n \"sports\": [],\n \"entertainment\": [],\n \"science\": [],\n \"other\": []\n }\n\n for f in file_list:\n\n file = get_file(f)\n cat = category(file)\n\n category_list[cat].append(f)\n\n return category_list\n","sub_path":"tgnews/categories.py","file_name":"categories.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"564508626","text":"if __name__ != \"__main__\":\n # importing module\n from ciphers.Caesar import Caesar\n from ciphers.Vigenere import Vigenere\n\nelse:\n # __name__ == \"__main__\"\n from Caesar import Caesar\n from Vigenere import Vigenere\n import random\n\n print(\"String to be encrypted:\", \"--------------------------------\", sep='\\n')\n _data = \"Lorem ipsum dolor sit amet enim.\"\n print(_data, \"\\n\")\n\n caesar_offset = random.randint(0, 26)\n print(\"Caesar: %d\" % caesar_offset, \"--------------------------------\", sep='\\n')\n caesar_encrypted = Caesar.encrypt(_data, caesar_offset, original=True)\n caesar_decrypted = Caesar.decrypt(caesar_encrypted, caesar_offset, original=True)\n print(caesar_encrypted, caesar_decrypted, \"\", sep='\\n')\n\n vigenere_key = \"secret_key\"\n print(\"Vigenere: %s\" % vigenere_key, \"--------------------------------\", sep='\\n')\n vigenere_encrypted = Vigenere.encrypt(_data, vigenere_key, original=True)\n vigenere_decrypted = Vigenere.decrypt(vigenere_encrypted, vigenere_key, original=True)\n print(vigenere_encrypted, vigenere_decrypted, \"\", sep='\\n')\n","sub_path":"ciphers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"486918470","text":"# -*- encoding: utf-8 -*-\nfrom grab import Grab\nimport codecs\ng = Grab(log_file='out.html')\nfrom newspaper import Article\nfrom bs4 import BeautifulSoup\nimport re\nimport csv\nimport io\nimport gzip\nimport unicodedata as ucd\nimport sys\n\n#----------------------------------------------------------------\n\nsearch=\"Банан\"\n\n#----------------------------------------------------------------\n\n\n#file=open('C:\\\\Users\\\\USK\\\\Desktop\\\\aa\\\\parser\\\\out.txt','r')\n#e=list()\n#for i in file:\n# e.append(i.strip('\\n'))\n#e.pop(0)\n#d=dict()\n#for i in e:\n# d[i.split(':')[0]]=i.split(':')[1]\n \n#file.close()\n\n\n\n\n#sr=d['q']\npop=''\nurl='https://news.yandex.kz/yandsearch?text='+search+'+'+pop+'&rpt=nnews2&grhow=clutop'+'&p='\na=list()\n\n\nfor i in range(0,10):\n try:\n g.go(url+str(i))\n print(url+str(i))\n #g.doc.set_input(\"q\",\"grab\")\n #g.doc.submit(submit_name = 'btnK')\n #print g.doc.select('//head/title').text()\n\n for el in g.doc.select('//li[@class=\"search-item\"]'):\n soup=BeautifulSoup(el.html(),'lxml')\n for link in soup.findAll('a', attrs={'href': re.compile(\"^http://\")}):\n a.append(link.get('href'))\n except:\n break\n\nd=dict()\nc=0\nprint('---------------------------------')\n#from Com import Com\nr=list()\nwith codecs.open(\"withnewspaper.csv\", \"w\", \"utf-8\") as file:\n file.write('publishedAt,title,author,url,urlToImage,description,comments'+'\\r\\n')\n for i in a:\n print(i)\n url = i\n article = Article(url)\n article.download()\n article.parse()\n # p=Com(url)\n #print(p.get_comment)\n title=article.title\n authors=article.authors\n publish_date=article.publish_date\n text=article.text\n top_image=article.top_image\n '''print(type(title.encode('UTF-8')))\n print(type(authors))\n print(type(str(publish_date)))\n print(type(text))\n print(type(top_image))'''\n html=(article.html)\n soup = BeautifulSoup(html,'lxml')\n p=\"\"\n try:\n soup=(soup.find('div', {'id':'comments'}))\n data = soup.findAll(text=True)\n \n for i in (data):\n p+=(i.strip())+':'\n\n except:\n p= (\"None\")\n if(len(str(publish_date))>0):\n file.write(str(publish_date)+',')\n file.write(title+',')\n file.write(' '.join([str(x) for x in authors])+ ',')\n file.write(i+',')\n file.write(top_image+',')\n file.write(text+',')\n file.write(p)\n file.write('\\r\\n')\n\n\n \n \n \n\n\n\n\n\n '''print title\n print authors\n print publish_date\n print text\n print top_image'''\n \n '''if title!=None:\n r.append({'title':title})\n else:\n r.append({'title':''})\n \n if publish_date!=None:\n r.append({'publishedAt':publish_date})\n else:\n r.append({'publishedAt':''})\n \n if authors!=None:\n r.append({'author':authors})\n else:\n r.append({'author':''})\n \n if top_image!=None:\n r.append({'urlToImage':top_image})\n else:\n r.append({'urlToImage':''})\n \n if text!=None:\n r.append({'description':(text)})\n else:\n r.append({'description':''})\n r.append({'url':i})'''\n '''try:\n if(publish_date!=None):\n file.write(publish_date)\n file.write(',')\n if(len(title)>0):\n file.write(title)\n file.write(',')\n if(authors!=None):\n file.write(authors)\n file.write(',')\n file.write(str(i))\n file.write(',')\n if(top_image!=None):\n file.write(top_image)\n file.write(',')\n if(text!=None):\n file.write(text)\n file.write('\\n')\n except:\n file.write('\\n')'''\n \n \n \n \n\n \n #print \"----------------\"\n\n #writer.writerow(({'publishedAt': str(article.publish_date), 'title': str(article.title), 'author': str(article.authors), 'url': i, 'urlToImage': str(article.top_image), 'description': str(article.text) }))\n #writer.write( article.publish_date, article.title, article.authors, i, article.top_image, article.text,\"\\n\" )\n \n \n","sub_path":"Parser with Newspaper and Grab/yandexwithnewspaper.py","file_name":"yandexwithnewspaper.py","file_ext":"py","file_size_in_byte":4295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"625668985","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Topic, Timer\nfrom .services import register_user_topic, is_topic_occupied, is_registration_open\nfrom .exceptions import NoStudentError, OccupiedTopicError, RegistrationClosedError\nfrom django.contrib import messages\n\n\n@login_required(login_url='/users/login/')\ndef topic_registration(request):\n topic_name_list = []\n for topic in Topic.objects.filter(professor=request.user.professor):\n occupied, by_current_user = is_topic_occupied(request.user, topic)\n topic_name_list.append((topic.name, occupied, by_current_user))\n timer = Timer.objects.first()\n context = {\n 'topic_name_list': topic_name_list,\n 'start_date': timer.start_date.strftime(\"%Y-%m-%d %H:%M\"),\n 'end_date': timer.end_date.strftime(\"%Y-%m-%d %H:%M\")\n }\n return render(request, 'topic_registration/topic_registration.html', context)\n\n\n@login_required(login_url='/users/login/')\ndef topic_register(request):\n try:\n if not is_registration_open():\n raise RegistrationClosedError\n selected_topic = request.POST['topic']\n register_user_topic(request.user, selected_topic)\n messages.success(request, 'Rejestracja zakonczona pomyslnie')\n except KeyError:\n messages.error(request, 'Nie wybrano tematu')\n except NoStudentError:\n messages.error(request, 'Tylko student moze zarejestrowac temat')\n except OccupiedTopicError:\n messages.error(request, 'Wybrany temat jest juz zarezerwowany')\n except RegistrationClosedError:\n messages.error(request, 'Rejestracja jest zamknieta')\n except Exception:\n messages.error(request, 'Nieoczekiwany blad')\n return redirect('topic_registration:topic_registration')\n","sub_path":"topic_registration/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"267593509","text":"from pathlib import Path\n\ntry:\n from tqdm.auto import tqdm\nexcept ModuleNotFoundError:\n tqdm = list\n\nroot_path = Path(__file__) / \"..\"\nroot_path = root_path.resolve()\n\nsrc_file = root_path / \"russian.txt\"\nout_file = root_path / \"russian_utf-8.txt\"\n\nif out_file.exists():\n out_file.unlink()\n\nwith src_file.open(\"r\", encoding=\"windows-1251\") as src, out_file.open(\"w\", encoding=\"utf-8\") as out:\n for line in tqdm(src.readlines()):\n line = line.strip(\"- \\n\")\n out.write(line + \"\\n\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"569454178","text":"from collections import deque\r\nfrom typing import List\r\n\r\n\r\nclass Solution:\r\n def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:\r\n if not nums:\r\n return []\r\n\r\n ans = []\r\n # 单调双向队列,从左到右递减,存储数的下标\r\n q = deque()\r\n for i in range(len(nums)):\r\n # 移除队列右边所有不大于当前数的item\r\n while len(q) > 0 and nums[i] >= nums[q[-1]]:\r\n q.pop()\r\n # 队列右边添加当前数的索引\r\n q.append(i)\r\n # 如果队列左边的下标(对应滑动窗口的最大值)位于滑动窗口外,则移除它\r\n if i - k >= q[0]:\r\n q.popleft()\r\n # 添加当前的最大值到结果集中\r\n if i >= k - 1:\r\n ans.append(nums[q[0]])\r\n return ans\r\n","sub_path":"0239. Sliding Window Maximum/solution_deque.py","file_name":"solution_deque.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"366011559","text":"\"\"\"Send a slack notification.\"\"\"\n# coding: utf-8\n\nfrom slacker import Slacker\nimport envdir\nimport os\nimport tempfile\n\nfrom . import constants as c\n\n\nslack = None\nDON = '@dmmfll'\n\n\ndef get_slack_client():\n \"\"\"Slack client.\"\"\"\n global slack\n if slack is None:\n envdir.open(os.path.expanduser('/home/dmmmd/slack_envdir/'))\n token = os.environ['WYNCODE']\n slack = Slacker(token)\n return slack\n\n\ndef send_notification(message='test message', recipient=DON, as_user=True):\n \"\"\"Send slack message to me.\n\n If kwarg username is added, it is the name of the bot. as_user has to\n then be False.\n\n \"\"\"\n slack = get_slack_client()\n slack.chat.post_message(recipient, message, as_user=as_user)\n\n\ndef search_for_id(first, last):\n \"\"\"Search for slack user id from first, last.\n\n :returns: slack_id\n \"\"\"\n slack = get_slack_client()\n response = slack.users.list()\n members = response.body['members']\n slack_ids = tuple(member['name']\n for member in members\n if all(name_.lower()\n in member['profile']['real_name'].lower()\n for name_ in (first, last)))\n return slack_ids\n\n\ndef upload_grading_markdown(resources, content, recipient=DON):\n \"\"\"Post a file to a channel.\n\n :returns: response\n \"\"\"\n slack = get_slack_client()\n keys = (\n 'content',\n 'filetype',\n 'filename',\n 'title',\n 'initial_comment',\n 'channels'\n )\n values = [\n c.MD,\n c.DOT.join(('{}', c.MD)),\n 'Copy of Good Measure comments for {}',\n 'I graded the homework exercise _{}_',\n recipient,\n ]\n values = [item.format(\n resources\n .config['question'][c.TEXT].split(c.CR)[c.LAST]) or None\n for item in values]\n values.insert(c.FIRST, content) # can't format content has {}\n assert len(keys) == len(values)\n data = dict(zip(keys, values))\n # filepath = tempfile.NamedTemporaryFile(delete=False).name\n\n tmp = tempfile.NamedTemporaryFile(delete=False).name\n return slack.files.upload(tmp, **data)\n\n\ndef upload_grading_pdf(resources, filepath, recipient=DON):\n \"\"\"Post a file to a channel.\n\n :returns: response\n \"\"\"\n slack = get_slack_client()\n keys = (\n 'filetype',\n 'title',\n 'initial_comment',\n 'channels'\n )\n values = [\n c.PDF,\n 'Copy of Good Measure comments for {}',\n 'I graded the homework exercise _{}_',\n recipient,\n ]\n values = [item.format(\n resources\n .config['question'][c.TEXT].split(c.CR)[c.LAST]) or None\n for item in values]\n data = dict(zip(keys, values))\n\n return slack.files.upload(filepath, **data)\n\n\ndef main():\n \"\"\"Main.\"\"\"\n send_notification()\n return 0\n","sub_path":"goodmeasure_cli/slack_notification.py","file_name":"slack_notification.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"225438875","text":"import visualization\nimport xyPlot\nimport displayGroupOdbToolset as dgo\nimport os, glob, inspect\nimport sys\nsys.path.append('C:\\\\Users\\\\doktor\\\\PycharmProjects\\\\InputFilesBuild')\nimport globalPar as gp\n\nreload(gp)\n\ndef write_to_files(line, dispFiles):\n if isinstance(dispFiles, list):\n for file in dispFiles:\n file.write(line)\n else:\n dispFiles.write(line)\n\ndef write_header(dispFiles):\n # Header - only on file initialization\n line_with_param = 'id' + semicolon + 'delta' + semicolon + 'alpha' + semicolon + 'velocity' + semicolon + 'time' \\\n + semicolon + 's' + semicolon + 'Tm' + semicolon + 'm'\n write_to_files(line_with_param, dispFiles)\n\n # Header - only on file initialization\n for key in odbLabels.keys():\n if not odbLabels[key]['labels']:\n line = semicolon + str(key)\n write_to_files(line, dispFiles)\n\n else:\n for label in odbLabels[key]['labels']:\n line = semicolon + str(label)\n write_to_files(line, dispFiles)\n\ndef close_files(dispFiles):\n for file in dispFiles:\n file.close()\n\npc = gp.ParametersClass()\nsemicolon = ';'\ncomma = ','\n\npath = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) +'\\\\workingDirectory\\\\'\nos.chdir(path)\n\ngp.scandirs(path)\n\n\n# DispFiles\nfilenames=['vumat_approx.csv']\ndispFiles=[open(filenames[0], 'a')] #dispFiles=[open(filenames[0], 'a'), open(filenames[1], 'a')]\n\n# Reading ODB Labels - for that one of the ODB files has to be open\nfile = glob.glob(\"*.odb\")[0]\no1 = session.openOdb(name=path + file)\nodb = session.odbs[path + file]\nstep = odb.steps['Step-1']\n\nodbLabels = gp.get_labels(step)\nodb.close()\n\n# Writing Header\nfor df in dispFiles:\n try:\n if os.stat(df.name).st_size == 0:\n write_header(df)\n except OSError as e:\n print(e)\n\n\nfor file in glob.glob(\"*.odb\"):\n print('Opening file: {0}'.format(file))\n o1 = session.openOdb(name=path + file)\n odb = session.odbs[path + file]\n step = odb.steps['Step-1']\n\n #odbLabels = gp.get_labels(step)\n\n # Data rows\n alpha, Tm, m, velocity_m_s, Dxx = gp.get_additional_parameters_ext(file)\n time = pc.s / (float(velocity_m_s) * 1000) ##velocity in mm/s\n print('Retrieving data for: alpha = {0}, Tm = {1}, m = {2}, vel = {3}, Dxx = {4}'.format(alpha, Tm, m, velocity_m_s, Dxx))\n for id, frame in enumerate(step.frames):\n line ='\\n' + str(id) + semicolon + str(Dxx) + semicolon + str(alpha) + semicolon + str(velocity_m_s) \\\n + semicolon + str(time) + semicolon + str(pc.s) + semicolon + str(Tm) + semicolon + str(m)\n write_to_files(line, dispFiles)\n\n for key in odbLabels.keys():\n if not odbLabels[key]['labels']:\n line = semicolon + str(frame.fieldOutputs[key].values[0].data)\n write_to_files(line, dispFiles)\n\n else:\n for label in odbLabels[key]['labels']:\n if key == 'S':\n line = semicolon + str(frame.fieldOutputs[key].getScalarField(componentLabel=label).values[0].data)\n write_to_files(line, dispFiles)\n else:\n line = semicolon + str(frame.fieldOutputs[key].getScalarField(componentLabel=label).values[7].data)\n write_to_files(line, dispFiles)\n odb.close()\n print('Done.')\n\nclose_files(dispFiles)","sub_path":"3_2_abaqus_OdbReader.py","file_name":"3_2_abaqus_OdbReader.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"615865607","text":"import datetime\r\nfrom scapy.all import *\r\n\r\nPACKETS_TO_SNIFF = 32\r\nLOG_PATH = 'Log.txt'\r\nRESOURCES_PATH = 'resources/'\r\nIP_BLACKLIST_PATH = RESOURCES_PATH + 'ip_blacklist.txt'\r\nFILES_BLACKLIST_PATH = RESOURCES_PATH + 'files_blacklist.txt'\r\nURL_BLACKLIST_PATH = RESOURCES_PATH + 'url_blacklist.txt'\r\n\r\n\r\n\r\nclass firewall:\r\n\tdef __init__(self):\r\n\t\tself.log = open(LOG_PATH, 'a+')\r\n\t\tself.ip_black_list = ['']\r\n\t\tself.url_black_list = ['']\r\n\t\tself.file_black_list = ['']\r\n\t\twith open(IP_BLACKLIST_PATH, 'r') as ip_file:\r\n\t\t\tself.ip_black_list = [line.rstrip('\\n') for line in ip_file]\r\n\t\twith open(URL_BLACKLIST_PATH, 'r') as url_file:\r\n\t\t\tself.url_black_list = [line.rstrip('\\n') for line in url_file]\r\n\t\twith open(FILES_BLACKLIST_PATH, 'r') as files_file:\r\n\t\t\tself.file_black_list = [line.rstrip('\\n') for line in files_file]\r\n\r\n\r\n\tdef cheack_packet(self, packet):\r\n\t\tself.compare_to_blacklist(packet)\r\n\r\n\r\n\tdef compare_to_blacklist(self, packet):\r\n\r\n\t\tif IP in packet:\r\n\t\t\tif packet[IP].src in self.ip_black_list:\r\n\t\t\t\tself.log.write('%s\\nsuspicous ip source\\nsource:\\t%s\\tdestination:\\t%s\\t%s\\n\\n' \r\n\t\t\t\t\t% (str(datetime.datetime.now()), packet[IP].src, packet[IP].dst, packet.summary()))\r\n\t\t\tif packet[IP].dst in self.ip_black_list:\r\n\t\t\t\tself.log.write('%s\\nsuspicous ip destination\\nsource:\\t%s\\tdestination:\\t%s\\t%s\\n\\n' \r\n\t\t\t\t\t% (str(datetime.datetime.now()), packet[IP].src, packet[IP].dst, packet.summary()))\r\n\r\n\r\n\t\tself.log.flush()\r\n\r\n\tdef check_syn_flood(self, capture_list):\r\n\t\t\"\"\" CODE \"\"\"\r\n\t\tpass\r\n\r\n\tdef firewall_run(self): \r\n\t\ttime_text = \"\\nbegan snnifing at:\\t%s\\n\\n\" % str(datetime.datetime.now())\r\n\t\tself.log.write(time_text)\r\n\t\tself.log.flush()\r\n\t\twhile True:\r\n\t\t\tsniff(PACKETS_TO_SNIFF, prn=self.cheack_packet)\r\n\r\n\r\ndef main():\r\n\tmain_firewall = firewall()\r\n\tmain_firewall.firewall_run()\r\n\r\n\r\nif __name__ == '__main__':\r\n\tmain()","sub_path":"End_Project.py","file_name":"End_Project.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"470425299","text":"\"\"\"Routines for running Edward's spectrometer using the Leiker/Force\nI/O card for Raspberry Pis\"\"\"\n#from threading import Thread, Lock\n#lck = Lock()\nfrom scipy.optimize import curve_fit\n#execfile(\"spectrometer.py\")\nfrom spectrometer import *\nimport os\n\nclass SignalGenerator:\n \"\"\"Routines for use with the Hittite syntesizer\n frequencies in MHz and power in dBm\"\"\"\n def __init__(self, ipAddress=\"192.168.0.70\"):\n self.lanio = \"lanio \" + ipAddress + \" \"\n self.freq = 0.0\n\n def setFreq(self, freq):\n \"\"\"Set the signal generator frequency in MHz\"\"\"\n os.system(self.lanio + \"\\\":FREQ \" + str(freq) + \" MHz\\\"\")\n self.freq = freq\n\n def getFreq(self):\n \"\"\"Get the signal generator frequency in MHz\"\"\"\n return float(os.popen(self.lanio + \"\\\"FREQ?\\\"\").read()) / 1000000\n\n def setPower(self, pwr):\n \"\"\"Set the signal generator power in dBm. \n With the Httite, stay above -42 dBm\"\"\"\n\n os.system(self.lanio + \"\\\":POW \" + str(pwr) + \" dBm\\\"\")\n os.system(self.lanio + \"\\\":OUTP 1\\\"\")\n\n def powerOff(self):\n os.system(self.lanio + \"\\\":OUTP 0\\\"\")\n\n def getPower(self):\n return os.system(self.lanio + \"\\\"POW?\\\"\")\n\nclass TestSpectrometer:\n def __init__(self,spec):\n self.spec = spec\n self.attenVals = np.zeros(32)\n self.zeroFit = np.array([0.0,0.0])\n\n def scanAtten(self, attenNumber = 0):\n \"\"\" Scan the attenuator over its range and measure the power at the peak\"\"\"\n for i in range(32):\n self.spec.setAtten(i)\n self.spec.sweep()\n ch0 = np.argmax(spec.vals)\n self.attenVals[i] = np.sum(self.spec.vals[ch0-1:ch0+2]-self.spec.zeros[ch0-1:ch0+2])\n# self.attenVals[i] = max(self.spec.vals)\n print(\"%d %d\" % (i, self.attenVals[i]))\n plt.plot(np.arange(15.5, -0.1, -0.5), 10*(np.log10(self.attenVals)- np.log10(32768)))\n plt.xlabel(\"Attenuation\")\n plt.ylabel(\"Max Signal (dB-full Scale)\")\n plt.title(\"Spectormeter %d's attenuator\" %(attenNumber))\n plt.show(block = False)\n \n def gaussian(self, x, amp, cen, wid):\n return amp * np.exp(-(((x-cen)/wid)**2) /2)\n \n def measureFilter(self, freq=10, power = -38, plot=True):\n \"\"\"Measure the yig fiklter response by doing 5 scans offset by 5MHz\n to get a more accurate measurement\"\"\"\n numPoints=7\n numFreqs=5\n vals = np.zeros(numPoints*numFreqs, dtype=np.int16)\n freqs = np.zeros(numPoints*numFreqs, dtype=float)\n savefStart = self.spec.fStart\n sg.setFreq(freq*1000)\n sg.powerOff()\n self.spec.sweep()\n zeros=np.copy(self.spec.vals)\n sg.setPower(power)\n for n in range(numFreqs):\n self.spec.fStart = savefStart + n* self.spec.df/numFreqs\n self.spec.sweep()\n if n == 0:\n ch0 = np.argmax(self.spec.vals) - int(numPoints/2)\n zero = np.average(zeros[ch0:ch0+numPoints])\n vals[n: numPoints*numFreqs:numFreqs] = self.spec.vals[ch0:ch0+numPoints] - zero\n freqs[n: numPoints*numFreqs:numFreqs] = self.spec.freqs[ch0:ch0+numPoints]\n self.spec.fStart=savefStart\n ch0 = np.argmax(vals)\n init_vals = [vals[ch0], freqs[ch0], .012]\n [amp, ctr, wid], covar = curve_fit(self.gaussian, freqs, vals, p0=init_vals)\n if plot:\n print(\"amp %d ctr %.4f, wid %.4f\" % (amp, ctr, wid))\n plt.plot(freqs, vals, label = \"measured data\")\n plt.plot(freqs, self.gaussian(freqs, amp, ctr, wid), label = \"Gaussian fit\")\n plt.legend()\n plt.show(block=False)\n else:\n return((freq, amp, ctr, wid))\n # np.savetxt('filter.txt', np.c_[freqs, vals], fmt = \"%.3f %d\")\n # print np.c_[freqs, vals,]\n \n def measureFrequencyScale(self, fStart=4.5, fStop=16.1, df=1):\n \"\"\" Measure the yig filter's response to a series of frequencies.\n Print frequency, amplitude, measured center freq and sigma of a gaussian\n fit. save in the file \"yigMeasurements\" in the current directory.\n Solve for a linear fit to the measured frequencies and suggest changes\n to the file yigConstants for the current spectrometer.\"\"\"\n\n d = []\n for f in np.arange(fStart, fStop, df):\n v = self.measureFilter(f, plot=False)\n d.append(v)\n print(\"%.2f %d %.4f %.5f\" % (v[0],v[1], v[2], v[3]))\n dt = np.array(d).transpose()\n coef = np.polyfit(dt[0], dt[2], 1)\n print(coef)\n print(\"change yig.freqOffset from %.4f to %.4f\" % (yig.freqOffset, yig.freqOffset-coef[1]))\n print(\"change yig.scaleFactor from %.5f to %.5f\" % (yig.scaleFactor, yig.scaleFactor/coef[0]))\n np.savetxt(\"yigMeasurements\", d, \"%.2f %d %.4f %.5f\")\n\n def showPeak(self):\n ch = np.argmax(self.spec.vals)\n print(\"The peak is %d at %.3f GHz\" % (self.spec.vals[ch], self.spec.freqs[ch]))\n \n# def runTwo():\n# print time.time()\n# p0 = mp.Process(target=self.spec0.main)\n# p1 = mp.Process(target=self.spec1.main)\n# p0.start()\n# p1.start()\n# print time.time()\n\n def hot(self, numInts = 1):\n self.spec.sweep()\n self.hotVals = np.array(self.spec.vals)\n if numInts > 1:\n for i in range(numInts-1):\n self.spec.sweep()\n self.hotVals += self.spec.vals\n# print \"i =%d val = %d hotVal = %d\" % (i, self.spec.vals[0], self.hotVals[0])\n self.hotVals /= numInts\n self.hotVals -= self.spec.zeros\n if self.spec.doPlot:\n plt.clf()\n plt.plot(self.spec.freqs, self.hotVals)\n plt.show(block = False)\n\n def cold(self, numInts = 1):\n self.spec.sweep()\n self.coldVals = np.array(self.spec.vals)\n if numInts > 1:\n for i in range(numInts-1):\n self.spec.sweep()\n self.coldVals += self.spec.vals\n# print \"i =%d val = %d coldVal = %d\" % (i, self.spec.vals[240], self.coldVals[240])\n self.coldVals /= numInts\n self.coldVals -= self.spec.zeros\n if self.spec.doPlot:\n plt.plot(self.spec.freqs, self.coldVals)\n plt.show(block = False)\n \n def zero(self):\n avg = np.zeros(self.spec.nSamp)\n \n for i in range(5):\n self.spec.sweep()\n avg += self.spec.vals\n avg /= 5\n self.zeroFit = np.polyfit(self.spec.freqs[20:],avg[20:],1)\n self.spec.zeros = np.polyval(self.zeroFit, self.spec.freqs)\n if self.spec.doPlot:\n plt.plot(self.spec.freqs,avg, self.spec.freqs, self.spec.zeros)\n plt.show(block = False)\n print(\"Fit const = %.1f slope %.2f std = %.2f\" % \\\n ( self.zeroFit[1], self.zeroFit[0], np.std(avg-self.spec.zeros)))\n \n def saveZero(self, fname=\"zeroParams\"):\n fn = '/instance/configFiles/' + fname + ( \"%d\" % (self.spec.number))\n# fd = open(fn, 'w')\n# fd.write(\"%.3f %.3f\" % (test.zeroFit[0], self.zeroFit[1]))\n np.savetxt(fn, self.zeroFit, \"%.3f\")\n\n def readZero(self, fname=\"zeroParams\"):\n fn = '/instance/configFiles/' + fname + ( \"%d\" % (self.spec.number))\n# fn = \"/home/smauser/\"+fname+\"%d\" % (self.spec.number)\n# fd = open(fn, 'r')\n self.zeroFit = np.genfromtxt(fn)\n freq = self.spec.fStart\n for i in range(self.spec.nSamp):\n self.spec.freqs[i] = freq\n freq += self.spec.df\n self.spec.zeros = np.polyval(self.zeroFit, self.spec.freqs)\n\n def Y(self, fname=\"Y.txt\"):\n Y = (self.hotVals)/(self.coldVals)\n np.savetxt(fname, np.c_[self.spec.freqs, self.hotVals, self.coldVals, Y], fmt = \"%.3f %d %d %.3f\")\n if self.spec.doPlot:\n plt.clf()\n plt.plot(self.spec.freqs, Y)\n plt.draw()\n","sub_path":"online/Linux/applications/pi/ScanningSpectrometer/test_spectrometer.py","file_name":"test_spectrometer.py","file_ext":"py","file_size_in_byte":7226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"486587132","text":"#!/usr/bin/python\nimport argparse, os, tempfile, shutil, sys,math,pickle,itertools\nfrom subprocess import call, PIPE, STDOUT, Popen\nimport argparse\nimport datetime\nimport os\nparser = argparse.ArgumentParser(description='Submit job to batch')\nparser.add_argument('--config_file',type=str,dest=\"config_file\",default=1, help=\" config_file of the era\")\nparser.add_argument('--outputname',type=str,dest=\"outputname\",default=1, help=\"Run era\")\nparser.add_argument('--list',type=str,dest=\"list\",default=1, help=\"list of file to run\")\nparser.add_argument('--dirlist',type=str,dest=\"dirlist\",default=1, help=\"directory where are lists of file to run\")\nargs = parser.parse_args()\nconfig_file = args.config_file #path to the processed lumi JSON file\noutputname = args.outputname # which run\nlisttorun = args.list\ndirlist = args.dirlist\noutputdir = \"/eos/user/${USER:0:1}/$USER/JEC-task/HT_Condor_output/DijetRootTreeAnalyzer/\"+dirlist+'/'+datetime.date.today().isoformat()+'/'\ncmd4=\"./main \"+dirlist+listtorun+\" \"+config_file+\" dijets/events \"+outputdir+outputname+\" \"+outputdir+outputname\ncmd1=\"cd /afs/cern.ch/work/${USER:0:1}/$USER/JEC-task/CMSSW_8_0_31/src/CMSDIJET/DijetRootTreeAnalyzer/\"\ncmd2=\"export SCRAM_ARCH=slc6_amd64_gcc530\"\ncmd3=\"eval `scramv1 runtime -sh`\"\ncmd5=\"export X509_USER_PROXY=/afs/cern.ch/user/${USER:0:1}/$USER/.globus/gridproxy.cert\" \ncall(\"mkdir -p \"+outputdir+\" && \"+cmd1+\" && \"+cmd5+\" && \"+cmd2+\" && \"+cmd3+\" && \"+cmd4, shell=True )\nprint(cmd4)\n\n","sub_path":"Run_Analyser_short.py","file_name":"Run_Analyser_short.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"138282039","text":"import cv2\nimport RobotRaconteur as RR\nRRN = RR.RobotRaconteurNode.s\nimport RobotRaconteurCompanion as RRC\nimport argparse\nimport sys\nimport platform\nimport threading\nimport numpy as np\nfrom RobotRaconteurCompanion.Util.InfoFileLoader import InfoFileLoader\nfrom RobotRaconteurCompanion.Util.DateTimeUtil import DateTimeUtil\nfrom RobotRaconteurCompanion.Util.SensorDataUtil import SensorDataUtil\nfrom RobotRaconteurCompanion.Util.AttributesUtil import AttributesUtil\n\n\nclass CameraImpl(object):\n \n def __init__(self, device_id, width, height, fps, camera_info):\n \n #if platform.system() == \"Windows\":\n # self._capture = cv2.VideoCapture(device_id + cv2.CAP_DSHOW)\n #else:\n self._capture = cv2.VideoCapture(device_id)\n assert self._capture.isOpened(), f\"Could not open device: {device_id}\"\n\n self._seqno = 0\n\n self._capture.set(cv2.CAP_PROP_FRAME_WIDTH, width)\n self._capture.set(cv2.CAP_PROP_FRAME_HEIGHT, height)\n self._capture.set(cv2.CAP_PROP_FPS, fps)\n\n self._imaging_consts = RRN.GetConstants('com.robotraconteur.imaging')\n self._image_consts = RRN.GetConstants('com.robotraconteur.image')\n self._image_type = RRN.GetStructureType('com.robotraconteur.image.Image')\n self._image_info_type = RRN.GetStructureType('com.robotraconteur.image.ImageInfo')\n self._compressed_image_type = RRN.GetStructureType('com.robotraconteur.image.CompressedImage')\n self._date_time_utc_type = RRN.GetPodDType('com.robotraconteur.datetime.DateTimeUTC')\n self._isoch_info = RRN.GetStructureType('com.robotraconteur.device.isoch.IsochInfo')\n self._capture_lock = threading.Lock()\n self._streaming = False\n self._fps = self._capture.get(cv2.CAP_PROP_FPS)\n self._camera_info = camera_info\n self._date_time_util = DateTimeUtil(RRN)\n self._sensor_data_util = SensorDataUtil(RRN)\n\n def RRServiceObjectInit(self, ctx, service_path):\n self._downsampler = RR.BroadcastDownsampler(ctx)\n self._downsampler.AddPipeBroadcaster(self.frame_stream)\n self._downsampler.AddPipeBroadcaster(self.frame_stream_compressed)\n self._downsampler.AddPipeBroadcaster(self.preview_stream)\n self._downsampler.AddWireBroadcaster(self.device_clock_now)\n self.frame_stream.MaxBacklog = 2\n self.frame_stream_compressed.MaxBacklog = 2\n self.preview_stream.MaxBacklog = 2\n \n # TODO: Broadcaster peek handler in Python\n self.device_clock_now.PeekInValueCallback = lambda ep: self._date_time_util.FillDeviceTime(self._camera_info.device_info,self._seqno)\n\n @property\n def device_info(self):\n return self._camera_info.device_info\n\n @property\n def camera_info(self):\n return self._camera_info\n\n def _cv_mat_to_image(self, mat):\n\n is_mono = False\n if (len(mat.shape) == 2 or mat.shape[2] == 1):\n is_mono = True\n\n image_info = self._image_info_type()\n image_info.width =mat.shape[1]\n image_info.height = mat.shape[0]\n if is_mono:\n image_info.step = mat.shape[1]\n image_info.encoding = self._image_consts[\"ImageEncoding\"][\"mono8\"]\n else:\n image_info.step = mat.shape[1]*3\n image_info.encoding = self._image_consts[\"ImageEncoding\"][\"bgr888\"]\n image_info.data_header = self._sensor_data_util.FillSensorDataHeader(self._camera_info.device_info,self._seqno)\n \n\n image = self._image_type()\n image.image_info = image_info\n image.data=mat.reshape(mat.size, order='C')\n return image\n\n def _cv_mat_to_compressed_image(self, mat, quality = 100):\n\n is_mono = False\n if (len(mat.shape) == 2 or mat.shape[2] == 1):\n is_mono = True\n\n image_info = self._image_info_type()\n image_info.width =mat.shape[1]\n image_info.height = mat.shape[0]\n \n image_info.step = 0\n image_info.encoding = self._image_consts[\"ImageEncoding\"][\"compressed\"]\n image_info.data_header = self._sensor_data_util.FillSensorDataHeader(self._camera_info.device_info,self._seqno)\n \n image = self._compressed_image_type()\n image.image_info = image_info\n res, encimg = cv2.imencode(\".jpg\",mat,[int(cv2.IMWRITE_JPEG_QUALITY), quality])\n assert res, \"Could not compress frame!\"\n image.data=encimg\n return image\n\n def capture_frame(self):\n with self._capture_lock:\n ret, mat=self._capture.read()\n if not ret:\n raise RR.OperationFailedException(\"Could not read from camera\")\n self._seqno+=1\n return self._cv_mat_to_image(mat)\n\n def capture_frame_compressed(self):\n with self._capture_lock:\n ret, mat=self._capture.read()\n if not ret:\n raise RRN.OperationFailedException(\"Could not read from camera\")\n self._seqno+=1\n return self._cv_mat_to_compressed_image(mat)\n\n def trigger(self):\n raise RR.NotImplementedException(\"Not available on this device\")\n\n def frame_threadfunc(self):\n while(self._streaming):\n with self._capture_lock:\n ret, mat=self._capture.read()\n if not ret:\n #TODO: notify user?\n self._streaming=False\n continue\n self._seqno+=1\n \n self.frame_stream.AsyncSendPacket(self._cv_mat_to_image(mat),lambda: None)\n self.frame_stream_compressed.AsyncSendPacket(self._cv_mat_to_compressed_image(mat),lambda: None)\n self.preview_stream.AsyncSendPacket(self._cv_mat_to_compressed_image(mat,70),lambda: None)\n device_now = self._date_time_util.FillDeviceTime(self._camera_info.device_info,self._seqno)\n self.device_clock_now.OutValue = device_now\n\n def start_streaming(self):\n if (self._streaming):\n raise RR.InvalidOperationException(\"Already streaming\")\n self._streaming=True\n t=threading.Thread(target=self.frame_threadfunc)\n t.start()\n\n def stop_streaming(self):\n if (not self._streaming):\n raise RR.InvalidOperationException(\"Not streaming\")\n self._streaming=False\n\n @property\n def isoch_downsample(self):\n return self._downsampler.GetClientDownsample(RR.ServerEndpoint.GetCurrentEndpoint())\n\n @isoch_downsample.setter\n def isoch_downsample(self, value):\n return self._downsampler.SetClientDownsample(RR.ServerEndpoint.GetCurrentEndpoint(),value)\n\n @property\n def isoch_info(self):\n ret = self._isoch_info()\n ret.update_rate = self._fps\n ret.max_downsample = 100\n ret.isoch_epoch = np.zeros((1,),dtype=self._date_time_utc_type)\n\n @property\n def capabilities(self):\n return 0x1 | 0x2 | 0x4\n\n \n\ndef main():\n parser = argparse.ArgumentParser(description=\"OpenCV based camera driver service for Robot Raconteur\")\n parser.add_argument(\"--camera-info-file\", type=argparse.FileType('r'),default=None,required=True,help=\"Camera info file (required)\")\n parser.add_argument(\"--device-id\", type=int, default=0, help=\"the device to open (default 0)\")\n parser.add_argument(\"--width\", type=int, default=1280, help=\"try to set width of image (default 1280)\")\n parser.add_argument(\"--height\", type=int, default=720, help=\"try to set height of image (default 720)\")\n parser.add_argument(\"--fps\", type=int, default=15, help=\"try to set rate of video capture (default 15 fps)\")\n parser.add_argument(\"--wait-signal\",action='store_const',const=True,default=False, help=\"wait for SIGTERM orSIGINT (Linux only)\")\n\n args, _ = parser.parse_known_args()\n\n rr_args = [\"--robotraconteur-jumbo-message=true\"] + sys.argv\n\n #RRN.RegisterServiceTypesFromFiles(['com.robotraconteur.imaging'],True)\n RRC.RegisterStdRobDefServiceTypes(RRN)\n\n with args.camera_info_file:\n camera_info_text = args.camera_info_file.read()\n\n info_loader = InfoFileLoader(RRN)\n camera_info, camera_ident_fd = info_loader.LoadInfoFileFromString(camera_info_text, \"com.robotraconteur.imaging.camerainfo.CameraInfo\", \"camera\")\n\n attributes_util = AttributesUtil(RRN)\n camera_attributes = attributes_util.GetDefaultServiceAttributesFromDeviceInfo(camera_info.device_info)\n\n camera = CameraImpl(args.device_id,args.width,args.height,args.fps, camera_info)\n for _ in range(10):\n camera.capture_frame()\n \n with RR.ServerNodeSetup(\"com.robotraconteur.imaging.camera\",59823,argv=rr_args):\n\n service_ctx = RRN.RegisterService(\"camera\",\"com.robotraconteur.imaging.Camera\",camera)\n service_ctx.SetServiceAttributes(camera_attributes)\n\n if args.wait_signal: \n #Wait for shutdown signal if running in service mode \n print(\"Press Ctrl-C to quit...\")\n import signal\n signal.sigwait([signal.SIGTERM,signal.SIGINT])\n else:\n #Wait for the user to shutdown the service\n if (sys.version_info > (3, 0)):\n input(\"Server started, press enter to quit...\")\n else:\n raw_input(\"Server started, press enter to quit...\")\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"robotraconteur_camera_driver.py","file_name":"robotraconteur_camera_driver.py","file_ext":"py","file_size_in_byte":9311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"343622347","text":"# Copyright (c) 2016-present, Facebook, Inc.\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\n# pyre-strict\n\nimport json\nimport logging\nimport os\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional\n\nfrom .command import Command, profiling_log_path\n\n\nLOG: logging.Logger = logging.getLogger(__name__)\n\n\n@dataclass(frozen=True)\nclass EventMetadata:\n name: str\n pid: int\n timestamp: int\n tags: Dict[str, str]\n\n\n@dataclass(frozen=True)\nclass Event:\n # pyre-ignore[13]: We shouldn't throw an uninitialized attribute error here\n metadata: EventMetadata\n\n def __init__(self, metadata: EventMetadata) -> None:\n raise NotImplementedError\n\n\n@dataclass(frozen=True)\nclass DurationEvent(Event):\n duration: int\n\n\n@dataclass(frozen=True)\nclass CounterEvent(Event):\n description: Optional[str]\n\n\ndef _parse_tags(input: List[List[str]]) -> Dict[str, str]:\n return {key: value for [key, value] in input}\n\n\ndef _parse_metadata(input_json: Dict[str, Any]) -> EventMetadata:\n return EventMetadata(\n name=input_json[\"name\"],\n pid=input_json[\"pid\"],\n timestamp=input_json[\"timestamp\"],\n tags=_parse_tags(input_json.get(\"tags\", [])),\n )\n\n\ndef parse_event(input_string: str) -> Event:\n input_json: Dict[str, Any] = json.loads(input_string)\n event_type = input_json[\"event_type\"]\n metadata = _parse_metadata(input_json)\n if event_type[0] == \"Duration\":\n duration = event_type[1]\n return DurationEvent(duration=duration, metadata=metadata)\n elif event_type[0] == \"Counter\":\n description = None if len(event_type) <= 1 else event_type[1]\n return CounterEvent(description=description, metadata=metadata)\n else:\n raise ValueError(\"Unrecognized event type: {}\".format(input))\n\n\ndef parse_events(input_string: str) -> List[Event]:\n output: List[Event] = []\n for index, line in enumerate(input_string.splitlines()):\n try:\n line = line.strip()\n if len(line) == 0:\n continue\n output.append(parse_event(line))\n except Exception:\n raise RuntimeError(\n \"Malformed log entry detected on line {}\".format(index + 1)\n )\n return output\n\n\ndef to_traceevents(events: List[Event]) -> List[Dict[str, Any]]:\n def to_traceevent(event: Event) -> Optional[Dict[str, Any]]:\n if isinstance(event, DurationEvent):\n duration_ms = event.duration\n start_time_ms = event.metadata.timestamp - duration_ms\n return {\n \"pid\": event.metadata.pid,\n \"tid\": 0,\n \"ts\": start_time_ms * 1000,\n \"ph\": \"X\",\n \"name\": event.metadata.name,\n \"dur\": duration_ms * 1000,\n \"args\": event.metadata.tags,\n }\n elif isinstance(event, CounterEvent):\n timestamp_ms = event.metadata.timestamp\n arguments: Dict[str, Any] = {\n key: int(value) for key, value in event.metadata.tags.items()\n }\n return {\n \"pid\": event.metadata.pid,\n \"tid\": 0,\n \"ts\": timestamp_ms * 1000,\n \"ph\": \"C\",\n \"name\": event.metadata.name,\n \"args\": arguments,\n }\n else:\n return None\n\n return [\n trace_event\n for trace_event in map(to_traceevent, events)\n if trace_event is not None\n ]\n\n\nclass Profile(Command):\n NAME = \"profile\"\n\n def _run(self) -> None:\n try:\n profiling_output = Path(profiling_log_path())\n if not profiling_output.is_file():\n raise RuntimeError(\n \"Cannot find profiling output at `{}`. \"\n \"Please run Pyre with `--enable-profiling` option first.\".format(\n profiling_output\n )\n )\n events = parse_events(profiling_output.read_text())\n print(json.dumps(to_traceevents(events)))\n except Exception as e:\n LOG.error(\"Failed to inspect profiling log: {}\".format(e))\n","sub_path":"client/commands/profile.py","file_name":"profile.py","file_ext":"py","file_size_in_byte":4280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"421849510","text":"# -*- coding:utf-8 -*-\n'''\nCreated on 14 de set de 2017\n\n@author: Guilherme C.\n@author: Eduardo Miranda\n'''\nfrom Util import Util;\n\nclass Individuo(object):\n\n #def __init__(self, idNum, cor, vitalidade, deslocamento, classeIndividuo, vit1, vit2):\n def __init__(self, idNum, cor, vitalidade, deslocamento, classeIndividuo, vit1, vit2, KC, KD, KS, KW, KI):\n '''Constructor'''\n #Informacoes basicas do individuo\n self.idNum = idNum\n self.cor = cor\n self.ultimaDirecao = 0\n self.classeIndividuo = classeIndividuo\n self.vitalidade = vitalidade\n self.deslocamentoBase = deslocamento\n self.deslocamento = deslocamento\n self.qtdPassos = 0\n self.vit1 = vit1\n self.vit2 = vit2\n self.KC = KC\n self.KD = KD\n self.KS = KS\n self.KW = KW\n self.KI = KI\n self.iteracoesGastas = 0\n \n #Estatisticas\n self.movimentosFeitos = 0\n self.movimentosWaiting = 0\n \n #Posicionamento do individuo no mapa\n self.coluna = 0\n self.linha = 0\n self.idMapa = 0\n self.saiu = False\n '''\n self.idade = idade\n self.escolaridade = escolaridade\n self.contadorNoRound = 0\n self.status = Util.I_NAO_MOVIDO\n '''\n\n def posicionaIndividuoMapa(self, coluna, linha, idMapa):\n self.coluna = coluna\n self.linha = linha\n self.idMapa = idMapa\n\n def diminuiVitalidade(self, distancia):\n\n if (distancia == 0):\n return self.vitalidade\n \n return self.vitalidade - (16-distancia)\n\n def corrigeDeslocamento(self):\n if self.vitalidade < self.vit1:\n return self.deslocamentoBase + 1\n elif self.vitalidade < self.vit2:\n return self.deslocamentoBase + 2\n return self.deslocamentoBase \n ","sub_path":"Experimentos/Experimento Nishihari/Individuo.py","file_name":"Individuo.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"376070820","text":"import numpy as np\nimport tensorflow as tf\nimport os\nfrom os.path import join as pjoin\n\nprint(tf.__version__)\n\nx_train = np.load(\"./info/task2/x_train.npy\")\ny_train = np.load(\"./info/task2/y_train.npy\")\nx_test = np.load(\"./info/task2/x_test.npy\")\ny_test = np.load(\"./info/task2/y_test.npy\")\n\nx_train = x_train * 1.0 / 127.5 - 1\nx_test = x_test * 1.0 / 127.5 - 1\nprint(\"data load finish\")\n# Training Parameters\nlearning_rate = 0.0005\nnum_steps = 1000\n\nbatch_size = 64\nnum_epochs = 10\ntf.logging.set_verbosity(tf.logging.INFO)\n\n# Network Parameters\nnum_input = 7500 # MNIST data input (img shape: 28*28)\nnum_classes = 5 # MNIST total classes (0-9 digits)\ndropout = 0.25 # Dropout, probability to drop a unit\n\n\n# Create the neural network\ndef conv_net(x_dict, n_classes, dropout, reuse, is_training):\n # Define a scope for reusing the variables\n with tf.variable_scope('ConvNet', reuse=reuse):\n # TF Estimator input is a dict, in case of multiple inputs\n x = x_dict['images']\n\n # MNIST data input is a 1-D vector of 784 features (28*28 pixels)\n # Reshape to match picture format [Height x Width x Channel]\n # Tensor input become 4-D: [Batch Size, Height, Width, Channel]\n # x = tf.reshape(x, shape=[-1, 28, 28, 1])\n\n # Convolution Layer with 32 filters and a kernel size of 5\n conv1 = tf.layers.conv2d(x, 32, 5, activation=tf.nn.relu)\n # Max Pooling (down-sampling) with strides of 2 and kernel size of 2\n conv1 = tf.layers.max_pooling2d(conv1, 2, 2)\n\n # Convolution Layer with 64 filters and a kernel size of 5\n conv2 = tf.layers.conv2d(conv1, 64, 5, activation=tf.nn.relu)\n # Max Pooling (down-sampling) with strides of 2 and kernel size of 2\n conv2 = tf.layers.max_pooling2d(conv2, 2, 2)\n\n conv3 = tf.layers.conv2d(conv2, 128, 5, activation=tf.nn.relu)\n # Max Pooling (down-sampling) with strides of 2 and kernel size of 2\n conv3 = tf.layers.max_pooling2d(conv3, 2, 2)\n\n # Flatten the data to a 1-D vector for the fully connected layer\n fc1 = tf.contrib.layers.flatten(conv3)\n\n # Fully connected layer (in tf contrib folder for now)\n fc1 = tf.layers.dense(fc1, 1024)\n # Apply Dropout (if is_training is False, dropout is not applied)\n fc1 = tf.layers.dropout(fc1, rate=dropout, training=is_training)\n\n # Output layer, class prediction\n out = tf.layers.dense(fc1, n_classes)\n\n return out\n\n\n# Define the model function (following TF Estimator Template)\ndef model_fn(features, labels, mode):\n # Build the neural network\n # Because Dropout have different behavior at training and prediction time, we\n # need to create 2 distinct computation graphs that still share the same weights.\n logits_train = conv_net(features, num_classes, dropout, reuse=False, is_training=True)\n logits_test = conv_net(features, num_classes, dropout, reuse=True, is_training=False)\n\n # Predictions\n pred_classes = tf.argmax(logits_test, axis=1)\n pred_probas = tf.nn.softmax(logits_test)\n\n # If prediction mode, early return\n if mode == tf.estimator.ModeKeys.PREDICT:\n return tf.estimator.EstimatorSpec(mode, predictions=pred_classes)\n\n # Define loss and optimizer\n loss_op = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(\n logits=logits_train, labels=tf.cast(labels, dtype=tf.int32)), name='loss')\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\n train_op = optimizer.minimize(loss_op, global_step=tf.train.get_global_step())\n\n # Evaluate the accuracy of the model\n acc_op = tf.metrics.accuracy(labels=labels, predictions=pred_classes)\n # TF Estimators requires to return a EstimatorSpec, that specify\n # the different ops for training, evaluating, ...\n estim_specs = tf.estimator.EstimatorSpec(\n mode=mode,\n predictions=pred_classes,\n loss=loss_op,\n train_op=train_op,\n eval_metric_ops={'accuracy': acc_op})\n\n return estim_specs\n\n\nprint('Training model...')\n# Build the Estimator\n\nmodel = tf.estimator.Estimator(model_fn, model_dir=\"./log/task2/\",\n config=tf.estimator.RunConfig(save_summary_steps=10, keep_checkpoint_max=1,\n log_step_count_steps=10))\n\n# Define the input function for training\ninput_fn = tf.estimator.inputs.numpy_input_fn(\n x={'images': x_train}, y=y_train,\n batch_size=batch_size, num_epochs=None, shuffle=True)\n# Train the Model\n\nmodel.train(input_fn, steps=num_steps)\nprint('Done training!')\n\n# Evaluate the Model\n# Define the input function for evaluating\ninput_fn = tf.estimator.inputs.numpy_input_fn(\n x={'images': x_test}, y=y_test,\n batch_size=batch_size, shuffle=False)\n# Use the Estimator 'evaluate' method\nprint('total accuracy: {}'.format(model.evaluate(input_fn)['accuracy']))\n\nfor c in np.nditer(np.unique(y_test)):\n x_temp = np.array([x_test[i] for i in range(0, len(y_test)) if y_test[i] == c])\n y_temp = np.zeros((x_temp.shape[0],), dtype=np.int) + c\n input_fn = tf.estimator.inputs.numpy_input_fn(\n x={'images': x_temp}, y=y_temp,\n batch_size=batch_size, shuffle=False)\n print('class{} accuracy: {}'.format(c, model.evaluate(input_fn)['accuracy']))\n\nprint('Done exporting!')\n","sub_path":"test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":5341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"574363717","text":"import collections\nimport random\nimport typing\n\nimport numpy as np\n\n\nDirection = collections.namedtuple(\"Direction\", [\"name\", \"transpose\", \"reverse\"])\n\ndirections = [\n Direction(\"down\", True, True),\n Direction(\"left\", False, False),\n Direction(\"right\", False, True),\n Direction(\"up\", True, False),\n]\n\n\nclass Game(object):\n def __init__(self):\n self.board = np.zeros((4, 4), dtype=\"int\")\n self.score = 0\n self.steps = 0\n self.spawn()\n self.spawn()\n\n def spawn(self) -> None:\n new_number = random.choices([2, 4], [0.9, 0.1])[0]\n free_cols, free_rows = self.get_free_fields()\n new_coord = random.choice(list(zip(free_cols, free_rows)))\n self.board[new_coord] = new_number\n\n def get_free_fields(self) -> typing.Tuple[np.array, np.array]:\n free_cols, free_rows = np.where(self.board == 0)\n return free_cols, free_rows\n\n def is_game_over(self) -> bool:\n return not np.any(self.board == 0)\n\n def move(self, direction: Direction) -> int:\n sum_merges = 0\n board = transform_board(self.board, direction, True)\n for i in range(board.shape[0]):\n row = board[i]\n non_zero = list(row[row != 0])\n j = 0\n while j < len(non_zero) - 1:\n if non_zero[j] == non_zero[j + 1]:\n non_zero[j] += non_zero[j + 1]\n sum_merges += non_zero[j]\n del non_zero[j + 1]\n j += 1\n row = non_zero + [0] * (4 - len(non_zero))\n board[i, :] = row\n self.board = transform_board(board, direction, False)\n self.score += sum_merges\n self.steps += 1\n return sum_merges\n\n def __str__(self) -> str:\n return str(self.board)\n\n\ndef transform_board(board: np.array, direction: Direction, forward: bool) -> np.array:\n if forward:\n if direction.transpose:\n board = board.T\n if direction.reverse:\n board = board[:, ::-1]\n else:\n if direction.reverse:\n board = board[:, ::-1]\n if direction.transpose:\n board = board.T\n return board\n","sub_path":"game_simulation_sandbox/ri2048/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"75297430","text":"#http serv\r\n\r\nimport socket\r\nimport time\r\nimport sqlite3\r\nimport threading\r\ndef console():\r\n \"\"\"Constantly read from stdin and discard\"\"\"\r\n try:\r\n while 1:\r\n a = input()\r\n if a == \"d\":\r\n s.delall()\r\n except (KeyboardInterrupt, EOFError):\r\n socket.socket().connect((socket.gethostname()+\".home\",80))\r\n\r\ndef log(data):\r\n t = time.strftime(\"%d/%m/%Y %X : \")\r\n text = t + data + \"\\n\"\r\n f = open(\"log.txt\",\"a\")\r\n f.write(text)\r\n f.close()\r\ndef readPage(p):\r\n r = \"\"\r\n i = 3\r\n while 1:\r\n i+=1\r\n if p[i] == \" \":\r\n break\r\n else:\r\n r += p[i]\r\n return r\r\ndef readFile(name):\r\n try:\r\n file = open(name,\"r\")\r\n r = file.read()\r\n file.close()\r\n except FileNotFoundError:\r\n return nofile()\r\n return r, \"200 OK\"\r\ndef readImage(name):\r\n file = open(name,\"rb\")\r\n r = file.read()\r\n file.close()\r\n return r, \"200 OK\"\r\ndef nofile():\r\n rp = \"404

    404 PAGE NOT FOUND

    \"\r\n code = \"404 File Not Found\"\r\n return rp, code\r\nclass server():\r\n def __init__(self):\r\n self.ip = socket.gethostname()+\".home\"\r\n self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n self.sock.bind((self.ip,80))\r\n self.sock.listen(1024)\r\n self.threads = []\r\n def start(self):\r\n log(\"Started\")\r\n try:\r\n self.loop()\r\n except KeyboardInterrupt:\r\n print(\"Goodbye\")\r\n log(\"Ended\")\r\n def loop(self):\r\n print(\"Server starting on host: {0}\".format(self.ip))\r\n while 1:\r\n s, a = self.sock.accept()\r\n threading.Thread(target=self.conHandle,args=(s,a,)).start()\r\n def conHandle(self,s,addr):\r\n print(\"{0} threads running. {1}\".format(threading.active_count(),threading.current_thread()))\r\n data = \"\"\r\n t = time.time()\r\n while data == \"\":\r\n data += str(s.recv(1024),\"UTF-8\")\r\n if time.time()-t > 5:\r\n print(\"Connection timed out\")\r\n break\r\n if data == \"\":\r\n s.sendall(bytes(\"HTTP/1.1 500 Invalid request\\r\\n\",\"UTF-8\"))\r\n log(\"New connection from {0} with no data recieved\".format(addr[0]))\r\n s.close()\r\n return \"\"\r\n page = readPage(data)\r\n log(\"New connection from {0} reqeusting {1}\".format(addr[0],page))\r\n print(\"PAGE: \" + page)\r\n code = \"500 internal error\"\r\n mime = \"text/html\"\r\n if page == \"/\":\r\n rp, code = readFile(\"testing.html\")\r\n elif page == \"/app.js\":\r\n rp, code = readFile(\"app.js\")\r\n mime = \"text/javascript\"\r\n elif page == \"/home.html\":\r\n rp, code = readFile(\"home.html\")\r\n elif page == \"/favicon.png\":\r\n mime = \"image/png\"\r\n rp, code = readImage(\"favicon.png\")\r\n else:\r\n rp, code = nofile()\r\n if type(rp) == str:\r\n resp = \"HTTP/1.1 {0}\\r\\nDate: {1}\\r\\nServer: Non-Existent\\r\\nContent-Type: {2}\\r\\n\\r\\n{3}\".format(code,time.strftime(\"%D $X\"),mime,rp)\r\n s.sendall(bytes(resp,\"UTF-8\"))\r\n elif type(rp) == bytes:\r\n resp = bytes(\"HTTP/1.1 {0}\\r\\nDate: {1}\\r\\nServer: Non-Existent\\r\\nContent-Type: {2}\\r\\n\\r\\n\".format(code,time.strftime(\"%D $X\"),mime),\"UTF-8\")\r\n resp = resp + rp\r\n s.sendall(resp)\r\n else:\r\n print(\"Invalid type of response page\")\r\n s.close()\r\nthreading.Thread(target=console).start()\r\ns = server()\r\ns.start()\r\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"61894621","text":"from django.http import HttpResponse\nimport json as simplejson\nfrom supra import views as supra\nfrom Citas.settings import ORIGIN\nfrom usuarios.models import Medico, Paciente\n\n# Create your views here.\nsupra.SupraConf.ACCECC_CONTROL[\"allow\"] = True\nsupra.SupraConf.ACCECC_CONTROL[\"origin\"] = ORIGIN\nsupra.SupraConf.ACCECC_CONTROL[\"credentials\"] = \"true\"\nsupra.SupraConf.ACCECC_CONTROL[\"headers\"] = \"origin, content-type, accept\"\nsupra.SupraConf.ACCECC_CONTROL[\"methods\"] = \"POST, GET, PUT, DELETE ,OPTIONS\"\n\n\ndef check_login(function):\n @supra.access_control\n def check(request, *args, **kwargs):\n if request.user.is_authenticated() or request.method == \"OPTIONS\":\n paciente = Paciente.objects.filter(id=request.user.pk).first()\n if paciente:\n if paciente.activado:\n return function(request, *args, **kwargs)\n # end if\n else:\n medico = Medico.objects.filter(id=request.user.pk).first()\n if medico:\n if medico.activado:\n return function(request, *args, **kwargs)\n # end if\n return HttpResponse(simplejson.dumps({\"error\": \"Debes activar tu cuenta\"}), status=403)\n # end if\n return HttpResponse(simplejson.dumps({\"error\": \"Debes iniciar sesion\"}), status=403)\n # end def\n return check\n# end def\n","sub_path":"Citas/decorator.py","file_name":"decorator.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"41986043","text":"#!/usr/bin/env python3\nimport time\nimport unittest\n\nfrom ..common import Checksum, log as common_log, retry_fn, RpmShard\n\n\nclass TestCommon(unittest.TestCase):\n\n\n def test_rpm_shard(self):\n self.assertEqual(\n RpmShard(shard=3, modulo=7), RpmShard.from_string('3:7'),\n )\n\n class FakeRpm:\n def __init__(self, filename):\n self._filename = filename\n\n def filename(self):\n return self._filename\n\n self.assertEqual(\n [('foo', True), ('bar', False), ('foo', False), ('bar', True)],\n [\n (rpm, shard.in_shard(FakeRpm(rpm)))\n for shard in [RpmShard(1, 7), RpmShard(2, 7)]\n for rpm in ['foo', 'bar']\n ],\n )\n\n def test_checksum(self):\n cs = Checksum(algorithm='oops', hexdigest='dada')\n self.assertEqual('oops:dada', str(cs))\n self.assertEqual(cs, Checksum.from_string(str(cs)))\n for algo in ['sha1', 'sha']:\n h = Checksum(algo, 'ignored').hasher()\n h.update(b'banana')\n self.assertEqual(\n '250e77f12a5ab6972a0895d290c4792f0a326ea8', h.hexdigest(),\n )\n\n def test_retry_fn(self):\n\n class Retriable:\n def __init__(self, attempts_to_fail=0):\n self.attempts = 0\n self.first_success_attempt = attempts_to_fail + 1\n\n def run(self):\n self.attempts += 1\n if self.attempts >= self.first_success_attempt:\n return self.attempts\n raise RuntimeError(self.attempts)\n\n self.assertEqual(1, retry_fn(\n Retriable().run, delays=[], what='succeeds immediately'\n ))\n\n # Check log messages, and ensure that delays add up as expected\n start_time = time.time()\n with self.assertLogs(common_log) as log_ctx:\n self.assertEqual(4, retry_fn(\n Retriable(3).run, delays=[0, 0.1, 0.2], what='succeeds on try 4'\n ))\n self.assertTrue(any(\n '\\n[Retry 3 of 3] succeeds on try 4 -- waiting 0.2 seconds.\\n' in o\n for o in log_ctx.output\n ))\n self.assertGreater(time.time() - start_time, 0.3)\n\n # Check running out of retries\n with self.assertLogs(common_log) as log_ctx, \\\n self.assertRaises(RuntimeError) as ex_ctx:\n retry_fn(Retriable(100).run, delays=[0] * 7, what='never succeeds')\n self.assertTrue(any(\n '\\n[Retry 7 of 7] never succeeds -- waiting 0 seconds.\\n' in o\n for o in log_ctx.output\n ))\n self.assertEqual((8,), ex_ctx.exception.args)\n","sub_path":"fs_image/rpm/tests/test_common.py","file_name":"test_common.py","file_ext":"py","file_size_in_byte":2723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"20903374","text":"#! /usr/bin/env python3\n\nimport os\nimport shutil\nimport datetime\nimport math\n\n# Variaveis da simulacao\nnum_nos = 5\nsimulacoes = 3\n\nraio = 30\ndensidade = 0.03\ntipoSimulacao = 'raio'\nnum_rounds = int(86400 * 1)\nmultiplicadorIntensidade = 0.4\nmaxTimeBetweenSends = 7200\nminTimeBetweenSends = 120\nmaxEnergyOfBattery = 1000 \nminEnergyOfBattery = 0\nmaxSolarIntensity = 1000 * multiplicadorIntensidade\nminSolarIntensity = 0\nwattPico = 0.15\nconstBattery = 1\t# Divisor\nconstIntensity = 1 # Multiplicador\n\nvaria_min = 20\nvaria_max = 60\nvaria_tic = 10\n\npathExist = True\t\n# Gera um arquivo para logs\ndebbugfile = open('logs_simulacoes/' + tipoSimulacao + '_sem.log', 'a+')\ndebbugfile.write('Iniciando a verificacao ' + tipoSimulacao + '_sem em: ')\ndebbugfile.write(str(datetime.datetime.now().strftime(\"%d/%m/%y %H:%M\")) + '\\n')\n\nfor varia_atual in range(varia_min, varia_max+1, varia_tic):\n\t\n\tfor simulacao in range(1, simulacoes+1):\n\t\tpathTX = 'logs/' + tipoSimulacao+ '_SimulacaoTX_' + str(varia_atual) + str(simulacao)\n\t\tpath = 'logs/' + tipoSimulacao+ '_Simulacao_' + str(varia_atual) + str(simulacao)\n\n\t\tif os.path.isdir(pathTX):\n\t\t\tdebbugfile.write(tipoSimulacao+ '_SimulacaoTX_' + str(varia_atual) + str(simulacao) + ' ... ok\\n' )\n\t\telse:\n\t\t\tpathExist = False\n\t\t\t\n\t\t\tif os.path.isdir(path):\n\t\t\t\tdebbugfile.write(tipoSimulacao+ '_SimulacaoTX_' + str(varia_atual) + str(simulacao) + ' ... erro\\n' )\n\t\t\t\tdebbugfile.write('Deletando a pasta ' + tipoSimulacao+ '_Simulacao_' + str(varia_atual) + str(simulacao))\n\t\t\t\tshutil.rmtree(path)\n\t\t\t\tdebbugfile.write(' ... ok\\n')\n\t\t\t\tdebbugfile.write('Iniciando ' + tipoSimulacao+ '_Simulacao_' + str(varia_atual) + str(simulacao))\n\t\t\t\t\n\t\t\t\t# chama a simulacao faltante\n\t\t\t\tos.system('./r_varia_' + tipoSimulacao + '.py ' + str(num_nos) + ' ' + str(simulacoes) + ' ' + str(simulacao) + ' ' + \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(raio) + ' ' + str(densidade) + ' ' + str(tipoSimulacao) + ' ' + \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(num_rounds) + ' ' + str(multiplicadorIntensidade) + ' ' + str(maxTimeBetweenSends) + ' ' +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(minTimeBetweenSends) + ' ' + str(maxEnergyOfBattery) + ' ' + str(minEnergyOfBattery) + ' ' +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(maxSolarIntensity) + ' ' + str(minSolarIntensity) + ' ' + str(wattPico) + ' ' +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(constBattery) + ' ' + str(constIntensity) + ' ' + str(varia_min) + ' ' + \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(varia_max) + ' ' + str(varia_tic) + ' ' + str(varia_atual))\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\n\t\t\t\tdebbugfile.write(' ... ok\\n')\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tdebbugfile.write(tipoSimulacao+ '_SimulacaoTX_' + str(varia_atual) + str(simulacao) + ' ... erro\\n' )\n\t\t\t\tdebbugfile.write('Iniciando ' + tipoSimulacao+ '_Simulacao_' + str(varia_atual) + str(simulacao))\n\t\t\t\t\n\t\t\t\t# chama a simulacao faltante\n\t\t\t\tos.system('./r_varia_' + tipoSimulacao + '.py ' + str(num_nos) + ' ' + str(simulacoes) + ' ' + str(simulacao) + ' ' + \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(raio) + ' ' + str(densidade) + ' ' + str(tipoSimulacao) + ' ' + \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(num_rounds) + ' ' + str(multiplicadorIntensidade) + ' ' + str(maxTimeBetweenSends) + ' ' +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(minTimeBetweenSends) + ' ' + str(maxEnergyOfBattery) + ' ' + str(minEnergyOfBattery) + ' ' +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(maxSolarIntensity) + ' ' + str(minSolarIntensity) + ' ' + str(wattPico) + ' ' +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(constBattery) + ' ' + str(constIntensity) + ' ' + str(varia_min) + ' ' + \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(varia_max) + ' ' + str(varia_tic) + ' ' + str(varia_atual))\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\n\t\t\t\tdebbugfile.write(' ... ok\\n')\t\t\t\t\n\t\t\tbreak\n\t\t\t\n\tif(pathExist == False):\n\t\tbreak\n\nif pathExist == True:\n\tos.system('python3 r_processa_' + tipoSimulacao + '.py ' + str(simulacoes) + ' ' + str(num_nos) + ' ' + str(varia_min) + ' ' + str(varia_max) + ' '+ str(varia_tic))\t\t\t\n\ndebbugfile.close()\n\n\n\n","sub_path":"r_raio_GAFEH.py","file_name":"r_raio_GAFEH.py","file_ext":"py","file_size_in_byte":3764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"474809407","text":"'''\nBSD Licence\nCopyright (c) 2012, Science & Technology Facilities Council (STFC)\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n* Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand/or other materials provided with the distribution.\n* Neither the name of the Science & Technology Facilities Council (STFC)\nnor the names of its contributors may be used to endorse or promote\nproducts derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS\nBE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\nOR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nCreated on 12 Apr 2013\n\n@author: mnagni\n'''\n\nfrom rdflib import Graph, URIRef\nimport logging\nfrom django.conf import settings\nfrom rdflib.namespace import Namespace\nimport uuid\nfrom djcharme.charme_middleware import CharmeMiddleware\nfrom rdflib.graph import ConjunctiveGraph\nfrom urllib2 import URLError\nfrom djcharme.exception import StoreConnectionError\n\nLOGGING = logging.getLogger(__name__)\n'''\nSELECT_ANNOTATION = \"\"\"\n PREFIX an: \n SELECT ?s ?p ?o\n WHERE {\n an:%s ?p ?o \n }\n\"\"\"\n\nSELECT_ANNOTATIONS = \"\"\"\nPREFIX charm: \nSELECT * WHERE {\n ?s a charm:anno .\n ?s ?p ?o \n}\n\"\"\"\n\nDESCRIBE_ANNOTATIONS = \"\"\"\nPREFIX charm: \nDESCRIBE ?s\nWHERE {\n ?s a charm:anno .\n}\n\"\"\"\n\nDESCRIBE_ANNOTATION = \"\"\"\n PREFIX an: \n DESCRIBE an:%s \n\"\"\"\n\nCONSTRUCT_ANNOTATION = \"\"\"\nPREFIX an: \nprefix oa: \nprefix charm: \n\nCONSTRUCT { an:%s ?p ?o .}\n\nWHERE {\n an:%s ?p ?o .\n}\n\"\"\"\n'''\nFORMAT_MAP = {'json-ld': 'application/ld+json',\n 'xml': 'application/rdf+xml',\n 'turtle': 'text/turtle'}\n\ndef rdf_format_from_mime(mimetype):\n for k,v in FORMAT_MAP.iteritems():\n if mimetype == v:\n return k \n\n# Create a namespace object for the CHARMe namespace.\nCHARM = Namespace(\"http://charm.eu/ch#\")\nRDF = Namespace(\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\")\nOA = Namespace(\"http://www.w3.org/ns/oa#\")\n\nANNO_SUBMITTED = 'submitted'\nANNO_INVALID = 'invalid'\nANNO_STABLE = 'stable'\nANNO_RETIRED = 'retired'\n\nNODE_URI = 'http://localhost/'\nANNO_URI = 'annoID'\nBODY_URI = 'bodyID'\nCH_NODE = 'chnode'\n\nRESOURCE = 'resource'\nDATA = 'data'\nPAGE = 'page'\n\nLOGGING = logging.getLogger(__name__)\n\n\ndef format_graphIRI(graph, baseurl = 'http://dummyhost'):\n '''\n Builds a named graph URIRef using, if exists, \n a settings.SPARQL_QUERY parameter.\n \n - string **graph** \n the graph name\n * return String\n '''\n if 'http://' in graph:\n return graph\n \n return '%s/%s' % (getattr(settings, 'SPARQL_DATA', baseurl), graph)\n\ndef generate_graph(store, graph):\n '''\n Generate a new Graph\n - string **graph** \n the graph name\n * return:rdflib.Graph - Returns an RDFlib graph containing the given data\n '''\n return Graph(store=store, identifier = format_graphIRI(graph))\n\ndef insert_rdf(data, mimetype, graph = None, store=None):\n '''\n Inserts an RDF/json-ld document into the triplestore\n - string **data** \n a document\n - string **mimetype** \n the document mimetype\n - string **graph** \n the graph name\n - rdflib.Store **store** \n if none use the return of get_store() \n '''\n if store is None:\n store = CharmeMiddleware.get_store()\n tmp_g = Graph()\n #Necessary as RDFlib does not contain the json-ld lib\n\n tmp_g.parse(data = data, format = rdf_format_from_mime(mimetype))\n _formatSubmittedAnnotation(tmp_g)\n final_g = generate_graph(store, graph)\n \n for ns in tmp_g.namespaces():\n final_g.store.bind(str(ns[0]), ns[1])\n \n for res in tmp_g:\n final_g.add(res)\n \n return final_g\n\ndef _formatResourceURIRef(resource_id):\n '''\n Returns the URIRef associated with the id for this specific node\n '''\n if resource_id.startswith('http:'):\n return URIRef(resource_id) \n return URIRef('%s/%s/%s' % (getattr(settings, 'NODE_URI', NODE_URI), \n RESOURCE,\n resource_id))\n \ndef _formatNodeURIRef(uriref, anno_uri, body_uri):\n '''\n Rewrite a URIRef according to the node configuration\n * uriref:rdflib.URIRef \n * anno_uri:String as hexadecimal \n * body_uri:String as hexadecimal\n ''' \n if isinstance(uriref, URIRef) and NODE_URI in uriref:\n uriref = URIRef(uriref.replace(NODE_URI,\n getattr(settings,\n 'NODE_URI', \n NODE_URI) + '/'))\n\n if isinstance(uriref, URIRef) and CH_NODE in uriref:\n uriref = URIRef(uriref.replace(CH_NODE + ':', \n getattr(settings, 'NODE_URI', NODE_URI) + '/')) \n if isinstance(uriref, URIRef) and ANNO_URI in uriref:\n uriref = URIRef(uriref.replace(ANNO_URI, \"resource/\" + anno_uri))\n if isinstance(uriref, URIRef) and BODY_URI in uriref:\n uriref = URIRef(uriref.replace(BODY_URI, \"resource/\" + body_uri)) \n return uriref\n\ndef _formatSubmittedAnnotation(graph):\n '''\n Formats the graph according to the node configuration\n '''\n anno_uri = uuid.uuid4().hex\n body_uri = uuid.uuid4().hex\n \n for s,p,o in graph:\n graph.remove((s, p, o))\n s =_formatNodeURIRef(s, anno_uri, body_uri)\n p = _formatNodeURIRef(p, anno_uri, body_uri)\n o = _formatNodeURIRef(o, anno_uri, body_uri)\n graph.add((s, p, o))\n\ndef change_annotation_state(resource_id, new_graph):\n '''\n Advance the status of an annotation\n - string **resource_id**\n the resource URL\n - string **new_graph**\n the name of the state where more the annotation\n ''' \n old_graph = find_annotation_graph(resource_id)\n old_g = generate_graph(CharmeMiddleware.get_store(), old_graph)\n new_g = generate_graph(CharmeMiddleware.get_store(), new_graph)\n for res in old_g.triples((_formatResourceURIRef(resource_id), None, None)):\n old_g.remove(res) \n new_g.add(res)\n return new_g\n\ndef find_annotation_graph(resource_id): \n triple = (_formatResourceURIRef(resource_id), None, None)\n for graph in [ANNO_SUBMITTED, ANNO_STABLE, ANNO_RETIRED, ANNO_INVALID]:\n new_g = generate_graph(CharmeMiddleware.get_store(), graph)\n if triple in new_g:\n return graph \n \n \n\ndef find_resource_by_id(resource_id):\n '''\n Returns the charme resource associated with the given resource_id\n * resource_id:String\n * return: an rdflib.Graph object\n '''\n g = ConjunctiveGraph(store=CharmeMiddleware.get_store())\n tmp_g = Graph()\n for res in g.triples((_formatResourceURIRef(resource_id), None, None)):\n tmp_g.add(res) \n return tmp_g\n\ndef _collect_annotations(graph):\n ''' \n Returns a graph containing all the node annotations\n - string **graph** \n the graph name \n '''\n g = generate_graph(CharmeMiddleware.get_store(), graph)\n\n tmp_g = Graph()\n try:\n for res in g.triples((None, None, OA['Annotation'])):\n tmp_g.add(res)\n for res in g.triples((None, OA['hasTarget'], None)):\n tmp_g.add(res) \n for res in g.triples((None, OA['hasBody'], None)):\n tmp_g.add(res)\n except URLError as e:\n raise StoreConnectionError(\"Cannot open a connection with triple store \\n\" + str(e))\n return tmp_g","sub_path":"djcharme/djcharme/node/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":8729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"199520209","text":"from django.core.management.base import BaseCommand, CommandError\n# from polls.models import Question as Poll\n\n\nclass Command(BaseCommand):\n help = 'loads from json file'\n\n def add_arguments(self, parser):\n parser.add_argument('dumpFile', nargs='+', type=str)\n\n def handle(self, *args, **options):\n from subprocess import call\n import os\n\n path, dirs, files = next(os.walk(\"/usr/lib\"))\n file_count = len(files)\n\n try:\n import psycopg2\n from psycopg2 import sql\n from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT\n except Exception as e:\n print(\"could not import psycopg2\")\n SystemExit(0)\n\n from django.contrib.contenttypes.models import ContentType\n\n def getAndWriteNewSetting():\n try:\n fs.close()\n except Exception as e:\n raise\n fs = open(\"databaseConnect.txt\", \"w+\")\n connectionDataTypes = [\"dbname\", \"user\", \"host\", \"password\"]\n connectionData = {}\n databaseSetting = \"\"\n for i in connectionDataTypes:\n connectionData[i] = input(str(i) + \" \")\n for i in range(len(connectionData)):\n\n databaseSetting = databaseSetting + \\\n connectionDataTypes[i] + \"='\" + \\\n connectionData[connectionDataTypes[i]] + \"'\"\n fs.write(databaseSetting)\n fs.close()\n return databaseSetting\n\n try:\n fs = open(\"databaseConnect.txt\", \"r\")\n fsText = fs.read()\n if fsText != None:\n text = input(\"would to use previos settings? (y/n) \")\n global databaseSetting\n if text == \"y\":\n # fs = open(\"databaseConnect.txt\",\"r\")\n\n databaseSetting = fs.read()\n fs.close()\n if text == \"n\":\n\n databaseSetting = getAndWriteNewSetting()\n\n except:\n raise\n\n try:\n database = psycopg2.connect(databaseSetting)\n except Exception as e:\n raise\n\n def backup():\n if not os.path.exists(\"backups\"):\n os.makedirs(\"backups\")\n call(\"python3 manage.py dumpdata > backups/dumpdataBackup.json\", shell=True)\n\n fs = open(\"databaseConnect.txt\", \"r\")\n databaseSetting = fs.read()\n fs.close()\n\n databaseSettingList = databaseSetting.split('=')\n ln = len(databaseSettingList[1])\n\n cursor = database.cursor()\n\n try:\n backup()\n except Exception as e:\n print(\"no database\")\n\n database.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)\n\n cursor.execute(sql.SQL(\"drop database if exists {};\").format(\n sql.Identifier(databaseSettingList[1][1:ln-4].replace(\"'\", \"\"))))\n cursor.execute(sql.SQL(\"create database {};\").format(\n sql.Identifier(databaseSettingList[1][1:ln-4].replace(\"'\", \"\"))))\n try:\n call(\"python3 manage.py migrate\", shell=True)\n except Exception as e:\n pass\n\n ContentType.objects.all().delete()\n call(\"python3 manage.py loaddata dump.json\", shell=True)\n from django.contrib.auth.models import User\n text = input(\"do you want to create/fix super user (y/n) \")\n if text == \"y\":\n try:\n text = input(\"your username \")\n User.objects.get(username=text, is_superuser=True).delete()\n call(\"python3 manage.py createsuperuser\", shell=True)\n except Exception as e:\n call(\"python3 manage.py createsuperuser\", shell=True)\n # text = input(\"your username\")\n # User.objects.get(username=\"joebloggs\", is_superuser=True).delete()\n\n\n# quit()\n","sub_path":"the_photohub_website/management/commands/reload.py","file_name":"reload.py","file_ext":"py","file_size_in_byte":3887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"555522272","text":"from collections import defaultdict\nd=defaultdict(list)\n#list append\nd['a'].append(1)\nd['a'].append(2)\nd['b'].append(4)\nprint(d)\n#set add\ne=defaultdict(set)\ne['a'].add(1)\ne['a'].add(2)\ne['b'].add(4)\nprint(e)\n\nprice={\n 'acme':45.23,\n 'aapl':612.78,\n 'ibm':205.55,\n 'hpq':37.20,\n 'fb':10.75,\n 'ffb':10.75,\n 'if':205.55\n}\nmin_price=min(zip(price.values(),price.keys()))\nprint(min_price)\nmax_price=max(zip(price.values(),price.keys()))\nprint(max_price)\nprice_sorted=sorted(zip(price.values(),price.keys()))\nprint(price_sorted)\nprint(price.items())\n\na=[1,2,5,6,5,2,2,5,4,2,1,9,8,5]\ndef clean(items):\n seen=set()\n for item in items:\n if item not in seen:\n yield item\n seen.add(item)\nprint(list(clean(a)))\n\n#序列出现次数最多的元素\nfrom collections import Counter\n#通过一个或多个字典中的值来对列表排序\nfrom operator import itemgetter\n#分组\nfrom itertools import groupby\nrow=[\n {'job':111,'data':'07/01/2012'},\n {'job':211,'data':'09/01/2012'},\n {'job':311,'data':'08/01/2012'},\n {'job':411,'data':'07/01/2012'},\n {'job':511,'data':'09/01/2012'},\n]\nrow.sort(key=itemgetter('data'))\nfor data,items in groupby(row,key=itemgetter('data')):\n print(data)\n for i in items :\n print(' ',i)\n#返回满足布尔值为true的相应元素\nfrom itertools import compress\naddress=[\n '5412 a clark',\n '5421 b asdf'\n]\ncounts=[0,1]\na=[n==1 for n in counts]\nprint(list(compress(address,a)))\n\n#多个映射或字典中合并为一个单独的映射并进行查找和检查建是否存在\nfrom collections import ChainMap\na={'x':1,'z':4}\nb={'y':2,'z':3}\nc=ChainMap(a,b)\nprint(c['x'],end=' ')\nprint(c['y'],end=' ')\nprint(c['z'],end='')\n\n","sub_path":"代码2.py","file_name":"代码2.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"34114556","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 ('civilireports', '0003_merge'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='report',\n name='date_of_report',\n field=models.DateTimeField(default=datetime.datetime(2014, 11, 15, 17, 0, 56, 805291), verbose_name=b'date of report'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='report',\n name='status',\n field=models.CharField(default=b'reported', max_length=255, verbose_name=b'status', choices=[(b'reported', b'reported'), (b'in_progress', b'in progress'), (b'finished', b'finished')]),\n preserve_default=True,\n ),\n ]\n","sub_path":"civili/civilireports/migrations/0004_auto_20141115_1700.py","file_name":"0004_auto_20141115_1700.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"306887177","text":"import numpy as np\nimport cv2\nimport time\nimport os\nfrom epsareas import epsareas_func\n\n\n\ndef main(frame_count, kernel, red_mask_mass, filename):\n frame_skip = 1 # не работает\n frame_size_mult = 0.8\n\n # границы красного цвета BGR\n lower_red = np.array([0, 0, 120], dtype=\"uint8\") # 198, 110\n upper_red = np.array([100, 100, 255], dtype=\"uint8\")\n\n # границы красного цвета HSV\n # lower_red = np.array([0, 0, 120], dtype=\"uint8\") # 198, 110\n # upper_red = np.array([100, 100, 255], dtype=\"uint8\")\n\n\n lower_black = 0\n upper_black = 0\n while True:\n # cap.set(cv2.CAP_PROP_POS_FRAMES, frame_count)\n if frame_count % frame_skip == 0:\n try:\n ret1, s_frame = cap.read()\n # s_frame = cv2.resize(s_frame, (int(cap_w * frame_size_mult), int(cap_h * frame_size_mult)),\n # interpolation=cv2.INTER_CUBIC)\n s_frame = s_frame[0:int(cap_h*0.7), 0:int(cap_w)]\n except:\n return -1\n\n black = np.zeros([s_frame.shape[:2][0], s_frame.shape[:2][1], 1], dtype=\"uint8\") # для фильтра черный фон\n\n # покадровая маска\n mask_red = cv2.inRange(cv2.medianBlur(s_frame, 5), lower_red, upper_red) # blured\n\n # морфологические преобразования\n mask_red1 = cv2.morphologyEx(mask_red, cv2.MORPH_OPEN, kernel)\n mask_red1 = cv2.morphologyEx(mask_red1, cv2.MORPH_CLOSE, kernel)\n\n # магия с последовательным изчезновением красного\n if len(red_mask_mass) < 4: # задержка в кадрах перед исчезновением красной области\n red_mask_mass.append(mask_red1)\n else:\n red_mask_mass.pop(0)\n red_mask_mass.append(mask_red1)\n\n sum_rmask = mask_red1\n if len(red_mask_mass) > 0:\n for rmask in red_mask_mass:\n sum_rmask = cv2.addWeighted(rmask, 0.5, sum_rmask, 1, 1)\n # cv2.imshow('summ_rmask', sum_rmask)\n\n # порог\n ret, thresh = cv2.threshold(sum_rmask, 127, 255, cv2.THRESH_BINARY)\n _, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # разобраться\n\n res = epsareas_func(contours, s_frame, frame_count, filename, black)\n if res:\n return res\n frame_count += frame_skip #\n else:\n # ret1, s_frame = cap.read()\n frame_count += 1 #\n\n if cv2.waitKey(50) & 0xFF == ord('q'):\n print(-1)\n break\n\n return -1\n\nstart_time = time.time()\ntext_file = \"C:/Users/janch/PycharmProjects/visionhack/output1_rev8.txt\"\n# r = re.compile(\".*avi\")\nfiles = [f for f in os.listdir('C:/Users/janch/Desktop/validationset')]\n# files = filter(r.match, files)\n\nfor file in files:\n filepath = ('C:/Users/janch/Desktop/validationset/%s' % file)\n\n cap_timestart = time.time()\n\n cap = cv2.VideoCapture(filepath)\n cap_w = cap.get(cv2.CAP_PROP_FRAME_WIDTH)\n cap_h = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)\n\n ret1, s_frame = cap.read()\n\n # cv2.imshow(\"s_frm\", s_frame)\n frame_count = 0\n kernel = np.ones((4, 4), np.uint8) # ядро для красного цвета\n red_mask_mass = []\n\n out = main(frame_count, kernel, red_mask_mass, file)\n\n if out <= 15:\n out = -1\n with open(text_file, 'a') as text:\n text.write(\"%s %s \\n\" % (file, out))\n cap.release()\n cv2.destroyAllWindows()\n print(\"--- %s seconds --- %s\" % (time.time() - cap_timestart, file))\n\n# time\nprint(\"--- %s seconds at all ---\" % (time.time() - start_time))\n\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"46544353","text":"# main imports\nimport sys, os, argparse, json\nimport numpy as np\n\n# models imports\nfrom keras.models import model_from_json\nfrom sklearn.externals import joblib\n\n# image processing imports\nfrom ipfml import processing, utils\nfrom PIL import Image\n\n# modules imports\nsys.path.insert(0, '') # trick to enable import of main folder module\n\nimport custom_config as cfg\nfrom data_attributes import get_image_features\n\n# variables and parameters\npath = cfg.dataset_path\nmin_max_ext = cfg.min_max_filename_extension\nfeatures_choices = cfg.features_choices_labels\nnormalization_choices = cfg.normalization_choices\n\ncustom_min_max_folder = cfg.min_max_custom_folder\n\ndef main():\n\n # getting all params\n parser = argparse.ArgumentParser(description=\"Script which detects if an image is noisy or not using specific model\")\n\n parser.add_argument('--image', type=str, help='Image path')\n parser.add_argument('--solution', type=str, help='Data of solution to specify filters to use')\n parser.add_argument('--model', type=str, help='.joblib or .json file (sklearn or keras model)')\n parser.add_argument('--mode', type=str, help='Kind of normalization level wished', choices=normalization_choices)\n parser.add_argument('--feature', type=str, help='feature data choice', choices=features_choices)\n parser.add_argument('--custom', type=str, help='Name of custom min max file if use of renormalization of data', default=False)\n\n args = parser.parse_args()\n\n p_img_file = args.image\n p_model_file = args.model\n p_solution = list(map(int, args.solution.split(' ')))\n p_mode = args.mode\n p_feature = args.feature\n p_custom = args.custom\n\n if '.joblib' in p_model_file:\n kind_model = 'sklearn'\n\n if '.json' in p_model_file:\n kind_model = 'keras'\n\n if kind_model == 'sklearn':\n # load of model file\n model = joblib.load(p_model_file)\n\n if kind_model == 'keras':\n with open(p_model_file, 'r') as f:\n json_model = json.load(f)\n model = model_from_json(json_model)\n model.load_weights(p_model_file.replace('.json', '.h5'))\n\n model.compile(loss='binary_crossentropy',\n optimizer='adam',\n features=['accuracy'])\n\n # load image\n img = Image.open(p_img_file)\n\n data = get_image_features(p_feature, img)\n\n # get indices of filters data to use (filters selection from solution)\n indices = []\n\n for index, value in enumerate(p_solution): \n if value == 1: \n indices.append(index)\n\n # No need to use custom normalization with this kind of process \n # check mode to normalize data\n if p_mode == 'svdne':\n\n # set min_max_filename if custom use\n min_max_file_path = os.path.join(path, p_feature + min_max_ext)\n\n # need to read min_max_file\n with open(min_max_file_path, 'r') as f:\n min_val = float(f.readline().replace('\\n', ''))\n max_val = float(f.readline().replace('\\n', ''))\n\n l_values = utils.normalize_arr_with_range(data, min_val, max_val)\n\n elif p_mode == 'svdn':\n l_values = utils.normalize_arr(data)\n else:\n l_values = data\n\n test_data = np.array(l_values)[indices]\n\n # get prediction of model\n if kind_model == 'sklearn':\n prediction = model.predict([test_data])[0]\n\n if kind_model == 'keras':\n test_data = np.asarray(test_data).reshape(1, len(test_data), 1)\n prediction = model.predict_classes([test_data])[0][0]\n\n # output expected from others scripts\n print(prediction)\n\nif __name__== \"__main__\":\n main()\n","sub_path":"prediction/predict_noisy_image_svd_attributes.py","file_name":"predict_noisy_image_svd_attributes.py","file_ext":"py","file_size_in_byte":3675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"52461787","text":"# -*- coding: UTF-8 -*-\n'''\n@author: Andrewzhj\n@contact: andrew_zhj@126.com\n@file: logistic_regression.py\n@time: 3/25/19 10:37 PM\n@desc: 良/恶性乳腺癌肿瘤数据训练\n@note:\n'''\n\nimport pandas as pd\nimport numpy as np\nimport ssl\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import classification_report\nfrom sklearn.svm import LinearSVC\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.feature_extraction import DictVectorizer\nssl._create_default_https_context = ssl._create_unverified_context\n\n\n# 良/恶性乳腺癌肿瘤数据训练\nclass LogisticRegressionTrain(object):\n '''\n 初始化数据地址\n '''\n\n def __init__(self):\n self.bathUrl = \"https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/\"\n self.dataFile = \"breast-cancer-wisconsin.data\"\n self.column_names = ['Sample code number', 'Clump Thickness', 'Uniformity of Cell Size',\n 'Uniformity of Cell Shape', 'Marginal Adhesion', 'Single Epithelial Cell Size', 'Bare Nuclei',\n 'Blan Chromatin', 'Normal Nucleoli', 'Mitoses', 'Class']\n\n '''\n 获取数据\n '''\n\n def get_data(self):\n url = self.bathUrl + self.dataFile\n # 读取数据\n data = pd.read_csv(url, names=self.column_names)\n # 将?转换为标准缺失值\n data = data.replace(to_replace='?', value=np.nan)\n # 丢弃带有缺失值的数据\n data = data.dropna(how='any')\n return data\n\n '''\n 逻辑回归训练\n 精确计算逻辑回归参数\n '''\n\n def logistic_train(self):\n data = self.get_data()\n # 创建特征列表\n x_train, x_test, y_train, y_test = train_test_split(data[self.column_names[1:10]], data[self.column_names[10]],\n test_size=0.25, random_state=33)\n print(y_train.value_counts())\n print(y_test.value_counts())\n print(data.shape)\n ss = StandardScaler()\n x_train = ss.fit_transform(x_train)\n x_test = ss.transform(x_test)\n lr = LogisticRegression()\n lr.fit(x_train, y_train)\n lr_y_predict = lr.predict(x_test)\n print(\"Accuracy of LR Classifier: \", lr.score(x_test, y_test))\n print(classification_report(y_test, lr_y_predict, target_names=['Benign', 'Malignant']))\n\n '''\n 随机梯度参数估计\n 采用梯度法估计参数\n '''\n\n def sgdc_train(self):\n data = self.get_data()\n # 创建特征列表\n x_train, x_test, y_train, y_test = train_test_split(data[self.column_names[1:10]], data[self.column_names[10]],\n test_size=0.25, random_state=33)\n print(y_train.value_counts())\n print(y_test.value_counts())\n print(data.shape)\n ss = StandardScaler()\n x_train = ss.fit_transform(x_train)\n x_test = ss.transform(x_test)\n sgdc = SGDClassifier()\n sgdc.fit(x_train, y_train)\n sgdc_y_predict = sgdc.predict(x_test)\n print(\"Accuracy of SGD Classifier: \", sgdc.score(x_test, y_test))\n print(classification_report(y_test, sgdc_y_predict, target_names=['Benign', 'Malignant']))\n\n '''\n 支持向量机分类器\n '''\n def svc_train(self):\n data = self.get_data()\n # 创建特征列表\n x_train, x_test, y_train, y_test = train_test_split(data[self.column_names[1:10]], data[self.column_names[10]],\n test_size=0.25, random_state=33)\n print(y_train.value_counts())\n print(y_test.value_counts())\n print(data.shape)\n ss = StandardScaler()\n x_train = ss.fit_transform(x_train)\n x_test = ss.transform(x_test)\n lsvc = LinearSVC()\n lsvc.fit(x_train, y_train)\n y_predict = lsvc.predict(x_test)\n print(\"The Accuracy of Liner SVC is\", lsvc.score(x_test, y_test))\n print(classification_report(y_test, y_predict))\n\n '''\n 决策树模型,不需要线性假设\n '''\n def decision_tree_train(self):\n data = self.get_data()\n # 创建特征列表\n x_train, x_test, y_train, y_test = train_test_split(data[self.column_names[1:10]], data[self.column_names[10]],\n test_size=0.25, random_state=33)\n print(y_train.value_counts())\n print(y_test.value_counts())\n print(data.shape)\n vec = DictVectorizer(sparse=False)\n x_train = vec.fit_transform(x_train.to_dict(orient='record'))\n print(vec.feature_names_)\n x_test = vec.transform(x_test.to_dict(orient='record'))\n dtc = DecisionTreeClassifier()\n dtc.fit(x_train, y_train)\n y_predict = dtc.predict(x_test)\n print(\"The Accuracy of decision tree is \", dtc.score(x_test, y_test))\n print(classification_report(y_test, y_predict))\n\n\nif __name__ == '__main__':\n cancerTrain = LogisticRegressionTrain()\n cancerTrain.logistic_train()\n cancerTrain.sgdc_train()\n cancerTrain.svc_train()\n cancerTrain.decision_tree_train()","sub_path":"classifier_tutorial/logistic_regression.py","file_name":"logistic_regression.py","file_ext":"py","file_size_in_byte":5341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"546552700","text":"from opsgenie.response import BaseResponse\nfrom opsgenie.utility import convert_to_date\n\n\nclass GetAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.tags = self.pop('tags')\n self.count = self.pop('count')\n self.status = self.pop('status')\n self.teams = self.pop('teams')\n self.recipients = self.pop('recipients')\n self.tiny_id = self.pop('tinyId')\n self.alias = self.pop('alias')\n self.entity = self.pop('entity')\n self.id = self.pop('id')\n self.updated_at = convert_to_date(self.pop('updatedAt'))\n self.message = self.pop('message')\n self.details = self.pop('details')\n self.source = self.pop('source')\n self.description = self.pop('description')\n self.created_at = convert_to_date(self.pop('createdAt'))\n self.is_seen = self.pop('isSeen')\n self.acknowledged = self.pop('acknowledged')\n self.owner = self.pop('owner')\n self.actions = self.pop('actions')\n self.system_data = self.pop('systemData')\n\n self.decode()\n\n\nclass ListAlertsResponse(BaseResponse):\n class AlertResponse:\n def __init__(self, **kwargs):\n self.id = kwargs.get('id')\n self.alias = kwargs.get('alias')\n self.message = kwargs.get('message')\n self.status = kwargs.get('status')\n self.is_seen = kwargs.get('isSeen')\n self.acknowledged = kwargs.get('acknowledged')\n self.created_at = convert_to_date(kwargs.get('createdAt'))\n self.updated_at = convert_to_date(kwargs.get('updatedAt'))\n self.tiny_id = kwargs.get('tinyId')\n self.owner = kwargs.get('owner')\n\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.alerts = []\n for alert in self.pop('alerts', []):\n self.alerts.append(ListAlertsResponse.AlertResponse(**alert))\n\n self.decode()\n\n\nclass ListAlertLogsResponse(BaseResponse):\n class AlertLogResponse:\n def __init__(self, **kwargs):\n self.log = kwargs.get('log')\n self.log_type = kwargs.get('logType')\n self.owner = kwargs.get('owner')\n self.created_at = convert_to_date(kwargs.get('createdAt'))\n\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.logs = []\n for log in self.pop('logs', []):\n self.logs.append(ListAlertLogsResponse.AlertLogResponse(**log))\n\n self.lastKey = self.pop('lastKey')\n\n self.decode()\n\n\nclass ListAlertNotesResponse(BaseResponse):\n class AlertNoteResponse:\n def __init__(self, **kwargs):\n self.note = kwargs.get('note')\n self.owner = kwargs.get('owner')\n self.created_at = convert_to_date(kwargs.get('createdAt'))\n\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.took = self.pop('took')\n self.last_key = self.pop('lastKey')\n self.notes = []\n for note in self.pop('notes', []):\n self.notes.append(ListAlertNotesResponse.AlertNoteResponse(**note))\n\n self.decode()\n\n\nclass ListAlertRecipientsResponse(BaseResponse):\n class UserResponse:\n def __init__(self, **kwargs):\n self.username = kwargs.get('username')\n self.state = kwargs.get('state')\n self.method = kwargs.get('method')\n self.state_changed_at = convert_to_date(kwargs.get('stateChangedAt'))\n\n class GroupResponse:\n def __init__(self, **kwargs):\n self.username = kwargs.get('username')\n self.state = kwargs.get('state')\n self.method = kwargs.get('method')\n self.state_changed_at = convert_to_date(kwargs.get('stateChangedAt'))\n\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.users = []\n for user in self.pop('users', []):\n self.users.append(ListAlertRecipientsResponse.UserResponse(**user))\n\n self.groups = []\n for group in self.pop('groups', []):\n self.groups.append(ListAlertRecipientsResponse.GroupResponse(**group))\n\n self.decode()\n\n\nclass CreateAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.message = self.pop('message')\n self.alert_id = self.pop('alertId')\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass CloseAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass DeleteAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass CountAlertsResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.count = self.pop('count')\n\n self.decode()\n\n\nclass AcknowledgeAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass UnAcknowledgeAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass SnoozeAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass RenotifyAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass TakeOwnershipOfAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass AssignOwnerToAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass AddTeamToAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass AddRecipientToAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass AddNoteToAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass AddTagsToAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass RemoveTagsFromAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass AddDetailsToAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass RemoveDetailsFromAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass ExecuteActionOfAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass AttachFileToAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass EscalateToNextResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n","sub_path":"opsgenie/alert/responses.py","file_name":"responses.py","file_ext":"py","file_size_in_byte":8860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"317980937","text":"#!/usr/bin/env python\n__author__ = ''\n\nimport random\nfrom math import sqrt\n\nl1 = [2, -5, 8, 9, -25, 25, 4]\n\ndate = '01.11.2013'\n\nMONTHS = {\"Jan\": \"1\", \"Feb\": 2, \"Mar\": 3, \"Apr\": 4, \"May\": 5, \"Jun\": 6,\n \"Jul\": \"7\", \"Aug\": 8, \"Sep\":9, \"Oct\": 10, \"11\": \"Nov\", \"Dec\": 12\n }\nDAYS = {\"01\": \"first\" , \"second\": \"02\", \"third\": \"03\", \"fourth\": \"04\", \"fifth\": \"05\",\n \"sixth\": \"06\", \"seventh\": \"07\", \"eight\": \"08\", \"ninth\": \"09\", \"tenth\": \"10\",\n \"eleventh\": \"11\", \"twelfth\": \"12\", \"thirteen\": \"13\", \"fourteenth\": \"14\",\n \"fifteenth\": \"15\", \"sixteenth\": \"16\", \"seventeenth\": \"17\",\n \"eighteenth\": \"18\", \"nineteenth\": \"19\", \"twentieth\": \"20\", \"twenty first\": \"21\",\n \"twenty second\": \"22\", \"twenty third\": \"23\", \"twenty fourth\": \"24\",\n \"twenty fifth\": \"25\", \"twenty sixth\": \"26\", \"twenty seventh\": \"27\",\n \"twenty eight\": \"28\", \"twenty ninth\": \"29\", \"thirtieth\": \"30\",\n \"thirty first\": \"31\"\n }\n\n\ndef represent_date(date):\n\n date_elements = date.split('.')\n day = date_elements[0]\n month = date_elements[1]\n year = date_elements[2]\n formatted_date = f\"Date: {DAYS.get(day)} {MONTHS.get(month)} {year}\"\n return formatted_date\n\n\ndef whole_sqrt_list(origin_list):\n new_list = []\n for num in origin_list:\n if num >= 0:\n new_el = sqrt(num)\n if new_el.is_integer(): # float(5.0).is_integer == True\n new_list.append(int(new_el))\n return new_list\n\n\ndef main():\n print(f\"OldList: {l1}\\nNewList: {whole_sqrt_list(l1)}\")\n print(represent_date(date))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"practice/hw02_normal01.py","file_name":"hw02_normal01.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"113580876","text":"# This file is Copyright 2010 Dean Hall.\n#\n# This file is part of the Python-on-a-Chip program.\n# Python-on-a-Chip is free software: you can redistribute it and/or modify\n# it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE Version 2.1.\n#\n# Python-on-a-Chip 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.\n# A copy of the GNU LESSER GENERAL PUBLIC LICENSE Version 2.1\n# is seen in the file COPYING up one directory from this.\n\nPM_FEATURES = {\n \"HAVE_PRINT\": True,\n \"HAVE_GC\": True,\n \"HAVE_FLOAT\": False,\n \"HAVE_DEL\": True,\n \"HAVE_IMPORTS\": True,\n \"HAVE_DEFAULTARGS\": True,\n \"HAVE_REPLICATION\": True,\n \"HAVE_CLASSES\": True,\n \"HAVE_ASSERT\": True,\n \"HAVE_GENERATORS\": True,\n \"HAVE_BACKTICK\": True,\n \"HAVE_STRING_FORMAT\": False,\n \"HAVE_CLOSURES\": True,\n \"HAVE_BYTEARRAY\": True,\n \"HAVE_DEBUG_INFO\": True,\n}\n","sub_path":"pmfeatures.py","file_name":"pmfeatures.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"108374035","text":"from typing import Optional, Callable\nfrom datetime import datetime\nfrom time import time\nimport hashlib\nfrom xml.dom.minidom import parseString as parser_xml_from_str\n\nimport arrow\n\n\nasync def send_response_in_one_call(send, status: int, message: bytes = b\"\") -> None:\n \"\"\"moved to DAVResponse.send_in_one_call()\"\"\"\n headers = [\n (b\"Content-Type\", b\"text/html\"),\n # (b'Content-Type', b'application/xml'),\n (b\"Content-Length\", bytes(str(len(message)), encoding=\"utf8\")),\n (b\"Date\", bytes(datetime.utcnow().isoformat(), encoding=\"utf8\")),\n ]\n await send(\n {\n \"type\": \"http.response.start\",\n \"status\": status,\n \"headers\": headers,\n }\n )\n await send(\n {\n \"type\": \"http.response.body\",\n \"body\": message,\n }\n )\n\n return\n\n\nasync def receive_all_data_in_one_call(receive: Callable) -> bytes:\n data = b\"\"\n more_body = True\n while more_body:\n request_data = await receive()\n data += request_data.get(\"body\", b\"\")\n more_body = request_data.get(\"more_body\")\n\n return data\n\n\nclass DAVTime:\n def __init__(self, timestamp: Optional[float] = None):\n if timestamp is None:\n timestamp = time()\n\n self.timestamp = timestamp\n self.arrow = arrow.get(timestamp)\n\n def iso_850(self) -> str:\n # https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Last-Modified\n # Last-Modified:\n # , :: GMT\n return self.arrow.format(arrow.FORMAT_RFC850)\n\n def iso_8601(self) -> str:\n return self.arrow.format(arrow.FORMAT_W3C)\n\n\ndef generate_etag(f_size: [float, int], f_modify_time: float) -> str:\n \"\"\"\n https://tools.ietf.org/html/rfc7232#section-2.3 ETag\n https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/ETag\n \"\"\"\n return 'W/\"{}\"'.format(\n hashlib.md5(\"{}{}\".format(f_size, f_modify_time).encode(\"utf-8\")).hexdigest()\n )\n\n\ndef pprint_xml(xml_str):\n xml = parser_xml_from_str(xml_str).toprettyxml()\n print(xml)\n","sub_path":"asgi_webdav/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"154546281","text":"import web\n\nfrom datetime import datetime, date, timedelta\n\nfrom databaseoperations import *\n\n\nrender = web.template.render('templates/')\n\nurls = (\n '/', 'solar_home',\n '/system_overview/([s]\\d+)', 'system_overview',\n '/api/add/([s]\\d+)', 'add'\n)\napp = web.application(urls, globals())\napp = app.wsgifunc()\n\nclass solar_home:\n def GET(self):\n return 'hi'\n\nclass system_overview: \n def GET(self, system):\n '''\n Send a page with data on the requested system\n \n @parameter system - the system number\n\n @return - a html page with information on the system\n ''' \n current_timestamp = datetime.now()\n days_ago = current_timestamp - timedelta(7)\n hours_ago = current_timestamp - timedelta(hours = 7)\n\n data1 = get_many(str(system), 'hour', hours_ago, current_timestamp)\n\n data2 = get_many(str(system), 'day', days_ago, current_timestamp)\n \n\n return render.solar_home(data1, data2)\n\nclass add:\n def GET(self, system):\n return 'add entries here for ' + system + ' here' \n\n def POST(self, system):\n pass \n\n\n\nif __name__ == \"__main__\":\n app = web.application(urls, globals())\n app.run()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"444224","text":"import numpy as np\nimport os\nfrom random import shuffle\nimport re\nimport tensorflow as tf\nimport sys\nimport urllib.request\nimport zipfile\nimport lxml.etree\nimport json\nimport math\nfrom shuffle import Shuffle as SF\nfrom prepare_sentences import Preparer\nfrom dataParser import DataParser\nfrom config import CONFIG\nimport tensorflow.contrib.seq2seq as seq2seq\nfrom tensorflow.contrib.rnn import LSTMCell, GRUCell, BasicRNNCell\n \nclass SummaryModel(object):\n \n def output_fn(self, outputs):\n return tf.contrib.layers.linear(outputs, CONFIG.DIM_VOCAB) \n def project_encoder_last_states(self, encoder_last_states):\n return tf.contrib.layers.linear(encoder_last_states, 2* CONFIG.DIM_WordEmbedding)\n def __init__(self, is_training):\n \n ''' Init all constants, embedding, and cell'''\n self.is_training = is_training\n # load the word embedding, init by random\n #self.embedding = tf.get_variable('embedding',initializer=CONFIG.w2vMatrix)\n self.embedding = tf.get_variable('embedding', shape=[CONFIG.DIM_VOCAB, CONFIG.DIM_WordEmbedding], initializer=tf.random_uniform_initializer(-0.1, 0.1)) \n #self.embedding = tf.get_variable('embedding', shape = [CONFIG.DIM_VOCAB, CONFIG.DIM_WordEmbedding], initializer = tf.contrib.layers.xavier_initializer())\n self.addPlaceholders()\n self.addEncoder()\n self.addDecoder()\n print ('model built') \n \n if (self.is_training):\n self.decoder_outputs = tf.nn.dropout(self.decoder_outputs, CONFIG.KEEPPROB)\n # this is before projection, try masking here\n \n self.u = self.output_fn(self.decoder_outputs)\n self.cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=self.label_placeholder, logits=self.u)\n #self.cross_entropy = tf.reduce_sum(self.u)\n \n # mask entropy with mask\n self.masked_cross_entropy = self.cross_entropy * self.Mplaceholder\n mean_loss_by_example = tf.reduce_sum(self.masked_cross_entropy, reduction_indices = 1)\n self.mean_loss = tf.reduce_mean(mean_loss_by_example)\n \n #self.train_op = tf.train.AdamOptimizer(learning_rate = self.learning_rate).minimize(self.mean_loss)\n optimizer = tf.train.AdamOptimizer(learning_rate = self.learning_rate)\n #self.var_grad = tf.gradients(self.mean_loss, [self._decoder_in_state])[0]\n gvs = optimizer.compute_gradients(self.mean_loss)\n #capped_gvs = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gvs]\n self.train_op = optimizer.apply_gradients(gvs)\n else:\n\n self.output_words = tf.cast(tf.argmax(self.decoder_outputs, axis = -1),tf.int32)\n \n \n \n # helper functions \n def addEncoder(self):\n print ('adding encoder...')\n self.encoder_inputs = tf.nn.embedding_lookup(self.embedding, self.x_placeholder)\n if (self.is_training):\n self.encoder_inputs = tf.nn.dropout(self.encoder_inputs, CONFIG.KEEPPROB)\n cell_fw = GRUCell(CONFIG.DIM_WordEmbedding)\n cell_bw = GRUCell(CONFIG.DIM_WordEmbedding)\n (encoder_output_fw, encoder_output_bw), (fw_state, bw_state) = tf.nn.bidirectional_dynamic_rnn(cell_fw, cell_bw, self.encoder_inputs, dtype=tf.float32, sequence_length=self.x_lens)\n # concatenate the bidirectional inputs\n self._encoder_outputs = tf.concat([encoder_output_fw, encoder_output_bw],2)\n self._decoder_in_state = self.project_encoder_last_states(bw_state)\n #self._decoder_in_state = tf.concat([fw_state, bw_state],1)\n self.attention_states = self._encoder_outputs\n #self._decoder_in_state = tf.zeros(shape=[CONFIG.BATCH_SIZE, CONFIG.DIM_WordEmbedding *2], dtype=tf.float32)\n #self.attention_states = tf.zeros(shape=[CONFIG.BATCH_SIZE, CONFIG.DIM_RNN, CONFIG.DIM_WordEmbedding * 2])\n def addDecoder(self):\n print ('adding decoder...')\n cell = GRUCell(2* CONFIG.DIM_WordEmbedding)\n self.attention_states = self._encoder_outputs\n self.decoder_inputs_embedded = tf.nn.embedding_lookup(self.embedding, self.y_placeholder)\n # prepare attention: \n (attention_keys, attention_values, attention_score_fn, attention_construct_fn) = seq2seq.prepare_attention(attention_states=self.attention_states, attention_option='bahdanau', num_units=2* CONFIG.DIM_WordEmbedding)\n \n if (self.is_training): \n # new Seq2seq train version\n self.check_op = tf.add_check_numerics_ops()\n decoder_fn_train = seq2seq.attention_decoder_fn_train(encoder_state=self._decoder_in_state, attention_keys=attention_keys, attention_values=attention_values, attention_score_fn=attention_score_fn, attention_construct_fn=attention_construct_fn, name='attention_decoder')\n (self.decoder_outputs_train, self.decoder_state_train, self.decoder_context_state_train) = seq2seq.dynamic_rnn_decoder(cell=cell, decoder_fn=decoder_fn_train, inputs=self.decoder_inputs_embedded, sequence_length=self.y_lens, time_major=False)\n self.decoder_outputs = self.decoder_outputs_train\n \n else:\n \n # new Seq2seq version\n start_id = CONFIG.WORDS[CONFIG.STARTWORD]\n stop_id = CONFIG.WORDS[CONFIG.STOPWORD]\n decoder_fn_inference = seq2seq.attention_decoder_fn_inference(encoder_state=self._decoder_in_state, attention_keys = attention_keys, attention_values=attention_values, attention_score_fn=attention_score_fn, attention_construct_fn=attention_construct_fn, embeddings=self.embedding, start_of_sequence_id=start_id, end_of_sequence_id = stop_id, maximum_length = CONFIG.DIM_DECODER, num_decoder_symbols=CONFIG.DIM_VOCAB, output_fn = self.output_fn )\n (self.decoder_outputs_inference, self.decoder_state_inference, self.decoder_context_state_inference) = seq2seq.dynamic_rnn_decoder(cell=cell, decoder_fn=decoder_fn_inference, time_major=False)\n self.decoder_outputs = self.decoder_outputs_inference\n \n \n def addPlaceholders(self):\n self.x_placeholder = tf.placeholder(tf.int32, [CONFIG.BATCH_SIZE, CONFIG.DIM_RNN])\n self.y_placeholder = tf.placeholder(tf.int32, [CONFIG.BATCH_SIZE, CONFIG.DIM_DECODER-1])\n self.label_placeholder = tf.placeholder(tf.int32, [CONFIG.BATCH_SIZE, None])\n self.x_lens = tf.placeholder(tf.int32, [CONFIG.BATCH_SIZE])\n self.y_lens = tf.placeholder(tf.int32, [CONFIG.BATCH_SIZE])\n self.learning_rate = tf.placeholder(tf.float32)\n self.Mplaceholder = tf.placeholder(tf.float32, [CONFIG.BATCH_SIZE, None]) # Mask for the output sequence\n \n def getMask(self, lens, DIM_RNN):\n mask = []\n for i in range(CONFIG.BATCH_SIZE):\n temp = [1.0 if j0):\n break\n it += 1\n _,doc_valid, summary_valid, docLens_valid, sumLens_valid = tup\n doc_batch_v = _get_doc_batch(doc_valid)\n summary_batch_v = _get_summary_batch(summary_valid)\n label_batch_v = _get_label_batch(summary_valid)\n m_valid.run_valid_step(sess, doc_batch_v, summary_batch_v, label_batch_v, np.array(docLens_valid), np.array(sumLens_valid)) \n iters += 1\n \n \ndef _initWordDic(from_word2Vec=False):\n# Load the words into WORDS dictionary of CONFIG\n if not (from_word2Vec):\n with open(CONFIG.WORDFILE, 'r') as wordsFile:\n for l in wordsFile:\n word, freq = l.split()\n freq = int(freq)\n if (freq > 1):\n # only record the words having frequency > 1\n CONFIG.WORDS[word] = len(CONFIG.WORDS)\n CONFIG.WORDSLIST.append(word)\n else:\n #CONFIG.WORDS[word] = len(CONFIG.WORDS)\n #CONFIG.WORDSLIST.append(word)\n break \n # now update the dimension\n CONFIG.WORDS[CONFIG.PADDING] = len(CONFIG.WORDS)\n CONFIG.WORDS[CONFIG.UNKNOWN] = len(CONFIG.WORDS)\n CONFIG.WORDS[CONFIG.STARTWORD] = len(CONFIG.WORDS)\n CONFIG.WORDS[CONFIG.STOPWORD] = len(CONFIG.WORDS)\n CONFIG.DIM_VOCAB = len(CONFIG.WORDS)\n CONFIG.WORDSLIST.extend([CONFIG.PADDING, CONFIG.UNKNOWN, CONFIG.STARTWORD, CONFIG.STOPWORD]) \n else:\n # load the word2vec model\n from gensim.models import Word2Vec\n model_ted = Word2Vec.load(CONFIG.WORDMODELFILE)\n w2vMatrix = model_ted.syn0\n #TODO: add random vectors rep padding, unknown, startword, stopword\n w2vIndex = model_ted.index2word\n for wd in w2vIndex:\n CONFIG.WORDS[wd] = len(CONFIG.WORDS)\n CONFIG.WORDSLIST.append(wd)\n CONFIG.WORDS[CONFIG.PADDING] = len(CONFIG.WORDS)\n CONFIG.WORDS[CONFIG.UNKNOWN] = len(CONFIG.WORDS)\n CONFIG.WORDS[CONFIG.STARTWORD] = len(CONFIG.WORDS)\n CONFIG.WORDS[CONFIG.STOPWORD] = len(CONFIG.WORDS)\n CONFIG.DIM_VOCAB = len(CONFIG.WORDS)\n CONFIG.WORDSLIST.extend([CONFIG.PADDING, CONFIG.UNKNOWN, CONFIG.STARTWORD, CONFIG.STOPWORD])\n append_vec = np.random.uniform(low=0.0, high = 1.0, size=[4,CONFIG.DIM_WordEmbedding])\n # concatenate this vector to the w2vMatrix\n CONFIG.w2vMatrix = np.concatenate((w2vMatrix, append_vec), axis=0)\n \n \n\ndef main():\n _initWordDic(True)\n # parse the data using dataParser\n parser = DataParser()\n docs, summary = parser.parseFile()\n p_doc = Preparer(docs)\n p_summary = Preparer(summary, is_summary=True)\n p_doc.cutDocs()\n p_summary.cutDocs()\n docLens = p_doc.countDocs()\n sumLens = p_summary.countDocs()\n print (max(sumLens))\n #sys.exit()\n p_doc.doc2Int()\n p_summary.doc2Int()\n # docs, docLens, summary, sumLens are the data\n data = list(zip(docs, summary, docLens, sumLens))\n training_data = data[:1585]\n validation_data = data[:1835]\n testing_data = data[1835:] \n \n ''' FIXING THE DIMENSION ISSUES OF BATCHES\n sf_train = SF(training_data, CONFIG.BATCH_SIZE, is_training = True)\n sf_valid = SF(validation_data, CONFIG.BATCH_SIZE, is_training = False)\n for tup in sf_train.get_batch(): \n _, doc, summary, docLens, sumLens = tup\n doc_batch = _get_doc_batch(doc)\n summary_batch = _get_summary_batch(summary)\n label_batch = _get_label_batch(summary)\n docLens = np.array(docLens)\n summaryLens = np.array(sumLens) \n print (doc_batch[0])\n print (summary_batch[0])\n print (label_batch[0])\n print (list(doc for doc in docLens))\n print (list(doc for doc in summaryLens))\n sys.exit()'''\n \n with tf.Graph().as_default():\n initializer = tf.random_uniform_initializer(-0.1, 0.1)\n with tf.name_scope('Train'):\n with tf.variable_scope('Model', reuse=None, initializer=initializer):\n m = SummaryModel(is_training=True) \n with tf.name_scope('Valid'):\n with tf.variable_scope('Model', reuse=True, initializer=initializer):\n m_valid = SummaryModel(is_training=False) \n with tf.name_scope('Test'):\n with tf.variable_scope('Model', reuse=True, initializer=initializer):\n m_test = SummaryModel(is_training=False)\n \n init_op = tf.global_variables_initializer()\n sess = tf.Session()\n sess.run(init_op)\n for epoch in range(CONFIG.EPOCH):\n print ('---------------running ' + str(epoch) + 'th epoch ----------------')\n run_epoch(sess, m, m_valid, training_data, validation_data)\n\nmain()\n \n \n \n \n \n","sub_path":"open/summarizer_debug.py","file_name":"summarizer_debug.py","file_ext":"py","file_size_in_byte":16168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"158141886","text":"\nimport pickle\nfrom collections import namedtuple\nimport logging\nimport os\n\nimport master_data_creation as mdc\nimport conditional_volatility_model as cvm\nimport classification_models as cm\nimport sharpe_ratio_generation as srg\n\n\nclass MasterRunResults:\n\n def __init__(self, stock, fitted_classifier_ensemble, class_predictions, sharpe_projection, current_price,\n cointegration_set, estimated_variance):\n self.stock = stock\n self.fitted_classifier_ensemble = fitted_classifier_ensemble\n self.class_predictions = class_predictions\n self.sharpe_projection = sharpe_projection\n self.current_price = current_price\n self.cointegration_set = cointegration_set\n self.estimated_variance = estimated_variance\n\n# Create master run function to perform data engineering, classification fit, classification predict for a single stock\nclass MasterRun:\n def __init__(self, data):\n self.data = data\n\n def master_run(self, stock):\n try:\n logging.info('Running for {}'.format(stock))\n current_price = self.data.stock_dict[stock]['ADJ_CLOSE'][-1:].item()\n\n # Fit conditional volatility models to Returns\n mean_returns = self.data.stock_dict[stock]['RETURN'].mean()\n variance_of_returns = ((self.data.stock_dict[stock]['RETURN']-mean_returns)**2)\n vm = cvm.VolatilityModels(variance_of_returns)\n #volatility, fitted_model = vm.create_hmm_model()\n fitted_volatility, fitted_model = vm.create_hmm_model(n_states=3)\n\n # Create master table, a collection of labels and key exogenous variables\n engineer = mdc.CreateMasterTable(stock, self.data, fitted_volatility, mean_returns, bound_limits=1.5)\n master_table, cointegration_set = engineer.base_table_create()\n\n # Fit classification models\n modeler = cm.ClassifierEnsemble(stock, master_table)\n fitted_ensemble = modeler.fit_classifier_ensemble()\n\n # Predict Classification\n current_state = master_table[-1:]\n predicted_probabilities = fitted_ensemble.predict(current_state)\n\n # Simulate returns based on the assigned classification and volatility estimates\n simulation = srg.SharpePredict(fitted_model, predicted_probabilities, bound_limits=1.5)\n sharpe_ratio_projection, sigma_estimate = simulation.generate_sharpe_projection()\n\n # Save the results\n results = MasterRunResults(stock, fitted_ensemble, predicted_probabilities, sharpe_ratio_projection,\n current_price, cointegration_set, sigma_estimate)\n self.save_master_results(stock, results)\n\n except Exception as e:\n logging.info('Master run failed on {}, failure was {}'.format(stock, e))\n\n def save_master_results(self, stock, results):\n file_path = open(os.path.join(self.data.results_data_path, '{}_results.p'.format(stock)), 'wb')\n pickle.dump(results, file_path)\n file_path.close()\n","sub_path":"code/master_run_functions.py","file_name":"master_run_functions.py","file_ext":"py","file_size_in_byte":3089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"166212296","text":"def loop_daily_load(start_year, end_year, start_month, end_month, start_day, end_day):\n # Update the database as NASA adds data\n import MakeDailyCsv\n import LoadDailyMysql\n from generator import generate\n\n year_list = generate(start_year, end_year, 4)\n month_list = generate(start_month, end_month, 2)\n day_list = generate(start_day, end_day, 2)\n\n for year in year_list:\n for month in month_list:\n for day in day_list:\n MakeDailyCsv.make_daily_csv(year, month, day)\n LoadDailyMysql.Load_Daily_Mysql(year, month, day)\n\n","sub_path":"python/Updator/Updator.py","file_name":"Updator.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"137724161","text":"# -*- coding: utf-8 -*-\nimport datetime\n\nfrom django.db import models\n\ndef purificador(nombre):\n \n nombre_copia = nombre\n \n nombre = \"\"\n \n for n in nombre_copia.split(' '):\n \n if not n.isalpha():\n raise\n \n nombre = nombre + \" \" + n.capitalize()\n \n if nombre.startswith(' '):\n nombre = nombre[1:]\n \n return nombre\n\ndef esCUITValida(cuit):\n \n cuit = str(cuit)\n cuit = cuit.replace(\"-\", \"\")\n cuit = cuit.replace(\" \", \"\")\n cuit = cuit.replace(\".\", \"\")\n \n if len(cuit) != 11:\n return False\n \n if not cuit.isdigit():\n return False\n \n base = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2]\n aux = 0\n for i in xrange(10):\n aux += int(cuit[i]) * base[i]\n \n aux = 11 - (aux % 11)\n \n if aux == 11:\n aux = 0\n elif aux == 10:\n aux = 9\n \n if int(cuit[10]) == aux:\n return True\n else:\n return False\n\nclass Persona(models.Model):\n \n nombre = models.CharField(max_length=100, null=False, blank=False)\n apellido = models.CharField(max_length=100, null=False, blank=False)\n fecha_nacimiento = models.DateField(null=False, blank=False)\n cuil = models.CharField(max_length=13, null=False, blank=False)\n genero = models.CharField(max_length=1,\n choices=[('F', 'F'), ('M', 'M')],\n default='F')\n estado = models.CharField(max_length=3,\n choices=[('ON', 'ON'), ('OFF', 'OFF')],\n default='ON')\n usuario_creador = models.CharField(max_length=30, default='admin')\n fecha_creacion = models.DateTimeField(auto_now_add=True)\n usuario_modificador = models.CharField(max_length=30, default='admin')\n fecha_modificacion = models.DateTimeField(auto_now=True)\n \n def __str__(self, ):\n return (self.apellido + \", \" + self.nombre).encode('utf-8')\n \n def __eq__(self, o):\n return self.cuil == o.cuil\n \n def set_nombre(self, nombre):\n \n if nombre == \"\":\n raise Exception(\"El nombre no puede estar vacío.\")\n \n try:\n nombre = purificador(nombre)\n except:\n raise Exception(\"El nombre posee caracteres no permitidos.\")\n \n self.nombre = nombre\n \n def set_apellido(self, apellido):\n \n if apellido == \"\":\n raise Exception(\"El apellido no puede estar vacío.\")\n \n try:\n apellido = purificador(apellido)\n except:\n raise Exception(\"El apellido posee caracteres no permitidos.\")\n \n self.apellido = apellido\n \n def set_cuil(self, cuil):\n \n if not esCUITValida(cuil):\n raise Exception(\"El cuil no es válido.\")\n \n self.cuil = cuil\n \n def set_fecha_nacimiento(self, fecha_nacimiento):\n \n try:\n fecha_nacimiento = datetime.datetime.strptime(fecha_nacimiento, \"%Y-%m-%d\").date()\n except:\n raise Exception(\"La fecha de nacimiento no es válida.\")\n \n self.fecha_nacimiento = fecha_nacimiento\n \n def set_genero(self, genero):\n \n self.genero = genero\n","sub_path":"perfil/objects/persona.py","file_name":"persona.py","file_ext":"py","file_size_in_byte":3250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"144012100","text":"import re\n\ndef sgn(i):\n\tif i > 0:\n\t\treturn 1\n\telif i == 0:\n\t\treturn 0\n\telse:\n\t\treturn -1\n\npattern = re.compile(r'')\npositions = []\nvelocities = [[0] * 3 for i in range(4)]\nwith open('12.dat', 'r') as file:\n\tfor line in file:\n\t\tmatch = pattern.match(line.strip())\n\t\tassert match\n\t\tpositions.append([int(match.group(1)), int(match.group(2)), int(match.group(3))])\n\nfor cycle in range(1000):\n\tfor moon in range(4):\n\t\tfor other_moon in range(4):\n\t\t\tfor index in range(3):\n\t\t\t\tvelocities[moon][index] += sgn(positions[other_moon][index] - positions[moon][index])\n\n\tfor moon in range(4):\n\t\tfor index in range(3):\n\t\t\tpositions[moon][index] += velocities[moon][index]\n\nenergy = 0\nfor moon in range(4):\n\tenergy += (abs(positions[moon][0]) + abs(positions[moon][1]) + abs(positions[moon][2])) * (\n\t\t\t\tabs(velocities[moon][0]) + abs(velocities[moon][1]) + abs(velocities[moon][2]))\n\nprint(energy)\n","sub_path":"2019/12a.py","file_name":"12a.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"7020200","text":"from django.contrib import admin\r\nfrom .models import tblStudent, tblUnits, tblClasses\r\n\r\nclass StudentAdmin(admin.ModelAdmin):\r\n list_display = ('name_first', 'name_last', 'date_of_birth' ,'gender' ,'id_foreign_classes')\r\n list_filter = ['gender']\r\n search_fields = ['name_first', 'name_last']\r\n\r\n\r\nclass ClassAdmin(admin.ModelAdmin):\r\n list_display = ('class_code', 'id_foreign_unit_1', 'id_foreign_unit_2', 'id_foreign_unit_3')\r\n fieldsets = [\r\n (None, {'fields':['class_code']}),\r\n ('Units', {'fields': ['id_foreign_unit_1',\r\n 'id_foreign_unit_2',\r\n 'id_foreign_unit_3']}),\r\n ]\r\n\r\nclass UnitAdmin(admin.ModelAdmin):\r\n list_display = ('name_unit','description')\r\n\r\n\r\nadmin.site.register(tblStudent, StudentAdmin)\r\nadmin.site.register(tblClasses, ClassAdmin)\r\nadmin.site.register(tblUnits, UnitAdmin)\r\n","sub_path":"Student_information_system/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"321672522","text":"\"\"\"Test dashboard.services.summaries.\"\"\"\n\nimport pytest\nfrom dateutil.relativedelta import relativedelta\n\n\n@pytest.fixture\ndef summaries():\n \"\"\"Get the module under test.\"\"\"\n from ..services import summaries\n return summaries\n\n\n@pytest.fixture\ndef datetime():\n \"\"\"Provide fixture for datetime.\"\"\"\n import datetime\n return datetime\n\n\n@pytest.fixture\ndef make_one(summaries):\n \"\"\"Provide an function to make an instance of the CUT.\"\"\"\n def _make_one(**kwargs):\n defaults = dict(\n filter_id=6292809552232448,\n incomplete=5,\n complete=10,\n total=15,\n )\n defaults.update(**kwargs)\n s = summaries.create(**defaults)\n return s\n return _make_one\n\n\ndef test_make_one(make_one):\n \"\"\"Ensure our maker makes properly.\"\"\"\n s = make_one(incomplete=3, complete=2, total=5)\n assert s.incomplete == 3\n assert s.complete == 2\n assert s.total == 5\n\n\ndef test_setup(summaries):\n \"\"\"Ensure we wired the test up.\"\"\"\n assert summaries\n\n\ndef test_make_summary(summaries):\n \"\"\"Ensure we can create a summary.\"\"\"\n data = dict(\n filter_id=6292809552232448,\n incomplete=5,\n complete=10,\n total=15,\n )\n\n s = summaries.create(**data)\n\n for key, value in data.items():\n assert getattr(s, key) == value\n\n\ndef test_make_summary_adds_the_date(summaries, datetime):\n \"\"\"A date is added to the summary when created.\"\"\"\n data = dict(\n filter_id=6292809552232448,\n incomplete=5,\n complete=10,\n total=15,\n )\n\n s = summaries.create(**data)\n assert s.created_on == datetime.date.today()\n\n\ndef test_make_summary_honors_date_arg(summaries, datetime):\n \"\"\"A date arg is honored when passed.\"\"\"\n yesterday = datetime.date.today() - relativedelta(days=1)\n data = dict(\n filter_id=6292809552232448,\n incomplete=5,\n complete=10,\n total=15,\n created_on=yesterday,\n )\n s = summaries.create(**data)\n assert s.created_on == yesterday\n\n\ndef test_summary_object_provides_pct_complete(make_one):\n \"\"\"A summary object provides a percent complete.\"\"\"\n kwargs = dict(\n incomplete=2,\n complete=4,\n total=6\n )\n s = make_one()\n assert s.pct_complete == kwargs['complete'] / float(kwargs['total'])\n\n\n@pytest.mark.system\n@pytest.mark.django_db\ndef test_store(summaries, make_one):\n \"\"\"Ensure we can store summary objects.\"\"\"\n s = make_one()\n s, result = summaries.store(s)\n assert result == summaries.SAVED\n assert s.id\n\n\n@pytest.mark.system\n@pytest.mark.django_db\ndef test_update(summaries, make_one):\n \"\"\"Ensure multiple calls to create on the same date return the same obj.\"\"\"\n s = make_one()\n s, result = summaries.store(s)\n assert result == summaries.SAVED\n assert s.id\n\n s2 = make_one(incomplete=1, complete=2, total=3)\n s2, result = summaries.store(s2)\n assert result == summaries.UPDATED\n assert s2.id == s.id\n assert (1, 2, 3) == (s2.incomplete, s2.complete, s2.total)\n\n\n@pytest.mark.system\n@pytest.mark.django_db\ndef test_update_different_filters(summaries, make_one):\n \"\"\"Ensure multiple calls to create on the same date/diff filter return the same obj.\"\"\"\n s = make_one(filter_id=1234)\n s, result = summaries.store(s)\n assert result == summaries.SAVED\n assert s.id\n\n s2 = make_one(filter_id=5678)\n s2, result = summaries.store(s2)\n assert result == summaries.SAVED\n assert s2.id != s.id\n\n\n@pytest.mark.system\n@pytest.mark.django_db\ndef test_for_date(summaries, make_one, datetime):\n \"\"\"Ensure we can find summaries from the past.\"\"\"\n week_ago = datetime.date.today() - relativedelta(days=7)\n\n s1 = make_one(created_on=week_ago)\n s2 = make_one()\n\n s1, result = summaries.store(s1)\n s2, result = summaries.store(s2)\n\n s3 = summaries.for_date(filter_id=s2.filter_id, date=week_ago)\n assert s3.id == s1.id\n\n\n@pytest.mark.system\n@pytest.mark.django_db\ndef test_for_date_sad(summaries, make_one, datetime):\n \"\"\"Validate what happens when we can't find summaries from the past.\"\"\"\n week_ago = datetime.date.today() - relativedelta(days=7)\n\n s1 = make_one()\n s2 = summaries.for_date(filter_id=s1.filter_id, date=week_ago)\n assert s2 is None\n","sub_path":"dashboard/tests/test_services_summaries.py","file_name":"test_services_summaries.py","file_ext":"py","file_size_in_byte":4302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"206530634","text":"# coding:utf-8\n# 2019/10/15\n# 线性回归\n\nimport sys\nsys.path.append('../../')\n\nfrom sklearn import linear_model\nfrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, ExtraTreesRegressor, AdaBoostRegressor, BaggingRegressor\nfrom sklearn.svm import SVR, LinearSVR\nfrom sklearn.kernel_ridge import KernelRidge\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom xgboost import XGBRegressor\n\nimport numpy as np\nimport pickle \n\nfrom util import io\n\ndef getModel(modelName):\n\t\"\"\"选择模型\"\"\"\n\tmodelDict = {\n\t\t\"Linear\" : linear_model.LinearRegression(),\n\t\t\"Ridge\": linear_model.Ridge(alpha=0.5, copy_X=True, fit_intercept=True, max_iter=None,\n\t \tnormalize=False, random_state=None, solver='auto', tol=0.001),\n\t\t\"Lasso\" : linear_model.Lasso(alpha=0.1, copy_X=True, fit_intercept=True, max_iter=1000,\n \t\t\tnormalize=False, positive=False, precompute=False, random_state=None,\n \t\t\tselection='cyclic', tol=0.0001, warm_start=False),\n\t\t\"ElasticNet\" : linear_model.ElasticNet(alpha=0.001,max_iter=10000),\n\t\t\"GradientBoosting\" : GradientBoostingRegressor(),\n\t\t\"SVR\" : SVR(),\n\t\t\"XGB\" : XGBRegressor(), \n\t\t\"AdaBoost\" : AdaBoostRegressor(n_estimators=50),\n\t\t\"Bagging\" : BaggingRegressor(),\n\t}\n\n\treturn modelDict[modelName]\n\ndef train(reg, X, Y):\n\t\"\"\"\n\t@param reg 训练模型\n\t@param X 训练数据\n\t@param Y 标签\n\t\"\"\"\n\t# reg = linear_model.Ridge(alpha=0.5, copy_X=True, fit_intercept=True, max_iter=None,\n\t# normalize=False, random_state=None, solver='auto', tol=0.001)\n\treg.fit(X, Y) \n\tprint(\"w: {}\\n, b: {}\".format(reg.coef_, reg.intercept_))\n\n\treturn reg\n\ndef main():\n\tdataFilePath = \"../../data/samples-data.data\"\n\tlabelsFilePath = \"../../data/samples-data-labels.data\"\n\tX = io.getData(dataFilePath)\n\tY = io.getData(labelsFilePath)\n\tmodelNames = [\"Linear\", \"Ridge\", \"Lasso\", \"ElasticNet\", \"GradientBoosting\"]\n\tfor modelName in modelNames:\n\t\treg = getModel(modelName)\n\n\t\tmodel = train(reg, X, Y)\n\t\tio.saveData(model, \"../../data/{}.model\".format(modelName))\n\nif __name__ == '__main__':\n\tmain()","sub_path":"tool/毕设代码/algorithms/regression/Regression.py","file_name":"Regression.py","file_ext":"py","file_size_in_byte":2077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"449476124","text":"from __future__ import absolute_import, division\nimport numpy as np\nfrom numba import jit\nimport timeit\n#from test_arrays import X_train,expand_window_input\n\ntry:\n range = xrange\nexcept NameError:\n pass\n\n@jit(nopython=True)\ndef __difference_numba(a, b):\n return abs(a-b)\n\n@jit(nopython=True)\ndef __reduce_by_half_numba(x):\n return [(x[i] + x[1+i]) / 2 for i in range(0, len(x) - len(x) % 2, 2)]\n\n@jit(nopython=True)\ndef __expand_window_numba(path, len_x, len_y, radius):\n path_ = set(path)\n for i, j in path:\n for a, b in [(i + a, j + b) for a in range(-radius, radius+1) for b in range(-radius, radius+1)]:\n path_.add((a, b))\n\n window_ = set()\n for i, j in path_:\n for a, b in ((i * 2, j * 2), (i * 2, j * 2 + 1),\n (i * 2 + 1, j * 2), (i * 2 + 1, j * 2 + 1)):\n window_.add((a, b))\n\n window = []\n start_j = 0\n for i in range(0, len_x):\n new_start_j = None\n for j in range(start_j, len_y):\n if (i, j) in window_:\n window.append((i, j))\n if new_start_j is None:\n new_start_j = j\n elif new_start_j is not None:\n break\n start_j = new_start_j\n\n return window\n\n@jit(nopython=True)\ndef __dtw_numba(x, y, window):\n len_x, len_y = len(x), len(y)\n if window is None:\n window = [(i, j) for i in range(len_x) for j in range(len_y)]\n window = [(i + 1, j + 1) for i, j in window]\n\n #my code\n D=np.full((window[-1][0]+1,window[-1][1]+1,3),np.inf)\n D[0, 0] = np.array([0, 0, 0])\n\n for i,j in window:\n dt = __difference_numba(x[i-1], y[j-1])\n priors=np.array([(D[i-1, j][0], i-1, j), (D[i, j-1][0], i, j-1),\n (D[i-1, j-1][0], i-1, j-1)])\n D[i,j] = priors[np.argmin(priors[:,0])]\n D[i,j][0]+=dt\n\n path = []\n i, j = len_x, len_y\n while not (i == j == 0):\n path.append((i-1, j-1))\n i, j = int(D[i, j][1]), int(D[i, j][2])\n path.reverse()\n return (D[len_x, len_y][0], path)\n\n@jit(nopython=True)\ndef __fastdtw_numba(x, y, radius):\n min_time_size = radius + 2\n\n if len(x) < min_time_size or len(y) < min_time_size:\n return dtw(x, y)\n\n x_shrinked = __reduce_by_half_numba(x)\n y_shrinked = __reduce_by_half_numba(y)\n distance, path = \\\n __fastdtw_numba(x_shrinked, y_shrinked, radius=radius)\n window = __expand_window_numba(path, len(x), len(y), radius)\n return __dtw_numba(x, y, window)\n\n@jit(nopython=True)\ndef dtw(x, y):\n ''' return the distance between 2 time series without approximation\n Parameters\n ----------\n x : array_like\n input array 1\n y : array_like\n input array 2\n dist : function or int\n The method for calculating the distance between x[i] and y[j]. If\n dist is an int of value p > 0, then the p-norm will be used. If\n dist is a function then dist(x[i], y[j]) will be used. If dist is\n None then abs(x[i] - y[j]) will be used.\n Returns\n -------\n distance : float\n the approximate distance between the 2 time series\n path : list\n list of indexes for the inputs x and y\n Examples\n --------\n >>> import numpy as np\n >>> import fastdtw\n >>> x = np.array([1, 2, 3, 4, 5], dtype='float')\n >>> y = np.array([2, 3, 4], dtype='float')\n >>> fastdtw.dtw(x, y)\n (2.0, [(0, 0), (1, 0), (2, 1), (3, 2), (4, 2)])\n '''\n return __dtw_numba(x, y, None)\n\n@jit(nopython=True)\ndef fastdtw(x, y, radius=1):\n ''' return the approximate distance between 2 time series with O(N)\n time and memory complexity\n Parameters\n ----------\n x : array_like\n input array 1\n y : array_like\n input array 2\n radius : int\n size of neighborhood when expanding the path. A higher value will\n increase the accuracy of the calculation but also increase time\n and memory consumption. A radius equal to the size of x and y will\n yield an exact dynamic time warping calculation.\n dist : function or int\n The method for calculating the distance between x[i] and y[j]. If\n dist is an int of value p > 0, then the p-norm will be used. If\n dist is a function then dist(x[i], y[j]) will be used. If dist is\n None then abs(x[i] - y[j]) will be used.\n ##### Currently not functional, always will use abs.\n Returns\n -------\n distance : float\n the approximate distance between the 2 time series\n path : list\n list of indexes for the inputs x and y\n Examples\n --------\n >>> import numpy as np\n >>> import fastdtw\n >>> x = np.array([1, 2, 3, 4, 5], dtype='float')\n >>> y = np.array([2, 3, 4], dtype='float')\n >>> fastdtw.fastdtw(x, y)\n (2.0, [(0, 0), (1, 0), (2, 1), (3, 2), (4, 2)])\n '''\n return __fastdtw_numba(x, y, radius)\n\na=np.array([1.0,2.0,3.0],dtype=np.float)\nb=np.array([2.0,3.0,4.0],dtype=np.float)\nd=2.0\nc=4.7\ne=2\nf=[1.0,2.0,3.0]\ng=[1.0,2.0,3.0]\n\ndef main():\n '''a=np.array([1.0,2.0,3.0],dtype=np.float)\n b=np.array([2.0,3.0,4.0],dtype=np.float)\n d=2.0\n c=4.7\n e=2'''\n fastdtw(X_train[0],X_train[-1])\n #__expand_window(expand_window_input[0],expand_window_input[1],expand_window_input[2],expand_window_input[3])\n #cProfile.run('fastdtw(f,g)')\n #__dtw(a,b,None,__difference)\n #fastdtw.inspect_types()\n\n\nif __name__==\"__main__\":\n main()\n #print (timeit.timeit(\"main()\",\"gc.enable; from __main__ import main\",number=100))\n","sub_path":"dtw_stuff/fastdtw_numba.py","file_name":"fastdtw_numba.py","file_ext":"py","file_size_in_byte":5742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"100085346","text":"import os\nos.environ[\"OMP_NUM_THREADS\"] = \"1\"\nimport random\nimport torch\ntorch.set_num_threads(1)\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.utils.data.sampler import SubsetRandomSampler\nimport argparse\nimport numpy as np\nfrom torch.utils.tensorboard import SummaryWriter\n\n\nfrom experiment import ex\nfrom model import load_model, save_model\nfrom utils import post_config_hook\n\nfrom modules import LogisticRegression\nfrom modules.deepmil import Attention\nfrom modules.transformations import TransformsSimCLR\nfrom modules.losses.focal_loss import FocalLoss\nfrom modules.Splitter import split_indices_by_patient, split_indices, get_train_val_indices\n\nfrom msidata.dataset_msi import PreProcessedMSIDataset as dataset_msi\nfrom msidata.save_feature_vectors import infer_and_save, aggregate_patient_vectors\nfrom msidata.dataset_msi_features_with_patients import PreProcessedMSIFeatureDataset\nfrom msidata.dataset_tcga_tiles import TiledTCGADataset as dataset_tcga\n\nimport matplotlib.pyplot as plt\n\nimport pandas as pd\nimport time\nimport datetime\nimport json\n\nfrom sklearn import metrics\n\n\ndef infer(args, loader, context_model, device):\n # get encoding of images\n feature_vector, labels_vector, patients, imgs = [], [], [], []\n for step, (x, y, patient, img_name, _) in enumerate(loader):\n x = x.to(device)\n with torch.no_grad():\n if args.logistic_extractor == 'simclr':\n h, z = context_model(x)\n else:\n h = context_model(x)\n h = h.detach()\n feature_vector.extend(h.cpu().detach().numpy())\n labels_vector.extend(y.numpy())\n\n if step % 20 == 0:\n print(f\"Step [{step}/{len(loader)}]\\t Computing features...\")\n\n patients+=patient\n imgs+=img_name\n\n feature_vector = np.array(feature_vector)\n labels_vector = np.array(labels_vector)\n return feature_vector, labels_vector, patients, imgs\n\n\ndef get_features(args, context_model, train_loader, val_loader, test_loader, device):\n train_X, train_y, train_patients, train_imgs = infer(args, train_loader, context_model, device)\n val_X, val_y, val_patients, val_imgs = infer(args, val_loader, context_model, device)\n test_X, test_y, test_patients, test_imgs = infer(args, test_loader, context_model, device)\n return train_X, train_y, val_X, val_y, test_X, test_y, train_patients, train_imgs, val_patients, val_imgs, test_patients, test_imgs\n\n\ndef create_data_loaders_from_arrays(X_train, y_train, X_val, y_val, X_test, y_test, batch_size, train_patients, train_imgs, val_patients, val_imgs, test_patients, test_imgs):\n train = torch.utils.data.TensorDataset(\n torch.from_numpy(X_train), torch.from_numpy(y_train), torch.Tensor(train_patients)\n )\n train_loader = torch.utils.data.DataLoader(\n train, batch_size=batch_size, shuffle=False\n )\n\n val = torch.utils.data.TensorDataset(\n torch.from_numpy(X_val), torch.from_numpy(y_val), torch.Tensor(val_patients)\n )\n val_loader = torch.utils.data.DataLoader(\n val, batch_size=batch_size, shuffle=False\n )\n\n test = torch.utils.data.TensorDataset(\n torch.from_numpy(X_test), torch.from_numpy(y_test), torch.Tensor(test_patients)\n )\n test_loader = torch.utils.data.DataLoader(\n test, batch_size=batch_size, shuffle=False\n )\n return train_loader, val_loader, test_loader\n\n\ndef train(args, train_loader, val_loader, extractor, model, criterion, optimizer, val_losses, val_roc, global_step, epoch, writer):\n loss_epoch = 0\n accuracy_epoch = 0\n for step, data in enumerate(train_loader):\n global_step += 1\n print(f\"[ Step {global_step} / {len(train_loader)} ] @ {datetime.datetime.now()}\")\n optimizer.zero_grad()\n x = data[0].to(args.device) \n y = data[1].to(args.device)\n\n if not (args.precompute_features or args.use_precomputed_features):\n if args.freeze_encoder:\n extractor.eval()\n with torch.no_grad():\n out = extractor.forward(x)\n else:\n extractor.train()\n out = extractor.forward(x)\n \n if args.logistic_extractor=='simclr': # Simclr returns (h, z)\n h = out[0]\n x = h\n else: # Torchvision models return h\n h = out\n x = h # We name it x, since it's the input for the logistic regressors, and it saves some memory\n \n model.train()\n if args.classification_head == 'logistic':\n y = y.long()\n output = model(x)\n if not args.use_focal_loss:\n loss = criterion(output, y)\n else: # use focal loss\n focal = FocalLoss(args.focal_loss_alpha, args.focal_loss_gamma)\n loss = torch.nn.functional.cross_entropy(output,y, reduction='none')\n loss = focal(loss)\n\n predicted = output.argmax(1)\n acc = (predicted == y).sum().item() / y.size(0)\n loss_epoch += loss.item()\n\n elif args.classification_head == 'linear':\n output = model(x).flatten() # output \\in R^(batch_size*1)\n loss = criterion(output.flatten(), y.flatten())\n loss_epoch += loss.item() \n acc = 0 # accuracy is not meaningful here\n \n elif args.classification_head == 'deepmil':\n y = y.long() # Might be a float if we use TCGA since we do a groupby.mean() operation\n Y_prob, Y_hat, A = model.forward(x)\n loss = criterion(Y_prob, y)\n train_loss = loss.item()\n loss_epoch += train_loss\n error, _ = model.calculate_classification_error(y, Y_hat)\n acc = 1. - error\n\n elif args.classification_head == 'linear-deepmil':\n Y_prob, Y_hat, A = model.forward(x) # Y_prob == Y_hat, in the linear case\n y = y.flatten() # shape([1, 1]) -> shape([1])\n loss = criterion(Y_prob.flatten(), y.flatten())\n train_loss = loss.item()\n loss_epoch += train_loss\n acc = 0 # meaningless here\n\n elif 'cnn' in args.classification_head:\n y = y.long()\n out = model.forward(x)\n loss = criterion(out, y)\n predicted = out.argmax(1)\n acc = (predicted == y).sum().item() / y.size(0)\n loss_epoch += loss.item()\n\n if not args.freeze_encoder and args.debug:\n previous_weights_of_last_layer = [param.clone().detach() for param in extractor.parameters()][-2]\n\n accuracy_epoch += acc\n loss.backward() # Depending on the setup: Computes gradients for classifier and possibly extractor\n optimizer.step() # Can update both the classifier and the extractor, depending on the options\n \n if not args.freeze_encoder and args.debug:\n new_weights_of_last_layer = [param.clone().detach() for param in extractor.parameters()][-2]\n assert(not torch.eq(new_weights_of_last_layer, previous_weights_of_last_layer).all()), \"The weights are not being updated!\"\n\n # Evaluate on validation set\n if global_step % args.evaluate_every == 0:\n # evaluate\n val_loss, val_accuracy, val_labels, val_preds, val_patients, _, _, _, _, _ = validate(args, val_loader, extractor, model, criterion, optimizer, final_test=False)\n val_losses.append(val_loss / len(val_loader))\n\n if args.classification_head not in ['linear', 'linear-deepmil']:\n # COMPUTE ROCAUC PER PATIENT. If we use a patient-level prediction, group and mean doesn't do anything. \n # If we use a tile-level prediciton, group and mean create a fraction prediction\n val_data, rocauc = compute_roc_auc(args, val_patients, val_labels, val_preds, save_curve=False)\n writer.add_scalar(\"loss/val\", val_loss / len(val_loader), epoch)\n writer.add_scalar(\"loss/train\", loss.cpu().item(), epoch)\n writer.add_scalar(\"rocauc/val\", rocauc, epoch)\n val_roc.append(rocauc)\n print(f\"{datetime.datetime.fromtimestamp(int(time.time())).strftime('%Y-%m-%d %H:%M:%S')} | Epoch [{epoch+1}/{args.logistic_epochs}]\\tStep [{step}/{len(train_loader)}]\\t Train loss: {loss.cpu().item()}\\tVal Loss: {val_loss / len(val_loader)}\\tAccuracy: {val_accuracy / len(val_loader)}\\tROC AUC: {rocauc}\")\n else:\n # COMPUTE R2 PER PATIENT.\n val_data, r2 = compute_r2(val_patients, val_labels, val_preds)\n writer.add_scalar(\"loss/val\", val_loss / len(val_loader), epoch)\n writer.add_scalar(\"r2/val\", r2, epoch)\n val_roc.append(r2)\n print(f\"{datetime.datetime.fromtimestamp(int(time.time())).strftime('%Y-%m-%d %H:%M:%S')} | Epoch [{epoch+1}/{args.logistic_epochs}]\\tStep [{step}/{len(train_loader)}]\\tVal Loss: {val_loss / len(val_loader)}\\tAccuracy: {val_accuracy / len(val_loader)}\\tR2: {r2}\")\n \n # Save model with each evaluation\n args.global_step = global_step\n if extractor:\n # We don't always have an extractor, e.g. when we use precomputed features\n save_model(args, extractor, None, prepend='extractor_')\n # Save classification model, which is the primary model being trained here\n save_model(args, model, None, prepend='classifier_')\n \n\n return loss_epoch, accuracy_epoch, val_losses, val_roc, global_step\n\n\ndef validate(args, loader, extractor, model, criterion, optimizer, final_test=False):\n loss_epoch, accuracy_epoch = 0, 0\n labels, preds, patients, img_names, attentions, attention_gradients, subsample_indices, predicted_probs = [], [], [], [], [], [], [], []\n\n model.eval()\n\n for step, data in enumerate(loader):\n model.zero_grad()\n\n x = data[0]\n y = data[1]\n patient = data[2]\n img_names += data[3] # a list of strings, each of one patient -> e.g. ['grid_123.pt', 'grid_234.pt', 'grid_345.pt', 'grid_456.pt']\n subsample_indices += data[4] # a list of indices per patient -> e.g. [ [1, 2, 6, 7] , [4, 6, 8, 10] , [1, 14, 17, 200] ]\n\n x = x.to(args.device)\n y = y.to(args.device)\n\n if not (args.precompute_features or args.use_precomputed_features):\n # x is an image not yet a feature vector\n extractor.eval()\n\n with torch.no_grad():\n out = extractor.forward(x)\n\n if args.logistic_extractor=='simclr': # Simclr returns (h, z)\n h = out[0]\n x = h\n else: # Torchvision models return h\n h = out\n x = h # We name it x, since it's the input for the logistic regressors\n \n else:\n # x is already a feature vector, and can go straight into the classifier\n pass\n\n if args.classification_head == 'logistic':\n y = y.long()\n with torch.no_grad():\n output = model(x)\n if not args.use_focal_loss:\n loss = criterion(output, y)\n else:\n # use focal loss\n focal = FocalLoss(args.focal_loss_alpha, args.focal_loss_gamma)\n loss = torch.nn.functional.cross_entropy(output,y, reduction='none')\n loss = focal(loss)\n\n predicted = output.argmax(1)\n predicted_prob = torch.nn.functional.softmax(output, dim=1)\n acc = (predicted == y).sum().item() / y.size(0)\n loss_epoch += loss.item()\n preds += predicted.cpu().tolist()\n predicted_probs += predicted_prob.cpu().tolist()\n\n elif args.classification_head == 'linear':\n with torch.no_grad():\n output = model(x).flatten()\n loss = criterion(output.flatten(), y.flatten())\n predicted = output\n acc = 0 # meaningless for linear regression\n loss_epoch += loss.item()\n preds += predicted.cpu().tolist()\n\n elif args.classification_head == 'deepmil':\n if final_test:\n x.requires_grad = True\n with torch.set_grad_enabled(final_test): ## We do want gradients for the final test, in order to do some nice visualization with the gradients & attention\n\n y = y.long() # Might be a float when using TCGA data due to groupby.mean() operator\n Y_prob, Y_hat, A = model.forward(x)\n loss = criterion(Y_prob, y)\n train_loss = loss.item()\n loss_epoch += train_loss\n error, _ = model.calculate_classification_error(y, Y_hat)\n acc = 1. - error \n binary_Y_prob = Y_prob.softmax(dim=1)[:,1] # Get the probability of it being class 1\n preds += binary_Y_prob.cpu().tolist() \n if final_test:\n # print(f\"Shape of x: {x.shape}\")\n # print(f\"Shape of A: {A.shape}\")\n # print(f\"Shape of binary_Y_prob: {binary_Y_prob}\")\n\n ## Get the DeepMIL attention gradients\n for i, patient_probability in enumerate(binary_Y_prob): # Pytorch can't do elemnt-wise backwards\n\n # print(f\"Shape of patient probability: {patient_probability}\")\n \n patient_probability.backward(retain_graph=True) # So we do a backward pass per patient\n dPositiveClassdA = model.A_grad[i].flatten() # Which means we now get a gradient from attention to class probability for each tile for the patient\n # since attention is batch x tiles x 1, we want the index of the patient we look at now, and flatten it.\n \n # print(f\"Shape of a single dPositiveClassdA: {dPositiveClassdA.shape}\")\n # print(f\"{i}: {dPositiveClassdA}\")\n attention_gradients.append(dPositiveClassdA.cpu().tolist()) # We save these as a list per patient\n model.zero_grad() # We remove the created gradients, so that they are not accumulated\n\n attentions += A.flatten(start_dim=1, end_dim=-1).cpu().tolist() # save attention as a list of attentions per patient\n\n elif args.classification_head == 'linear-deepmil':\n with torch.no_grad():\n Y_prob, Y_hat, A = model.forward(x)\n y = y.flatten() # torch.size([1,1]) -> torch.size([1])\n loss = criterion(Y_prob.flatten(), y.flatten())\n train_loss = loss.item()\n loss_epoch += train_loss\n acc = 0\n preds += Y_prob.cpu().tolist()\n\n elif 'cnn' in args.classification_head:\n with torch.no_grad():\n y = y.long()\n out = model.forward(x)\n loss = criterion(out, y)\n predicted = out.argmax(1)\n acc = (predicted == y).sum().item() / y.size(0)\n loss_epoch += loss.item()\n preds += predicted.cpu().tolist()\n\n accuracy_epoch += acc\n labels += y.cpu().tolist()\n \n if isinstance(patient, torch.Tensor):\n # Happens when using dataset_msi, as we return a hash, which is an integer, which is made into a tensor\n patients += patient.cpu().tolist()\n else:\n # Happens when using dataset_Msi_features_with_patients, as we return the patient id as a string, which can't be tensorfied\n patients += list(patient)\n\n return loss_epoch, accuracy_epoch, labels, preds, patients, attentions, attention_gradients, img_names, subsample_indices, predicted_probs\n\n\ndef get_precomputed_dataloader(args, run_id):\n print(f\"### Loading precomputed feature vectors from run id: {run_id} ####\")\n\n if args.dataset in ['msi-tcga', 'basis']:\n assert ('load_wsi_level_tensors' in vars(args).keys()), \"For TCGA we switched to WSI-level tensors. Please add 'load_wsi_level_tensors' (bool) to your config file\"\n\n #assert(args.load_patient_level_tensors and args.logistic_batch_size==1) or not args.load_patient_level_tensors, \"We can only use batch size=1 for patient-level tensors, due to different size of tensors\"\n\n if args.load_patient_level_tensors:\n sampling_strategy='patient'\n else:\n sampling_strategy='tile'\n\n if 'deepmil' in args.classification_head:\n stack_grid = True\n else:\n stack_grid = False\n\n if args.dataset=='msi-kather':\n\n train_dataset = PreProcessedMSIFeatureDataset(\n root_dir=args.path_to_msi_data, \n transform=None, \n data_fraction=1,\n sampling_strategy=sampling_strategy,\n append_img_path_with=f'_{run_id}',\n tensor_per_patient=args.load_patient_level_tensors,\n seed=args.seed,\n pad_tiles=args.logistic_batch_size > 1\n \n )\n test_dataset = PreProcessedMSIFeatureDataset(\n root_dir=args.path_to_test_msi_data, \n transform=None, \n data_fraction=1,\n sampling_strategy=sampling_strategy,\n append_img_path_with=f'_{run_id}',\n tensor_per_patient=args.load_patient_level_tensors,\n seed=args.seed,\n pad_tiles=args.logistic_batch_size > 1\n )\n\n elif args.dataset in ['msi-tcga', 'basis']:\n train_dataset, test_dataset, val_dataset = [dataset_tcga(\n args=args,\n csv_file=args.path_to_msi_data, \n root_dir=args.root_dir_for_tcga_tiles, \n transform=None,\n precomputed=True,\n precomputed_from_run=run_id,\n tensor_per_wsi=args.load_wsi_level_tensors,\n split_num=args.kfold,\n label=args.ddr_label,\n split=current_split,\n load_tensor_grid=args.load_tensor_grid,\n stack_grid=stack_grid,\n load_normalized_tiles=args.load_normalized_tiles,\n dataset=args.dataset\n ) for current_split in ['train', 'test', 'val']]\n\n if args.dataset=='msi-kather':\n train_indices, val_indices = get_train_val_indices(train_dataset, val_split=args.validation_split)\n train_sampler = SubsetRandomSampler(train_indices)\n val_sampler = SubsetRandomSampler(val_indices)\n val_dataset=train_dataset\n elif args.dataset in ['msi-tcga','basis']:\n train_sampler=None\n val_sampler=None\n\n train_loader = torch.utils.data.DataLoader(\n train_dataset,\n batch_size=args.logistic_batch_size,\n drop_last=False,\n num_workers=args.workers,\n sampler=train_sampler\n )\n\n val_loader = torch.utils.data.DataLoader(\n val_dataset,\n batch_size=args.logistic_batch_size,\n drop_last=False,\n num_workers=args.workers,\n sampler=val_sampler\n )\n\n test_loader = torch.utils.data.DataLoader(\n test_dataset,\n batch_size=args.logistic_batch_size,\n shuffle=False,\n drop_last=False,\n num_workers=args.workers,\n )\n\n assert (len(train_loader) != len(test_loader))\n assert (len(train_loader) != len(val_loader))\n assert (len(val_loader) != len(test_loader))\n\n return train_loader, val_loader, test_loader\n\ndef set_seed(seed):\n np.random.seed(seed)\n random.seed(seed)\n torch.manual_seed(seed)\n\ndef write_hparams(writer, config, metric):\n config_vars = vars(config)\n for key in config_vars.keys():\n if isinstance(config_vars[key], bool):\n if config_vars[key]:\n config_vars[key] = 1\n else:\n config_vars[key] = 0\n \n del config_vars['device']\n\n writer.add_hparams(config_vars, metric)\n\ndef compute_roc_auc(args, patients, labels, preds, save_curve=False, epoch=0):\n data = pd.DataFrame(data={'patient': patients, 'labels': labels, 'preds': preds})\n dfgroup = data.groupby(['patient']).mean()\n labels = dfgroup['labels'].values\n preds = dfgroup['preds'].values\n print(f\"Y_true: {labels}\")\n print(f\"Y_score: {preds}\")\n rocauc = metrics.roc_auc_score(y_true=labels, y_score=preds)\n\n if save_curve:\n fpr, tpr, threshold = metrics.roc_curve(labels, preds)\n\n plt.title('Receiver Operating Characteristic')\n plt.plot(fpr, tpr, 'b', label = 'AUC = %0.2f' % rocauc)\n plt.legend(loc = 'lower right')\n plt.plot([0, 1], [0, 1],'r--')\n plt.xlim([0, 1])\n plt.ylim([0, 1])\n plt.ylabel('True Positive Rate')\n plt.xlabel('False Positive Rate')\n\n plt.savefig(f'{args.out_dir}/roc_curve_epoch_{epoch}.png')\n\n return data, rocauc\n\ndef compute_r2(patients, labels, preds):\n data = pd.DataFrame(data={'patient': patients, 'labels': labels, 'preds': preds})\n dfgroup = data.groupby(['patient']).mean() # Let's just try taking the mean of all the tile predictions.. for now.. if it's linear-deepmil this will keep them as is\n labels = dfgroup['labels'].values # all continues values\n preds = dfgroup['preds'].values # all continues values\n r2=metrics.r2_score(y_true=labels, y_pred=preds)\n return data, r2\n\ndef save_attention(args, img_names, attentions, attention_gradients, subsample_indices, out_dir, humane_readable_time, epoch):\n\n all_x_coords, all_y_coords, all_tile_names, all_patient_ids = [], [], [], []\n\n for img_name, subsample_indices_per_patient, attention_per_patient, attention_gradient_per_patient in zip(img_names, subsample_indices, attentions, attention_gradients):\n\n # read grid with tiles\n meta_img_name = img_name.replace('grid_extractor', 'grid_paths_and_coords_extractor')\n meta_img = torch.load(meta_img_name, map_location='cpu')\n if args.dataset == 'msi-tcga':\n patient_id = img_name.split('/')[5].split('case-')[1] # all img names are from the same patient ID\n elif args.dataset == 'basis':\n patient_id = img_name.split('/')[4].split('case-')[1] # this is incorrect. img_name e.g. = /project/schirris/tiled_data_large/case-PD9578a/pid_YID161_tile_grid_extractor_585.pt\n tile_names = list(meta_img[0])\n coords = meta_img[1]\n tile_names = [tile_names[int(i)] if not torch.isnan(i) else np.nan for i in subsample_indices_per_patient]\n x_coords_unsampled = coords[:,0]\n y_coords_unsampled = coords[:,1]\n x_coords = [x_coords_unsampled[int(i)] if not torch.isnan(i) else np.nan for i in subsample_indices_per_patient]\n y_coords = [y_coords_unsampled[int(i)] if not torch.isnan(i) else np.nan for i in subsample_indices_per_patient]\n\n\n # We pad the left withe [None]s, because the subsample indices might be smaller than the actual array, and therefore smaller than the attention array\n # In order to make DeepMIL work with a bigger batch_size than 1, we pad each \"bag\" with zero-vectors. For consistency's sake, we continued doing this when\n # subsampling. However, in this case, this would lead to a larger attention vector than there are actual images. This would not be savable.\n # However, since we want to see how much attention there is on zero-vectors (as a sanity check) we want to save this, but with empty tile names and empty\n # coordinates\n tile_names = [np.nan] * (len(attention_per_patient) - len(tile_names)) + tile_names\n x_coords = [np.nan] * (len(attention_per_patient) - len(x_coords)) + x_coords\n y_coords = [np.nan] * (len(attention_per_patient) - len(y_coords)) + y_coords\n patient_ids = [patient_id] * len(tile_names)\n \n\n all_x_coords += x_coords # These are all a single list of objects now\n all_y_coords += y_coords\n all_tile_names += tile_names\n all_patient_ids += patient_ids\n\n\n attention_df = pd.DataFrame({\"tile_name\": all_tile_names, \"patient_id\": all_patient_ids, \"attention\": np.array(attentions).flatten(), \"attention_gradients\": np.array(attention_gradients).flatten(), 'x': all_x_coords, 'y': all_y_coords})\n\n attention_df.to_csv(f'{out_dir}/attention_output_epoch_{epoch}_{humane_readable_time}.csv')\n\n\ndef save_probabilities(args, img_names, predicted_probs, labels, out_dir, humane_readable_time, epoch):\n data = pd.DataFrame(data={'img': img_names, 'labels': labels, 'probs': predicted_probs})\n data.to_csv(f'{out_dir}/probabilities_output_epoch_{epoch}_{humane_readable_time}.csv')\n\n\n@ex.automain\ndef main(_run, _log):\n args = argparse.Namespace(**_run.config)\n args = post_config_hook(args, _run)\n args.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n if 'debug' not in vars(args).keys():\n args.debug = False\n\n if 'load_normalized_tiles' not in vars(args).keys():\n args.load_normalized_tiles = False\n\n if 'test_deepmil_subsample' in vars(args).keys():\n print(f\"*=*=*=*=* We will perform a subsampling experiment with {args.test_deepmil_subsample} subsampled tiles *=*=*=*=*\")\n\n if 'deepmil_intermediate_hidden' not in vars(args).keys():\n args.deepmil_intermediate_hidden = 128\n \n if 'reload_classifier' not in vars(args).keys():\n args.reload_classifier = False\n\n\n set_seed(args.seed)\n\n if 'train_extractor_on_generated_labels' in vars(args).keys():\n if args.train_extractor_on_generated_labels:\n assert('generated_labels_id' in vars(args).keys()), \"Please set the ID of the run that generated the labels\"\n assert('generated_label' in vars(args).keys()), \"Please set the label you want to use\"\n assert(args.generated_label != 'label'), \"Please set a non-standard label, otherwise we're not doing anything interesting\"\n assert(not args.freeze_encoder), \"If we want to finetune, we should not freeze the encoder\"\n assert(not args.precompute_features), \"If we want to finetune, we should not precompute any features. We should run the images through the encoder\"\n assert(args.classification_head == 'logistic'), \"We want to do tilewise predictions with our new tile-level labels!\"\n with open(f'./logs/{args.generated_labels_id}/config.json') as f:\n config_of_label_creation = json.load(f)\n assert(args.seed == config_of_label_creation['seed']), f\"Current seed: {args.seed}. Seed during label creation of run {args.generated_labels_id}: {config_of_label_creation['seed']}. Ensure they are equal to get the same train-test split\"\n\n tb_dir = os.path.join(args.out_dir, _run.experiment_info[\"name\"])\n os.makedirs(tb_dir)\n writer = SummaryWriter(log_dir=tb_dir)\n\n if 'train_extractor_on_generated_labels' in vars(args).keys():\n if args.train_extractor_on_generated_labels:\n label = args.generated_label\n load_labels_from_run = args.generated_labels_id\n else:\n label = 'label'\n load_labels_from_run=''\n else:\n label = 'label'\n load_labels_from_run=''\n\n if args.dataset == \"msi-kather\":\n train_dataset = dataset_msi(\n root_dir=args.path_to_msi_data, \n transform=TransformsSimCLR(size=224).test_transform, \n data_fraction=args.data_testing_train_fraction,\n seed=args.seed,\n label=label,\n load_labels_from_run=load_labels_from_run\n )\n test_dataset = dataset_msi(\n root_dir=args.path_to_test_msi_data, \n transform=TransformsSimCLR(size=224).test_transform, \n data_fraction=args.data_testing_test_fraction,\n seed=args.seed,\n label=label,\n load_labels_from_run=load_labels_from_run\n )\n elif args.dataset in [\"msi-tcga\", \"basis\"]:\n args.data_pretrain_fraction=1 \n assert ('.csv' in args.path_to_msi_data), \"Please provide the tcga .csv file in path_to_msi_data\"\n assert ('root_dir_for_tcga_tiles' in vars(args).keys()), \"Please provide the root dir for the tcga tiles\"\n\n\n # TODO Add the HE normalization from config arguments to the code below\n # Then commit\n # Then push\n # Then test\n if ('he_norm' in vars(args).keys()) and ('he_norm_method' in vars(args).keys()):\n if args.he_norm:\n he_normalization=args.he_norm_method\n if he_normalization == 'macenko':\n assert(os.path.isfile(args.he_norm_target)), f\"he_norm_target: {args.he_norm_target} is not an existing file\"\n he_norm_target = args.he_norm_target\n else:\n he_normalization = ''\n he_norm_target = ''\n else:\n he_normalization = ''\n he_norm_target = ''\n\n tcga_transform = TransformsSimCLR(size=224, henorm=he_normalization, path_to_target_im=he_norm_target).test_transform\n\n train_dataset, test_dataset, val_dataset = [dataset_tcga(\n args=args,\n csv_file=args.path_to_msi_data, \n root_dir=args.root_dir_for_tcga_tiles, \n transform=tcga_transform,\n split_num=args.kfold,\n label=args.ddr_label,\n split=current_split,\n load_normalized_tiles=args.load_normalized_tiles,\n dataset=args.dataset\n ) for current_split in ['train', 'test', 'val']]\n else:\n raise NotImplementedError\n\n # Get the extractor\n if args.logistic_extractor == 'byol':\n # We get the rn18 backbone with the loaded state dict\n print(\"Loading BYOL model ... \")\n _, _, _, extractor, n_features = load_model(args, reload_model=args.reload_model, model_type=args.logistic_extractor)\n else:\n extractor, _, _ = load_model(args, reload_model=args.reload_model, model_type=args.logistic_extractor)\n\n extractor = extractor.to(args.device)\n\n # Set extractor to eval if asked for\n if args.freeze_encoder:\n print(\"===== Extractor is frozen =====\")\n extractor.eval()\n else:\n print(\"===== Extractor is NOT frozen =====\")\n extractor.train()\n\n # Get number of features that feature extractor produces\n if args.logistic_extractor == 'simclr':\n n_features = extractor.n_features\n elif args.logistic_extractor == 'byol':\n # We returned n_features in load_model()..\n pass\n else:\n n_features = {'imagenet-resnet18': 512, 'imagenet-resnet50': 2048, 'imagenet-shufflenetv2_x1_0': 1024}[args.logistic_extractor]\n\n if 'linear' in args.classification_head:\n n_classes = 1 # Doing linear regression\n else:\n n_classes = 2 # Doing logistic regression\n\n\n ## Get classifier. Logistic / linear / deepmil / linear-deepmil\n if 'reload_classifier' not in vars(args).keys():\n args.reload_classifier = False\n model, _, _ = load_model(args, reload_model=args.reload_classifier, model_type=args.classification_head, prepend='', n_features=n_features, n_classes=n_classes)\n\n ## Get optimizer\n if args.classification_head == 'logistic' or args.classification_head == 'linear':\n if args.freeze_encoder:\n optimizer = torch.optim.Adam(model.parameters(), lr=args.logistic_lr)\n else:\n optimizer = torch.optim.Adam(list(extractor.parameters()) + list(model.parameters()), lr=args.logistic_lr)\n elif args.classification_head in ['deepmil', 'linear-deepmil', 'cnn-resnet18', 'cnn-densenet']:\n if args.freeze_encoder:\n optimizer = torch.optim.Adam(model.parameters(), lr=args.deepmil_lr, betas=(0.9, 0.999), weight_decay=args.deepmil_reg)\n else:\n optimizer = torch.optim.Adam(list(extractor.parameters()) + list(model.parameters()), lr=args.deepmil_lr, betas=(0.9, 0.999), weight_decay=args.deepmil_reg)\n else:\n print(f\"{args.classification_head} has not been implemented as classification head\")\n raise NotImplementedError\n\n model = model.to(args.device)\n print(model)\n \n\n ### ============= GET THE CORRECT DATA LOADERS ============= ###\n\n if args.precompute_features or not args.use_precomputed_features:\n # If we precompute features, we need an image loader\n # If we use precomputed features, we don't need an image loader\n # If we don't use any preocomputed features, which happens if we finetune, we do want an image loader \n\n assert not (args.precompute_features and args.use_precomputed_features), \"Ambiguous config. Precompute features or use precomputed features?\"\n\n drop_last = not (args.precompute_features and not args.precompute_features_in_memory) # if we precompute features, but NOT in memory, do not drop last\n\n if args.dataset in ['msi-tcga','basis']:\n # For msi-tcga, we have pre-split everything\n train_sampler=None\n val_sampler=None\n \n else:\n train_indices, val_indices = get_train_val_indices(train_dataset, val_split=args.validation_split)\n train_sampler = SubsetRandomSampler(train_indices)\n val_sampler = SubsetRandomSampler(val_indices) \n val_dataset = train_dataset\n # for non-msi-tcga, we have to split, still\n\n train_loader = torch.utils.data.DataLoader(\n train_dataset,\n batch_size=args.logistic_batch_size,\n drop_last=drop_last,\n num_workers=args.workers,\n sampler=train_sampler\n )\n\n val_loader = torch.utils.data.DataLoader(\n val_dataset,\n batch_size=args.logistic_batch_size,\n drop_last=drop_last,\n num_workers=args.workers,\n sampler=val_sampler\n )\n\n test_loader = torch.utils.data.DataLoader(\n test_dataset,\n batch_size=args.logistic_batch_size,\n drop_last=drop_last,\n num_workers=args.workers\n )\n \n\n ### ============ Precompute and/or load precomputed features ============= ###\n\n if args.precompute_features:\n # We need the image loader defined above \n \n if args.precompute_features_in_memory:\n print(\"### Creating features from pre-trained context model ###\")\n \n (train_X, train_y, val_X, val_y, test_X, test_y, train_patients, train_imgs, val_patients, val_imgs, test_patients, test_imgs) = get_features(\n args, extractor, train_loader, val_loader, test_loader, args.device\n )\n\n arr_train_loader, arr_val_loader, arr_test_loader = create_data_loaders_from_arrays(\n train_X, train_y, val_X, val_y, test_X, test_y, args.logistic_batch_size, train_patients, train_imgs, val_patients, val_imgs, test_patients, test_imgs\n )\n else:\n print(\"### Creating and saving features from pre-trained context model ###\")\n print(args.data_testing_train_fraction)\n assert args.data_testing_train_fraction == 1 and args.data_testing_test_fraction == 1, \"Bugs might occur when we do not save feature vectors for all data due to sampling issues\"\n\n run_id = args.out_dir.split('/')[-1] # \"./logs/pretrain/\"\n\n infer_and_save(loader=train_loader, context_model=extractor, device=args.device, append_with=f'_{run_id}', model_type=args.logistic_extractor)\n infer_and_save(loader=val_loader, context_model=extractor, device=args.device, append_with=f'_{run_id}', model_type=args.logistic_extractor)\n infer_and_save(loader=test_loader, context_model=extractor, device=args.device, append_with=f'_{run_id}', model_type=args.logistic_extractor)\n\n print(\"### Aggregating saved feature vectors into patient-level tensors ###\")\n print(\"### Aggregating for train...\")\n aggregate_patient_vectors(args, root_dir=args.path_to_msi_data, append_with=f'_{run_id}', grid=True, data=train_dataset.labels)\n print(\"### Aggregating for val...\")\n aggregate_patient_vectors(args, root_dir=args.path_to_msi_data, append_with=f'_{run_id}', grid=True, data=val_dataset.labels)\n print(\"### Aggregating for test...\")\n aggregate_patient_vectors(args, root_dir=args.path_to_msi_data, append_with=f'_{run_id}', grid=True, data=test_dataset.labels)\n \n # Overwriting previous variable names to reduce memory load\n train_loader, val_loader, test_loader = get_precomputed_dataloader(args, run_id)\n\n arr_train_loader, arr_val_loader, arr_test_loader = train_loader, val_loader, test_loader\n\n elif args.use_precomputed_features:\n # Did not need any image loader, as we create a new vector-based dataset\n \n assert (args.use_precomputed_features_id), 'Please set the run ID of the features you want to use'\n print(f\"Removing SIMCLR model from memory, as we use precomputed features..\")\n del extractor\n extractor = None\n arr_train_loader, arr_val_loader, arr_test_loader = get_precomputed_dataloader(args, args.use_precomputed_features_id)\n else:\n # We use the image loader as defined above\n arr_train_loader, arr_val_loader, arr_test_loader = train_loader, val_loader, test_loader\n\n\n ### ============= TRAINING ============= ###\n\n if 'linear' in args.classification_head:\n criterion = torch.nn.MSELoss()\n else:\n criterion = torch.nn.CrossEntropyLoss(weight=arr_train_loader.dataset.get_class_balance().float().to(args.device)) #TODO add class balance\n\n val_losses = []\n val_roc = []\n global_step = 0\n for epoch in range(args.logistic_epochs):\n args.current_epoch = epoch\n loss_epoch, accuracy_epoch, val_losses, val_roc, global_step = train(args, arr_train_loader, arr_val_loader, extractor, model, criterion, optimizer, val_losses, val_roc, global_step, epoch, writer)\n writer.add_scalar(\"loss/train\", loss_epoch / len(arr_train_loader), epoch)\n\n\n ### ============= TESTING ============= ###\n\n if args.logistic_epochs > 0:\n # If we have run epochs in the current run, we will take the best model from the current run\n if not 'best_model_evaluation' in vars(args).keys():\n args.best_model_evaluation = 'auc'\n\n if args.best_model_evaluation == 'auc' or args.best_model_evaluation == 'r2': # r2 for linear regression, which is saved in the roc array\n # This seems like it would make most sense for the logistic regression (tile-level prediction & majority vote)\n best_model_num = np.argmax(val_roc)\n elif args.best_model_evaluation == 'loss':\n # This is probably most sensible for patient-level prediction methods like deepmil\n best_model_num = np.argmin(val_losses)\n \n best_model_epoch = best_model_num * args.evaluate_every + args.evaluate_every\n\n print(f'Validation ROCs: {val_roc}\\nValidation loss: {val_losses}.\\nBest performance by model @ epoch # {best_model_epoch}')\n\n if extractor:\n extractor_fp = os.path.join(args.out_dir, \"extractor_checkpoint_{}.tar\".format(best_model_epoch))\n extractor.load_state_dict(torch.load(extractor_fp, map_location=args.device.type))\n model_fp = os.path.join(args.out_dir, \"classifier_checkpoint_{}.tar\".format(best_model_epoch))\n model.load_state_dict(torch.load(model_fp, map_location=args.device.type))\n\n else:\n # clarifying that we have not trained at all\n best_model_epoch=epoch=0\n\n # If we haven't run any epochs, we won't do anything, because we've already loaded the model before...\n\n # if args.reload_model:\n # if extractor:\n # extractor_fp = os.path.join(args.model_path, \"extractor_checkpoint_{}.tar\".format(args.epoch_num))\n # extractor.load_state_dict(torch.load(extractor_fp, map_location=args.device.type))\n # model_fp = os.path.join(args.model_path, \"classifier_checkpoint_{}.tar\".format(args.epoch_num))\n # model.load_state_dict(torch.load(model_fp, map_location=args.device.type))\n \n loss_epoch, accuracy_epoch, labels, preds, patients, attentions, attention_gradients, img_names, subsample_indices, predicted_probs = validate(\n args, arr_test_loader, extractor, model, criterion, optimizer, final_test=True\n )\n\n\n ### ============= Compute final metrics and write them to tensorboard ============= ###\n\n writer.add_scalar(\"loss/test\", loss_epoch / len(arr_test_loader))\n if 'linear' not in args.classification_head:\n # Logistic regression, using ROC AUC as metric\n final_data, rocauc = compute_roc_auc(args, patients, labels, preds, save_curve=True, epoch=best_model_epoch)\n writer.add_scalar(\"rocauc/test\", rocauc)\n write_hparams(writer, args, {'hparam/rocauc': rocauc })\n _run.log_scalar('test/rocauc', rocauc, 0)\n print(\n f\"======\\n[Final test with best model]\\t ROCAUC: {rocauc} \\t Loss: {loss_epoch / len(arr_test_loader)}\\t Accuracy: {accuracy_epoch / len(arr_test_loader)}\"\n )\n else:\n # Linear regression, using R2 score as metric\n final_data, r2 = compute_r2(patients, labels, preds)\n writer.add_scalar(\"r2/test\", r2)\n write_hparams(writer, args, {'hparam/r2': r2 })\n _run.log_scalar('test/r2', r2, 0)\n print(\n f\"======\\n[Final test with best model]\\t R2: {r2} \\t Loss: {loss_epoch / len(arr_test_loader)}\\t\"\n )\n\n\n ### ============= Save the predictions ============= ###\n\n humane_readable_time = datetime.datetime.fromtimestamp(int(time.time())).strftime('%Y-%m-%d-%H-%M-%S')\n print(f'This is the out dir {args.out_dir}')\n\n final_data.to_csv(f'{args.out_dir}/regression_output_epoch_{best_model_epoch}_{humane_readable_time}.csv') \n\n if args.classification_head == 'deepmil':\n # This means we'll have loaded a stacked grid, we'll have returned subsample indices, we'll have meaningful attentions.\n # Now save it for easy visualization..\n save_attention(args, img_names, attentions, attention_gradients, subsample_indices, args.out_dir, humane_readable_time, best_model_epoch)\n elif args.classification_head == 'logistic':\n save_probabilities(args, img_names, predicted_probs, labels, args.out_dir, humane_readable_time, best_model_epoch)\n\n \n \n\n","sub_path":"testing/logistic_regression.py","file_name":"logistic_regression.py","file_ext":"py","file_size_in_byte":42594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"405776077","text":"# __author__ = 'Fabian'\n# __project__ = erste_Programme\n# __file__ = rock_paper_scissor_gui.py\n# __version__ = 0.9\n\n\nimport tkinter as tk\nfrom tkinter import messagebox\nfrom PIL import Image, ImageTk\nimport random\n\n# ToDo Bestenliste mit gesuchter Zahl, Versuchen, mit/ohne Hinweis\n# ToDo Fehler: Bestätigen, Neustart, Modus auswählen -> Zähler bleibt eingeblendet\n# ToDo Fehler: Modus unbegrenzt, Unentschieden\n# ToDo Hintergrund, wenn Stop-Button (Modus: unbegrenzt) wieder ausgeblendet\n# ToDo Formatierung\n\n# Debug\nclass debug():\n global counter_debug\n # Debug anzeigen\n def debug_show(event):\n if counter_debug.get() == 0:\n counter_debug.set(\"1\")\n txdebug = tk.Text(main, width=47, height=9, relief = \"sunken\", bd = 2)\n txdebug.grid(column=0, row=7)\n txdebug.insert(\"end\", \"\")\n\n main.minsize(width=400, height=450) # min. Fenstergröße\n main.maxsize(width=400, height=450) # max. Fenstergröße\n else:\n debug.debug_update()\n # Debug aktualisieren\n def debug_update():\n debug.debug_invisible()\n txdebug = tk.Text(main, width=47, height=9, relief=\"sunken\", bd=2)\n txdebug.grid(column=0, row=7)\n txdebug.insert(\"end\", \"\")\n main.minsize(width=400, height=450) # min. Fenstergröße\n main.maxsize(width=400, height=450) # max. Fenstergröße\n # Debug ausblenden\n def debug_invisible():\n children = main.winfo_children()\n for child in children:\n if str(type(child)) == \"\":\n child.destroy()\n main.minsize(width=400, height=320) # min. Fenstergröße\n main.maxsize(width=400, height=320) # max. Fenstergröße\n return\n # Debug ausblenden Menü\n def debug_invisible_menu():\n counter_debug.set(\"0\")\n children = main.winfo_children()\n for child in children:\n if str(type(child)) == \"\":\n child.destroy()\n main.minsize(width=400, height=320) # min. Fenstergröße\n main.maxsize(width=400, height=320) # max. Fenstergröße\n return\n\n# Bilder\nclass images():\n # Image Player\n def image_player():\n load = Image.open(symbol[0])\n render = ImageTk.PhotoImage(load)\n img = tk.Label(frplayer, bg = bg, image=render)\n img.image = render\n img.grid(column=0, row=2, columnspan=2, rowspan=3)\n # Image Computer\n def image_computer():\n load = Image.open(symbol[1])\n render = ImageTk.PhotoImage(load)\n img = tk.Label(frcomputer, bg = bg, image=render)\n img.image = render\n img.grid(column=0, row=2, columnspan=2, rowspan=3)\n\n# # Auswahl Modus\n# class mode():\n#\n# # Interface Änderungen\n# class interface():\n#\n# # Eingabe\n# class guess():\n#\n# Werte zurücksetzten\ndef reset():\n pass\n\n# Programm Ende\ndef end():\n main.destroy()\n\n# Optionen\nbg = \"beige\" # Allgemeine Hintergrundfarbe\n\n# Hauptfenster\nmain = tk.Tk()\nmain.title(\"Spielesammlung\") # Fenstername\nmain.configure(bg = bg) # Hintergrundfarbe\nmain.minsize(width=400, height=320) # min. Fenstergröße\nmain.maxsize(width=400, height=320) # max. Fenstergröße\nmain.columnconfigure(0, weight = 3) # Zentrieren\n\n# Startwerte Variablen\ncounter_debug = tk.IntVar()\ncounter_debug.set(\"0\") # Zähler Debug\nsymbol = [\"X.png\", \"O.png\"] # Bilder\n\n\n# Hauptfenster Header\nlbheader = tk.Label(main, width = 43, bg = \"brown\", fg = \"white\", text = \"************** Tic Tac Toe **************\",\n font = \"Times 16 bold\", relief = \"raised\", bd = 4)\nlbheader.bind(\"\", debug.debug_show)\nlbheader.grid(column = 0, row = 0, columnspan = 3)\n\n# Menü\nmBar = tk.Menu(main)\n\nmFile = tk.Menu(mBar)\nmDebug = tk.Menu(mBar)\n\nmBar.add_cascade(label = \"Datei\", menu = mFile, underline = 0)\nmBar.add_cascade(label = \"Debugger\", menu = mDebug, underline = 0)\n\nmFile.add_command(label = \"Neustart\", underline = 0, command = reset)\nmFile.add_separator()\nmFile.add_command(label = \"Beenden\", command = end)\n\nmDebug.add_command(label = \"Debugger aus\", command = debug.debug_invisible_menu)\n\nmain[\"menu\"] = mBar\n\n# Anweisung\n # Anweisung Frame\nfrintroduction = tk.Frame(main, relief = \"sunken\", bd = 3)\nfrintroduction.configure(bg = bg)\nfrintroduction.grid(column = 0, row = 1, columnspan = 3)\n # Anweisung Text\ntxinstruction = tk.Text(frintroduction, bg = bg, width = 48, height = 2)\ntxinstruction.grid(column = 0, row = 0, columnspan = 3)\ntxinstruction.insert(tk.INSERT, \"Gewinne, indem du von deinen Symbolen,\\n\"\n \"3 in einer Reihe platzierst!\")\n\n# Spielfeld\n # Hauptfenster\ncatable = tk.Canvas(main, width = 210, height = 210, highlightbackground = \"sandybrown\", bg = \"peru\", relief = \"groove\", bd = 5)\ncatable.grid(column = 0, row = 2, sticky = \"w\", padx = 25, pady = 5)\ncatable_bg = tk.Canvas(catable, width = 210, height = 210, highlightbackground = \"sandybrown\", bg = \"peru\", relief = \"groove\", bd = 5)\ncatable_bg.grid(column = 0, row = 0)\n\ntable = tk.PhotoImage(file = \"table.png\")\ncatable_bg.create_image(113,113,image = table)\n\n # Feld 1\n# img_player = tk.PhotoImage(file = \"X.png\")\n# cafield_1 = tk.Canvas(catable, width = 9, height = 4)\n# cafield_1.grid(column = 0, row = 0)\n# cafield_1.create_image(60,60,image=img_player)\n# field_2 = tk.Text(frtable, width = 9, height = 4)\n# field_2.grid(column = 1, row = 0)\n# field_3 = tk.Text(frtable, width = 9, height = 4, bg = \"green\")\n# field_3.grid(column = 2, row = 0)\n# field_4 = tk.Text(frtable, width = 9, height = 4, bg = \"red\")\n# field_4.grid(column = 1, row = 1)\n# field_5 = tk.Text(frtable, width = 9, height = 4, bg = \"orange\")\n# field_5.grid(column = 0, row = 2)\n\n # Canvas\n# catable = tk.Canvas(main, width = 200, height = 200, highlightbackground = \"sandybrown\", bg = \"peru\", relief = \"groove\", bd = 5)\n# catable.grid_columnconfigure(2, weight = 5)\n# catable.grid_rowconfigure(2, weight = 5)\n# catable.grid(column = 0, row = 2, sticky = \"w\", padx = 25, pady = 5)\n # Linien\n# catable.create_line(5, 70, 205, 70, fill = \"black\", width = 3)\n# catable.create_line(5, 140, 205, 140, fill = \"black\", width = 3)\n# catable.create_line(70, 5, 70, 205, fill = \"black\", width = 3)\n# catable.create_line(140, 5, 140, 205, fill = \"black\", width = 3)\n\n# field_1 = tk.Canvas(catable, width = 60, height = 60)\n# # field_1.grid(column = 0, row = 0)\n# # catable.create_window(20,20, window = field_1)\n# catable.create_window(20,20, window=field_1)\n\n# Interface\n # Interface Frame\n\n\n # Interface Bilder\n# # Spieler\n# frplayer = tk.Frame(catable, bg = \"red\", relief = \"sunken\", bd = 0)\n# frplayer.configure(height = 60, width = 60)\n# frplayer.grid(column = 0, row = 0)\n# # Computer\n# frcomputer = tk.Frame(frinterface, bg = bg, relief = \"sunken\", bd = 0)\n# frcomputer.configure(height = 100, width = 120)\n# frcomputer.grid(column = 5, row = 1)\n\n # Interface Knöpfe\n # Frame Mitte\n# frmiddle = tk.Frame(frinterface, bg=\"peru\", relief=\"raised\", bd=4)\n# frmiddle.configure(height=100, width=120)\n# frmiddle.grid(column=3, row=1)\n\n # Interface Radiobutton\n # Frame Radio\nfrradio = tk.Frame(main, bg = \"sandybrown\", relief=\"groove\", bd=2)\nfrradio.grid(column = 1, row = 2)\n # Schere\n# rbscissor = tk.Radiobutton(frradio, bg = \"sandybrown\", text = \"Schere\", variable = pic_player, value = 0)\n# rbscissor.grid(column = 0, row = 0, sticky = \"w\")\n# # Stein\n# rbrock = tk.Radiobutton(frradio, bg = \"sandybrown\", text = \"Stein\", variable = pic_player, value = 1)\n# rbrock.grid(column = 0, row = 1, sticky = \"w\")\n# # Papier\n# rbpaper = tk.Radiobutton(frradio, bg = \"sandybrown\", text = \"Papier\", variable = pic_player, value = 2)\n# rbpaper.grid(column = 0, row = 2, sticky = \"w\")\n\n # Interface Bottom\n # Accept\n# buaccept = tk.Button(frradio, highlightbackground = \"sandybrown\", text = \"Bestätigen\", relief = \"ridge\", command = guess.guess)\n# buaccept.grid(column = 0, row = 3)\n # Restart\nburestart = tk.Button(frradio, highlightbackground = \"sandybrown\", text = \"Neustart\", relief = \"ridge\", command = reset)\nburestart.grid(column = 1, row = 0, rowspan = 2)\n # Beenden\nbuend = tk.Button(frradio, highlightbackground = \"sandybrown\", text = \"Beenden\", relief = \"ridge\", command = end)\nbuend.grid(column = 1, row = 2, rowspan = 2)\n\n# Hauptprogrammschleife starten\nmain.mainloop()","sub_path":"Spielesammlung/Spielesammlung_mit_GUI/tic_tac_toe.py","file_name":"tic_tac_toe.py","file_ext":"py","file_size_in_byte":9277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"361818733","text":"import pygame\nfrom groundcell import GroundCell\nfrom brickcell import BrickCell\nfrom watercell import WaterCell\nfrom stonecell import StoneCell\n\n\nCELL_WIDTH = 60\nCELL_HEIGHT = 60\nNUM_ROWS = 10\nNUM_COLS = 10\n\nclass Board():\n def __init__(self): \n self.grid = [[0]*NUM_COLS for a in range(NUM_ROWS)]\n self.cells = pygame.sprite.Group()\n\n def init_board(self,data):\n for i in xrange(2,len(data)):\n for c in data[i].split(\";\"):\n tmp = c.split(\",\")\n self.grid[int(tmp[1])][int(tmp[0])] = 1-i\n \n def draw_board(self):\n for i in xrange(NUM_ROWS):\n for j in xrange(NUM_COLS):\n if self.grid[i][j] == 0:\n cell = GroundCell()\n elif self.grid[i][j] == -1:\n cell = BrickCell()\n elif self.grid[i][j] == -2:\n cell = StoneCell()\n elif self.grid[i][j] == -3:\n cell = WaterCell()\n \n x = j*CELL_WIDTH\n y = i*CELL_HEIGHT\n \n cell.rect = pygame.Rect(x,y,CELL_WIDTH,CELL_HEIGHT)\n self.cells.add(cell)\n\n def move_tank(self,dire,i,j):\n if dire == 0 :\n if self.grid[i-1][j] == 0 and i != 0 :\n i -= 1\n elif dire == 1:\n if j != NUM_ROWS - 1 and self.grid[i][j+1] == 0:\n j += 1\n elif dire == 2:\n if i != NUM_COLS - 1 and self.grid[i+1][j] == 0:\n i += 1\n elif dire == 3:\n if self.grid[i][j-1] == 0 and j != 0:\n j -= 1\n \n x = j*CELL_WIDTH\n y = i*CELL_HEIGHT\n \n return [i,j,x,y] \n\n \n \n","sub_path":"board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"586413930","text":"import random\nfrom datetime import datetime\nimport time\n\ndef sorting(the_list):\n starter=0\n smallest=9999\n index=0\n\n while starterthe_list[number]:\n smallest=the_list[number]\n index=number\n\n the_list[starter], the_list[index] = the_list[index], the_list[starter]\n starter+=1\n smallest = 9999\n\n return(the_list)\n\nrandom.seed(int(str(datetime.now()).split(\".\")[1]))\n\nourlist=[]\nfor num in range(0,10000):\n ourlist.append(random.randint(0,100))\n\nprint(ourlist)\nstart_time = time.time()\n\nprint(sorting(ourlist))\n\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n\nstart_time = time.time()\nourlist.sort()\nprint(ourlist)\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n\n","sub_path":"sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"80476936","text":"\"\"\"\nA collection of activation functions.\n\"\"\"\n\nimport numpy as np\n\n\ndef sigmoid(n, derivative=False):\n \"\"\"\n The classical sigmoid function.\n :param n: (int/np.ndarray) The input to be 'activated'\n :param derivative: (bool/default=False) If this parameter is set to True, the derivative\n of the function will be returned.\n :return: The 'activated' value of 'n'...\n \"\"\"\n s1 = np.asscalar(np.array([1.], dtype=\"float64\"))\n if derivative:\n return n * (s1 - n)\n\n return s1 / (s1 + np.exp(-n))\n\n\ndef relu(n, derivative=False):\n if derivative:\n return (n > 0).astype(float)\n\n return np.maximum(0, n)\n\n\ndef softmax(n, axis=-1, derivative=False):\n if derivative:\n return np.asscalar(np.array([1.], dtype=\"float64\"))\n e = np.exp(n - np.max(n, axis=axis, keepdims=True))\n s = np.sum(e, axis=axis, keepdims=True)\n return e / s\n\n\ndef lrelu(n, derivative=False, leakage=0.01):\n if derivative:\n return np.clip(n > 0, leakage, 1.0)\n\n output = np.copy(n)\n output[output < 0] *= leakage\n return output\n\n\ndef tanh(n, derivative=False):\n n = np.tanh(n)\n if derivative:\n return 1 - np.power(n, 2)\n\n return n\n\n\ndef linear(n, derivative=False):\n if derivative:\n return 1\n return n\n\n\nactivation_functions = {\n \"sigmoid\": sigmoid,\n \"relu\": relu,\n \"softmax\": softmax,\n \"lrelu\": lrelu,\n \"tanh\": tanh,\n \"linear\": linear\n}","sub_path":"bull/layers/activation_functions.py","file_name":"activation_functions.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"409519099","text":"import imageio\nimport SimpleITK as sitk\nimport numpy as np\n\nimg = sitk.GetArrayFromImage(sitk.ReadImage(\"../datasets/BRATS_Dataset/brats_dataset/HGG/Brats18_2013_10_1/Brats18_2013_10_1_flair.nii.gz\"))\nimg = (img/img.max())*255\nimg = img.astype(np.uint8)\nimg = np.stack((img,)*3, axis=-1)\n\nseg = sitk.GetArrayFromImage(sitk.ReadImage(\"../datasets/BRATS_Dataset/brats_dataset/HGG/Brats18_2013_10_1/Brats18_2013_10_1_seg.nii.gz\"))\nncr = seg == 1\ned = seg == 2\net = seg == 4\n\nseg = (np.stack([ncr, ed, et])*255).astype(np.uint8)\nseg = seg.transpose(1,2,3,0)\n\nwith imageio.get_writer('mri.gif', mode='I', fps=15) as writer:\n alpha = 0.5\n images = (img*alpha + seg*(1-alpha)).astype(np.uint8)\n for i in images:\n writer.append_data(i)","sub_path":"mri_to_gif.py","file_name":"mri_to_gif.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"229764109","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 19 13:10:07 2014\n\n@author: W4TB\n\"\"\"\n\nfrom selenium import webdriver\nfrom selenium.webdriver import ActionChains\nfrom collections import defaultdict\nfrom selenium.webdriver.common.keys import Keys\nfrom csv import DictWriter\n\ndirectorySearch_url = \"http://mydoctor.kaiserpermanente.org/mas/mdo/\"\n\ndriver = webdriver.Chrome()\ndriver.get(directorySearch_url)\ndriver.implicitly_wait(15)\n\nfirstNameBox = driver.find_element_by_id(\"firstName\")\nfirstNameBox.send_keys(\"\")\n\nlastNameBox = driver.find_element_by_id(\"lastName\")\nlastNameBox.send_keys(\"Jo\")\n\ndriver.find_element_by_name(\"Submit\").submit()\n\ndocResults = (driver.find_elements_by_xpath(\"//tr[@class = 'odd']\") +\n driver.find_elements_by_xpath(\"//tr[@class = 'even']\"))\n\ndocList = []\nresultsPage = driver.current_window_handle\n\nfor result in docResults:\n doc = defaultdict()\n lastAndFirst = result.find_elements_by_xpath(\".//a\")\n link = lastAndFirst[0]\n doc['Link'] = link.get_attribute(\"href\")\n doc['Last Name'] = link.text\n doc['First Name'] = lastAndFirst[1].text\n \n newTabActions = ActionChains(driver)\n newTabActions.key_down(Keys.CONTROL)\n newTabActions.click(link)\n newTabActions.key_up(Keys.CONTROL)\n newTabActions.perform()\n \n driver.switch_to_window(driver.window_handles[-1])\n officeLink = driver.find_element_by_xpath(\"//li[@id = 'tab-offices']/a\")\n officeLink.click()\n \n addressList = []\n for element in driver.find_elements_by_xpath(\"//div[@class = 'drOffices']//ul//li\"):\n addressList.append(element.text)\n \n addressNum = 1 \n for i in range(0, len(addressList) - 1, 2):\n keyString = \"Address \" + str(addressNum)\n doc[keyString] = (addressList[i] + \" \" + addressList[i + 1])\n addressNum += 1\n driver.close()\n \n driver.switch_to_window(resultsPage)\n\n docList.append(doc)\n \nwith open(\"F:\\\\KaiserScrapeOutput.csv\", 'w') as f:\n fieldnames = set() \n for doc in docList:\n for key in doc.keys():\n fieldnames.add(key)\n \n for doc in docList:\n for fieldname in fieldnames:\n if fieldname not in doc.keys():\n doc[fieldname] = \"\"\n \n writer = DictWriter(f, fieldnames)\n for doc in docList:\n writer.writerow(doc)\n \ndriver.close()","sub_path":"KaiserScrapeTest.py","file_name":"KaiserScrapeTest.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"186772296","text":"import re\nfrom six import iteritems\nfrom whatsopt.utils import simple_value, to_camelcase, extract_disc_var, format_shape\nfrom .logging import debug, log\nfrom openmdao.api import IndepVarComp\n\ntry: # openmdao < 2.9\n from openmdao.devtools.problem_viewer.problem_viewer import _get_viewer_data\nexcept ImportError: # openmdao >= 2.9\n from openmdao.visualization.n2_viewer.n2_viewer import _get_viewer_data\n\nNULL_DRIVER_NAME = \"__DRIVER__\" # check WhatsOpt Discipline model\n\n\nclass PushCommand(object):\n def __init__(self, problem, scalar_format):\n data = _get_viewer_data(problem)\n self.problem = problem\n self.scalar_format = scalar_format\n self.tree = data[\"tree\"]\n self.connections = data[\"connections_list\"]\n self.vars = {}\n self.vardescs = {}\n self.discmap = {}\n\n def get_mda_attributes(self, group, tree, group_prefix=\"\"):\n self._collect_disc_infos()\n self._collect_var_infos()\n driver_attrs = {\"name\": NULL_DRIVER_NAME, \"variables_attributes\": []}\n mda_attrs = {\n \"name\": group.__class__.__name__,\n \"disciplines_attributes\": [driver_attrs],\n }\n if \"children\" not in tree:\n return\n\n for i, child in enumerate(tree[\"children\"]):\n if child[\"type\"] == \"subsystem\" and child[\"subsystem_type\"] == \"group\":\n prefix = group_prefix + child[\"name\"] + \".\"\n sub_analysis_attrs = self._get_sub_analysis_attributes(\n group._subsystems_myproc[i], child, prefix\n )\n mda_attrs[\"disciplines_attributes\"].append(sub_analysis_attrs)\n else:\n if not isinstance(group._subsystems_myproc[i], IndepVarComp):\n mda = group_prefix[:-1]\n discname = group_prefix + child[\"name\"]\n discattrs = self._get_discipline_attributes(\n driver_attrs, mda, discname\n )\n\n self._set_varattrs_from_outputs(\n group._subsystems_myproc[i]._var_abs2prom[\"output\"],\n \"out\",\n discattrs[\"variables_attributes\"],\n )\n\n mda_attrs[\"disciplines_attributes\"].append(discattrs)\n else:\n self._set_varattrs_from_outputs(\n group._subsystems_myproc[i]._var_abs2prom[\"output\"],\n \"out\",\n driver_attrs[\"variables_attributes\"],\n )\n\n self._set_varattrs_from_outputs(\n group._var_abs2prom[\"output\"], \"in\", driver_attrs[\"variables_attributes\"]\n )\n\n # remove fullname in driver varattrs\n for vattr in driver_attrs[\"variables_attributes\"]:\n vattr[\"desc\"] = self.vardescs[vattr[\"name\"]]\n if (\n vattr[\"io_mode\"] == \"out\"\n ): # set init value for design variables and parameters (outputs of driver)\n v = self.vars[vattr[\"fullname\"]]\n vattr[\"parameter_attributes\"] = {\"init\": simple_value(v)}\n if \"fullname\" in vattr:\n del vattr[\"fullname\"] # indeed for WhatsOpt var name is a primary key\n\n for discattr in mda_attrs[\"disciplines_attributes\"]:\n if \"variables_attributes\" in discattr:\n for vattr in discattr[\"variables_attributes\"]:\n if \"fullname\" in vattr:\n del vattr[\n \"fullname\"\n ] # indeed for WhatsOpt var name is a primary key\n\n return mda_attrs\n\n def _get_sub_analysis_attributes(self, group, child, prefix):\n submda_attrs = self.get_mda_attributes(group, child, prefix)\n submda_attrs[\"name\"] = to_camelcase(child[\"name\"])\n superdisc_attrs = {\n \"name\": child[\"name\"],\n \"sub_analysis_attributes\": submda_attrs,\n }\n return superdisc_attrs\n\n def _get_discipline_attributes(self, driver_attrs, mda, dname):\n varattrs = self._get_variables_attrs(\n driver_attrs[\"variables_attributes\"], mda, dname\n )\n discattrs = {\n \"name\": to_camelcase(self.discmap[dname]),\n \"variables_attributes\": varattrs,\n }\n return discattrs\n\n def _set_varattrs_from_outputs(self, outputs, io_mode, varattrs):\n for absname, varname in iteritems(outputs):\n if varname not in [varattr[\"name\"] for varattr in varattrs]:\n var = self.vars[absname]\n vattr = {\n \"name\": varname,\n \"fullname\": absname,\n \"io_mode\": io_mode,\n \"desc\": self.vardescs[varname],\n \"type\": var[\"type\"],\n \"shape\": var[\"shape\"],\n \"units\": var[\"units\"],\n }\n varattrs.append(vattr)\n\n def _get_varattr_from_connection(\n self, varattrs, driver_varattrs, mda, dname, connection\n ):\n fnamesrc = connection[\"src\"]\n mdasrc, discsrc, varsrc = extract_disc_var(fnamesrc)\n fnametgt = connection[\"tgt\"]\n mdatgt, disctgt, vartgt = extract_disc_var(fnametgt)\n debug(\"++++ MDA=%s DISC=%s\" % (mda, dname))\n debug(\n \"######### SRC=%s DISCSRC=%s TGT=%s DISCTGT=%s\"\n % (mdasrc, discsrc, mdatgt, disctgt)\n )\n\n varstoadd = []\n if mda == mdasrc and discsrc == dname:\n varattrsrc = {\n \"name\": varsrc,\n \"fullname\": fnamesrc,\n \"io_mode\": \"out\",\n \"type\": self.vars[fnamesrc][\"type\"],\n \"shape\": self.vars[fnamesrc][\"shape\"],\n \"units\": self.vars[fnamesrc][\"units\"],\n }\n varstoadd.append((discsrc, varattrsrc, \"source\"))\n if mda != \"\" and mda not in mdatgt:\n discsrc = NULL_DRIVER_NAME\n varattrsrc = {\n \"name\": varsrc,\n \"fullname\": fnamesrc,\n \"io_mode\": \"in\",\n \"type\": self.vars[fnametgt][\"type\"],\n \"shape\": self.vars[fnametgt][\"shape\"],\n \"units\": self.vars[fnametgt][\"units\"],\n }\n varstoadd.append((discsrc, varattrsrc, \"source\"))\n\n if mda == mdatgt and disctgt == dname:\n varattrtgt = {\n \"name\": vartgt,\n \"fullname\": fnametgt,\n \"io_mode\": \"in\",\n \"type\": self.vars[fnametgt][\"type\"],\n \"shape\": self.vars[fnametgt][\"shape\"],\n \"units\": self.vars[fnametgt][\"units\"],\n }\n varstoadd.append((disctgt, varattrtgt, \"target\"))\n if mda != \"\" and mda not in mdasrc:\n disctgt = NULL_DRIVER_NAME\n varattrtgt = {\n \"name\": vartgt,\n \"fullname\": fnametgt,\n \"io_mode\": \"out\",\n \"type\": self.vars[fnamesrc][\"type\"],\n \"shape\": self.vars[fnamesrc][\"shape\"],\n \"units\": self.vars[fnamesrc][\"units\"],\n }\n varstoadd.append((disctgt, varattrtgt, \"target\"))\n\n for disc, varattr, orig in varstoadd:\n debug(\"**************\", connection)\n if disc == dname:\n if varattr not in varattrs:\n debug(\n \">>>>>>>>>>>>> from\",\n orig,\n \" ADD to \",\n mda,\n dname,\n \": \",\n varattr[\"name\"],\n varattr[\"io_mode\"],\n )\n varattrs.append(varattr)\n else:\n if varattr[\"name\"] not in [vattr[\"name\"] for vattr in driver_varattrs]:\n debug(\n \">>>>>>>>>>>>> from\",\n orig,\n \" ADD to \",\n mda,\n \"__DRIVER__ :\",\n varattr[\"name\"],\n varattr[\"io_mode\"],\n )\n driver_varattrs.append(varattr)\n\n def _get_variables_attrs(self, driver_varattrs, mda, dname):\n varattrs = []\n for conn in self.connections:\n self._get_varattr_from_connection(\n varattrs, driver_varattrs, mda, dname, conn\n )\n for vattr in varattrs:\n vattr[\"desc\"] = self.vardescs[vattr[\"name\"]]\n if \"fullname\" in vattr:\n del vattr[\"fullname\"] # indeed for WhatsOpt var name is a primary key\n return varattrs\n\n # # see _get_tree_dict at\n # # https://github.com/OpenMDAO/OpenMDAO/blob/master/openmdao/devtools/problem_viewer/problem_viewer.py\n def _collect_disc_infos(self, group_prefix=\"\"):\n if \"children\" not in self.tree:\n return\n\n for i, child in enumerate(self.tree[\"children\"]):\n # retain only components, not intermediates (subsystem or group)\n if child[\"type\"] == \"subsystem\" and child[\"subsystem_type\"] == \"group\":\n self.discmap[group_prefix + child[\"name\"]] = child[\"name\"]\n prefix = group_prefix + child[\"name\"] + \".\"\n self._collect_disc_infos(prefix)\n else:\n # do not represent IndepVarComp\n if not isinstance(\n self.problem.model._subsystems_myproc[i], IndepVarComp\n ):\n self.discmap[group_prefix + child[\"name\"]] = child[\"name\"]\n else:\n self.discmap[group_prefix + child[\"name\"]] = \"__DRIVER__\"\n\n # see _get_tree_dict at\n # https://github.com/OpenMDAO/OpenMDAO/blob/master/openmdao/devtools/problem_viewer/problem_viewer.py\n def _collect_var_infos(self):\n for typ in [\"input\", \"output\"]:\n for abs_name in self.problem.model._var_abs_names[typ]:\n if typ == \"input\":\n io_mode = \"in\"\n elif typ == \"output\":\n io_mode = \"out\"\n else:\n raise Exception(\"Unhandled variable type \" + typ)\n meta = self.problem.model._var_abs2meta[abs_name]\n\n vtype = \"Float\"\n if re.match(\"int\", type(meta[\"value\"]).__name__):\n vtype = \"Integer\"\n shape = str(meta[\"shape\"])\n shape = format_shape(self.scalar_format, shape)\n name = self.problem.model._var_abs2prom[typ][abs_name]\n self.vars[abs_name] = {\n \"fullname\": abs_name,\n \"name\": name,\n \"io_mode\": io_mode,\n \"type\": vtype,\n \"shape\": shape,\n \"units\": meta[\"units\"],\n #'desc': meta['desc'],\n \"value\": meta[\"value\"],\n }\n\n # retrieve initial conditions\n var = self.vars[abs_name]\n if abs_name in self.problem.model._outputs._views:\n var[\"value\"] = self.problem.model._outputs[abs_name]\n elif abs_name in self.problem.model._inputs._views:\n var[\"value\"] = self.problem.model._inputs[abs_name]\n elif abs_name in self.problem.model._discrete_outputs:\n var[\"value\"] = self.problem.model._discrete_outputs[abs_name]\n elif abs_name in self.problem.model._discrete_inputs:\n var[\"value\"] = self.problem.model._discrete_inputs[abs_name]\n\n desc = self.vardescs.setdefault(name, \"\")\n if desc == \"\":\n self.vardescs[name] = meta[\"desc\"]\n elif desc != meta[\"desc\"] and meta[\"desc\"] != \"\":\n log(\n 'Find another description for {}: \"{}\", keep \"{}\"'.format(\n name, meta[\"desc\"], self.vardescs[name]\n )\n )\n","sub_path":"whatsopt/push_command.py","file_name":"push_command.py","file_ext":"py","file_size_in_byte":12241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"508983693","text":"from django.urls import reverse\n\nfrom AutoParts.accounts.models import Profile\nfrom AutoParts.store.models import Order\nfrom Tests.base.tests import AutoPartsTestCase\n\n\nclass CartViewTest(AutoPartsTestCase):\n\n def test_cart_view__if_right_template_is_used_with_authenticated_user(self):\n self.client.force_login(self.user)\n response = self.client.get(reverse('cart'))\n\n self.assertTemplateUsed(response, 'store/cart.html')\n\n def test_cart_view__if_user_is_not_authenticated(self):\n response = self.client.get(reverse('cart'))\n messages = list(response.context['messages'])\n self.assertEqual('You need to be sign in', str(messages[0]))\n\n def test_cart_view__with_is_authenticated_user_and_no_orders(self):\n self.client.force_login(self.user)\n response = self.client.get(reverse('cart'))\n order = response.context['order']\n self.assertEqual(None, order)\n\n def test_cart_view__with_is_authenticated_user_and_orders(self):\n self.client.force_login(self.user)\n customer = Profile.objects.first()\n order = Order.objects.create(customer=customer, complete=False)\n\n response = self.client.get(reverse('cart'))\n self.assertEqual(order, response.context['order'])","sub_path":"AutoParts/Tests/store/views/cart_view.py","file_name":"cart_view.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"561623980","text":"from selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\n\nfrom selenium.common.exceptions import NoSuchElementException, TimeoutException\n\n# initialize the driver\ndriver = webdriver.Chrome(\n executable_path='/Users/ingabukhvalova/PycharmProjects/python-selenium-automation/chromedriver')\ndriver.maximize_window()\n\n\n# open the url\ndriver.get('https://www.amazon.com/s?k=echo+dot&ref=nb_sb_noss_2')\ndriver.implicitly_wait(4)\n\n\n\n#click on element\nelement_found = driver.find_element(By.XPATH, \"//img[@alt='Echo Dot (3rd Gen) - Smart speaker with clock and Alexa - Sandstone']\")\nprint (\"found element = {0}\".format(element_found))\nelement_found.click()\n\n#wait\nwait=WebDriverWait(driver, 10)\nsomething=wait.until(EC.presence_of_element_located((By.XPATH, '//meta[@content=\"echo dot\"]')))\n\n#add to cart\ndriver.find_element_by_xpath('//input[@id=\"add-to-cart-button\"]').click()\n\n\n\ntry:\n WebDriverWait(driver, 3).until(EC.new_window_is_opened,\n 'Timed out waiting for popup window to appear.')\n alert = driver.switch_to.window()\n alert.dismiss()\n print(\"alert accepted\")\nexcept TimeoutException:\n print(\"no alert\")\n\n\n\n#verify and quit\ntext_expected = driver.find_element(By.XPATH, \"//span[contains(text(),'(1 item):')]\")\n\ndriver.quit()\n\n","sub_path":"add_product_script.py","file_name":"add_product_script.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"152310499","text":"import warnings\n\nfrom django.test import TestCase\nfrom django.test.client import Client as BaseClient\n\n\nclass Client(BaseClient):\n def login(self, *args, **kwargs):\n with warnings.catch_warnings(record=True) as w:\n ret = super(Client, self).login(*args, **kwargs)\n assert len(w) == 1\n return ret\n\n\nclass FeedHQTestCase(TestCase):\n client_class = Client\n","sub_path":"tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"70020","text":"# -*- encoding: utf-8 -*-\nimport logging\nimport urllib\nimport urlparse\nimport json\nimport string\nimport random\nimport time\nfrom tornado import web, gen, httpclient\nfrom .. import validator, exception\nfrom ..model import manager\nfrom ..auth import httpbasicauth, signature\n\n\n# (r\"/template\", template.IndexHandler),\nclass IndexHandler(web.RequestHandler):\n @httpbasicauth\n @web.asynchronous\n @gen.coroutine\n def get(self):\n itemPerPage = 20\n try:\n page = int(self.get_argument('page', 1))\n except ValueError:\n page = 1\n tab = self.get_argument('t', 'wait4audit')\n limit = page * itemPerPage\n offset = (page - 1) * itemPerPage\n query = {\n 'wait4audit': {'approved': manager.WAIT4AUD},\n 'approved': {'approved': manager.APPROVED},\n 'rejected': {'approved': manager.REJECTED},\n }\n\n db = self.settings['db']\n tm = manager.TplManager(db)\n res = yield tm.find(query.get(tab), offset, limit)\n count = yield tm.count(query.get('wait4audit'))\n acount = yield tm.count(query.get('approved'))\n rcount = yield tm.count(query.get('rejected'))\n tabcnt = {\n 'wait4audit': count,\n 'approved': acount,\n 'rejected': rcount\n }\n params = dict(\n tab=tab,\n page=page,\n itemPerPage=itemPerPage,\n count=count,\n acount=acount,\n rcount=rcount,\n total=tabcnt.get(tab, 0),\n tpls=res,\n )\n self.render('template/index.html.twig', **params)\n\n\n# post data:\n# content: string with variables \"this is the {key} field of template\" {key}\n# will be replaced with value which you've registered.\n# keys: [key, key1]\n# tag: tag for group of template\n\n# (r\"/template/register\", template.RegisterHandler),\nclass RegisterHandler(web.RequestHandler):\n @web.asynchronous\n @gen.coroutine\n def post(self):\n def genTplId(len=6):\n return ''.join(random.choice(string.letters) for x in range(len))\n\n tplid = genTplId()\n tpl = {\n 'tplid': tplid,\n 'content': self.get_argument('content', ''),\n 'name': self.get_argument('name', ''),\n 'tags': self.get_argument('tags', '').split(','),\n 'keys': self.get_argument('keys', '').split(','),\n 'entid': self.get_argument('entid', ''),\n 'product': self.get_argument('product', ''),\n 'callback': self.get_argument('callback', ''),\n 'created_at': int(time.time()),\n 'type': 'marketing',\n 'approved': manager.WAIT4AUD,\n 'approved_at': '',\n }\n try:\n res = yield self.register(tpl)\n if res:\n self.write({'res': 'succ', 'data': {'tplid': tplid}})\n else:\n self.write({'res': 'fail', 'info': 'insert data error'})\n except exception.SmsException as e:\n logging.error(e)\n self.write(str(e))\n finally:\n self.finish()\n\n @validator.required(\"entid\")\n @validator.required(\"name\")\n @validator.required(\"content\")\n @validator.required(\"product\")\n @gen.coroutine\n def register(self, tpl):\n db = self.settings['db']\n tm = manager.TplManager(db)\n result = yield tm.insert(tpl)\n raise gen.Return(result)\n\n\nclass ListHandler(web.RequestHandler):\n @web.asynchronous\n @gen.coroutine\n def get(self):\n try:\n offset = int(self.get_argument('offset', 0))\n except ValueError:\n offset = 0\n try:\n limit = int(self.get_argument('limit', 10))\n except ValueError:\n limit = 10\n try:\n db = self.settings['db']\n tm = manager.TplManager(db)\n query = {\n 'entid': self.get_argument('entid', ''),\n 'product': self.get_argument('product', ''),\n }\n total = yield tm.count(query)\n tag = self.get_argument('tag', None)\n if tag:\n query['tag'] = tag\n res = yield tm.find(query, offset, limit)\n self.write({\n 'res': 'succ',\n 'count': total,\n 'offset': offset,\n 'limit': limit,\n 'data': res,\n })\n except exception.SmsException as e:\n logging.error(e)\n self.write(str(e))\n finally:\n self.finish()\n\n\nclass UpdateHandler(web.RequestHandler):\n @web.asynchronous\n @gen.coroutine\n def post(self):\n tplid = self.get_argument('tplid', '')\n data = {\n 'content': self.get_argument('content', ''),\n 'approved': manager.WAIT4AUD,\n }\n callback = self.get_argument('callback', None)\n if callback or callback != '':\n data['callback'] = callback\n tags = self.get_argument('tags', None)\n if tags:\n data['tags'] = tags.split(',')\n keys = self.get_argument('keys', None)\n if keys:\n data['keys'] = keys.split(',')\n update = {'$set': data}\n q = {\n 'tplid': tplid,\n 'entid': self.get_argument('entid', ''),\n 'product': self.get_argument('product', ''),\n }\n db = self.settings['db']\n tm = manager.TplManager(db)\n try:\n result = yield tm.update(q, update)\n if result:\n self.write({'res': 'succ', 'data': result})\n else:\n self.write({\n 'res': 'fail',\n 'msg': 'tpl {0} not found or \\\n fail for update.'.format(tplid),\n })\n except exception.SmsException as e:\n logging.error(e)\n self.write(str(e))\n finally:\n self.finish()\n\n\n### for administrator ###\nclass OperateHandler(web.RequestHandler):\n @web.asynchronous\n @gen.coroutine\n def post(self, action):\n act = {\n 'approve': self._approve,\n 'marketing': self._marketing,\n 'recover': self._recover,\n 'reject': self._reject\n }\n tplids = self.get_arguments('tplid[]', '')\n db = self.settings['db']\n self.tm = manager.TplManager(db)\n try:\n result = yield act.get(action)(tplids)\n self.write(json.dumps({'res': 'succ', 'msg': result}))\n except exception.SmsException as e:\n logging.error(e)\n self.write(str(e))\n finally:\n self.finish()\n\n @gen.coroutine\n def _approve(self, tplids):\n result = yield self.tm.approve(tplids, sendType='notice')\n self.callback(tplids)\n raise gen.Return(result)\n\n @gen.coroutine\n def _marketing(self, tplids):\n result = yield self.tm.approve(tplids)\n self.callback(tplids)\n raise gen.Return(result)\n\n @gen.coroutine\n def _recover(self, tplids):\n query = {'tplid': {'$in': tplids}}\n update = {'$set': {'approved': manager.WAIT4AUD}}\n result = yield self.tm.update(query, update)\n self.callback(tplids)\n raise gen.Return(result)\n\n @gen.coroutine\n def _reject(self, tplids):\n reason = self.get_argument('reason', None),\n query = {'tplid': {'$in': tplids}}\n update = {'$set': {'approved': manager.REJECTED, 'reason': reason[0]}}\n result = yield self.tm.update(query, update)\n self.callback(tplids)\n raise gen.Return(result)\n\n @gen.coroutine\n def callback(self, tplids):\n query = {'tplid': {'$in': tplids}, 'callback': {'$exists': True}}\n results = yield self.tm.find(query)\n for tpl in results:\n callback = tpl.get('callback')\n logging.debug(callback)\n url = urlparse.urlparse(callback)\n if url.netloc == '':\n continue\n message = {'tplid': tpl.get('tplid'), 'status': tpl.get('approved')}\n if message['status'] == manager.REJECTED:\n message['reason'] = tpl.get('reason').encode('utf-8')\n\n client = httpclient.AsyncHTTPClient()\n httpclient.AsyncHTTPClient.configure(\n \"tornado.curl_httpclient.CurlAsyncHTTPClient\")\n yield client.fetch(callback,\n _handle_request, method='POST',\n body=urllib.urlencode(message))\n\n\n#path: /sendByTmpl\nclass SendHandler(web.RequestHandler):\n @web.asynchronous\n @gen.coroutine\n def post(self):\n tplid = self.get_argument('tplid', '')\n db = self.settings['db']\n tm = manager.TplManager(db)\n try:\n tpl = yield tm.findApproved(tplid)\n if tpl:\n result = yield self.send(tpl)\n self.write(result)\n else:\n self.write({'res': 'fail',\n 'info': 'tpl {0} not found or not approved.'\n .format(tplid)})\n except Exception as e:\n logging.error(e)\n self.write({'res': 'fail', 'info': str(e)})\n finally:\n self.finish()\n\n @validator.required(\"entid\")\n @validator.required(\"entpwd\")\n @validator.required(\"license\")\n @validator.required(\"product\")\n @validator.required(\"phones\")\n @validator.required(\"timestamp\")\n @validator.required(\"replace\")\n @validator.required(\"tplid\")\n #@validator.authenticate\n @gen.coroutine\n def send(self, tpl):\n logging.info(\"send message from {0}.\"\n .format(self.get_argument('product')))\n try:\n msg = self.buildMessage(tpl)\n response = yield self.directSend(msg)\n body = json.loads(response.body)\n except Exception as e:\n raise gen.Return({'res': 'fail', 'info': str(e)})\n raise gen.Return(body)\n\n # 发送给短信平台,需要重新计算签名\n @signature('certi_ac')\n def buildMessage(self, tpl):\n m = {\n 'format': 'json',\n 'version': '1.0',\n 'encoding': 'utf8',\n 'certi_app': 'sms.send',\n 'timestamp': int(time.time()),\n 'license': self.get_argument('license'),\n 'source': self.get_argument('product'),\n 'entId': self.get_argument('entid'),\n 'entPwd': self.get_argument('entpwd'),\n }\n use_reply = self.get_argument('use_reply', 0)\n if use_reply == '':\n m['use_reply'] = 0\n backlist = self.get_argument('use_backlist', 1)\n if backlist == '':\n m['use_backlist'] = 1\n\n m['sendType'] = 'fan-out' if tpl.get('type') == 'marketing' else 'notice'\n replace = self.get_argument('replace')\n try:\n r = json.loads(replace)\n content = tpl.get('content')\n keys = tpl.get('keys')\n for k, v in r.items():\n if k in keys:\n if isinstance(v, int):\n v = str(v)\n elif isinstance(v, float):\n v = str(v)\n elif v is None:\n v = ''\n content = content.replace('{{{0}}}'.format(k), v)\n contents = [{\n 'phones': self.get_argument('phones'),\n 'content': content,\n }]\n m['contents'] = json.dumps(contents)\n except Exception as e:\n raise exception.SmsException(\n 20001, 'template content error: {0}'.format(str(e)))\n return m\n\n @gen.coroutine\n def directSend(self, message={}):\n logging.info(message)\n client = httpclient.AsyncHTTPClient()\n httpclient.AsyncHTTPClient.configure(\n \"tornado.curl_httpclient.CurlAsyncHTTPClient\")\n response = yield client.fetch(\n self.settings.get('smsapi'),\n _handle_request,\n method='POST',\n body=urllib.urlencode(message))\n raise gen.Return(response)\n\n\ndef _handle_request(response):\n if response.error:\n logging.error(response.error)\n else:\n logging.info(response.body)\n","sub_path":"app/controller/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":12309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"608568264","text":"from statistics import mean\nnum_iterations = 3\nnum_processor_counts = ['24', '28', '32', '36', '40']\nnum_k = ['2', '25', '50', '100']\nwrite_lines = []\nsums = []\n\n# Build up values dict for population\nvals = {}\nfor p in num_processor_counts:\n vals.update({p:{}})\n for k in num_k:\n vals[p].update({k: {}})\n vals[p][k].update({'distance': 0})\n vals[p][k].update({'centroid': 0})\n vals[p][k].update({'total': 0})\n\n# Read in timing data\nwith open(\"./timings.txt\", \"r\") as fp:\n lines = fp.readlines()\n\n for line in lines:\n if line[0] == 'k':\n short = line[6:].strip()\n nprocs, k = short.split(sep='_')\n\n try:\n spl = line.split()\n for word in range(len(spl)):\n spl[word] = spl[word].rstrip(',')\n distance = float(spl[4])\n centroid = float(spl[-1])\n total = float(spl[2])\n vals[nprocs][k]['distance'] += distance\n vals[nprocs][k]['centroid'] += centroid\n vals[nprocs][k]['total'] += total\n except ValueError:\n pass\n except IndexError:\n pass\n\n for p in num_processor_counts:\n for k in num_k:\n d_mean = vals[p][k]['distance'] / num_iterations\n c_mean = vals[p][k]['centroid'] / num_iterations\n tot_mean = vals[p][k]['total'] / num_iterations\n write_lines.append(\n f\"NPROCS = {p}\\t\"\n f\"K = {k}\\t\"\n f\"dist = {round(d_mean, 4)}\\t\"\n f\"centroid = {round(c_mean, 4)}\\t\"\n f\"total = {round(tot_mean, 4)}\")\n\n# Write to a summary document\nwith open(\"./summary.txt\", \"w\") as w_fp:\n for timing in write_lines:\n w_fp.write(timing + \"\\n\")\n # w_fp.write(f\"global sum: {str(sum)}\\n\\n\")\n\nprint(\"Wrote summary.txt\")\n","sub_path":"a5/a2/out/mean_times.py","file_name":"mean_times.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"400351471","text":"import re\r\nimport pprint\r\n\r\ndt = open(\"FastFoodRestaurants.csv\")\r\ndt.readline()\r\nline_num = 1\r\n\r\n\r\ndef getel(line):\r\n result = re.split(r\",\", line, maxsplit=1)\r\n element = result[0].strip(\"\\\"\")\r\n return element, result[1]\r\n\r\n\r\ndef getaddress(line):\r\n address, line = getel(line)\r\n return address, line\r\n\r\n\r\ndef getcity(line):\r\n city, line = getel(line)\r\n return city, line\r\n\r\n\r\ndef getcountry(line):\r\n country, line = getel(line)\r\n return country, line\r\n\r\n\r\ndef getkeys(line):\r\n keys, line = getel(line)\r\n return keys, line\r\n\r\n\r\ndef getlatitude(line):\r\n latitude, line = getel(line)\r\n return latitude, line\r\n\r\n\r\ndef getlongitude(line):\r\n longitude, line = getel(line)\r\n return longitude, line\r\n\r\n\r\ndataset = {}\r\nfor line in dt:\r\n line = line.strip().rstrip()\r\n address, line = getaddress(line)\r\n city, line = getcity(line)\r\n country, line = getcountry(line)\r\n keys, line = getkeys(line)\r\n latitude, line = getlatitude(line)\r\n if keys[9:30] in latitude:\r\n latitude, line = getlatitude(line)\r\n longitude, line = getlongitude(line)\r\n# print(line_num, country, keys, latitude, longitude)\r\n line_num += 1\r\n if country not in dataset:\r\n dataset[country] = {}\r\n if keys not in dataset[country]:\r\n dataset[country][keys] = dict()\r\n if latitude not in dataset[country][keys]:\r\n dataset[country][keys][latitude] = dict()\r\n dataset[country][keys][latitude] = longitude\r\n\r\npprint.pprint(dataset)\r\ndt.close()\r\n","sub_path":"km-81/Krasnova_Yana/datamess.py","file_name":"datamess.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"513928615","text":"#!/usr/bin/env python\n# encoding: utf-8\n#\n# Copyright SAS Institute\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''' Common layers for the deep learning models '''\n\nfrom .utils import prod_without_none\n\n\nclass Layer(object):\n '''\n Base class for all layers\n\n Parameters\n ----------\n name : str\n Specifies the name of the layer.\n config : dict\n Specifies the configuration of the layer.\n src_layers : iter-of-Layers, optional\n Specifies the source layer(s).\n\n Returns\n -------\n :class:`Layer`\n\n '''\n\n def __init__(self, name=None, config=None, src_layers=None):\n self.name = name\n self.config = config\n if isinstance(src_layers, list):\n self.src_layers = src_layers\n elif src_layers is None:\n self.src_layers = None\n else:\n self.src_layers = list(src_layers)\n\n if 'act' in self.config.keys():\n self.activation = config['act'].title()\n else:\n self.activation = None\n\n self.output_size = None\n self.kernel_size = None\n self.num_weights = None\n self.num_bias = None\n\n def to_model_params(self):\n '''\n Convert the model configuration to SAS Viya parameters\n\n Returns\n -------\n dict\n\n '''\n if self.config['type'].lower() == 'input':\n return dict(name=self.name, layer=self.config)\n else:\n return dict(name=self.name, layer=self.config,\n srclayers=[item.name for item in self.src_layers])\n\n @property\n def summary_str(self):\n '''\n Generate the summary string describing the configuration of the layer.\n '''\n if self.config['type'].lower() == 'input':\n self.output_size = (int(self.config['width']),\n int(self.config['height']),\n int(self.config['nchannels']))\n self.kernel_size = None\n self.num_weights = 0\n self.num_bias = 0\n\n elif self.config['type'].lower() in ('convo', 'convolution'):\n self.output_size = (int(self.src_layers[0].output_size[0] //\n self.config['stride']),\n int(self.src_layers[0].output_size[1] //\n self.config['stride']),\n int(self.config['nfilters']))\n self.kernel_size = (int(self.config['width']), int(self.config['height']))\n self.num_weights = int(self.config['width'] *\n self.config['height'] *\n self.config['nfilters'] *\n self.src_layers[0].output_size[2])\n if 'includeBias' in self.config.keys():\n if self.config['includeBias'] is False:\n self.num_bias = 0\n else:\n self.num_bias = int(self.config['nfilters'])\n else:\n self.num_bias = int(self.config['nfilters'])\n\n elif self.config['type'].lower() in ('pool', 'pooling'):\n self.output_size = (int(self.src_layers[0].output_size[0] //\n self.config['stride']),\n int(self.src_layers[0].output_size[1] //\n self.config['stride']),\n int(self.src_layers[0].output_size[2]))\n self.kernel_size = (int(self.config['width']), int(self.config['height']))\n self.num_weights = 0\n self.num_bias = 0\n\n elif self.config['type'].lower() == 'batchnorm':\n self.output_size = self.src_layers[0].output_size\n self.kernel_size = None\n self.num_weights = 0\n self.num_bias = int(2 * self.src_layers[0].output_size[2])\n\n elif self.config['type'].lower() == 'residual':\n self.output_size = (int(min([item.output_size[0]\n for item in self.src_layers])),\n int(min([item.output_size[1]\n for item in self.src_layers])),\n int(max([item.output_size[2]\n for item in self.src_layers])))\n self.kernel_size = None\n self.num_weights = 0\n self.num_bias = 0\n\n elif self.config['type'].lower() == 'concat':\n self.output_size = (int(self.src_layers[0].output_size[0]),\n int(self.src_layers[0].output_size[1]),\n int(sum([item.output_size[2]\n for item in self.src_layers])))\n self.kernel_size = None\n self.num_weights = 0\n self.num_bias = 0\n\n elif self.config['type'].lower() in ('fc', 'fullconnect'):\n if isinstance(self.src_layers[0].output_size, int):\n num_features = self.src_layers[0].output_size\n else:\n num_features = prod_without_none(self.src_layers[0].output_size)\n self.output_size = int(self.config['n'])\n self.kernel_size = (int(num_features), int(self.config['n']))\n self.num_weights = int(num_features * self.config['n'])\n self.num_bias = int(self.config['n'])\n\n elif self.config['type'].lower() == 'output':\n self.type_name = 'Output'\n if isinstance(self.src_layers[0].output_size, int):\n num_features = self.src_layers[0].output_size\n else:\n num_features = prod_without_none(self.src_layers[0].output_size)\n\n if 'n' in self.config.keys():\n self.output_size = int(self.config['n'])\n self.kernel_size = (int(num_features), int(self.config['n']))\n self.num_weights = int(num_features * self.config['n'])\n self.num_bias = int(self.config['n'])\n else:\n self.kernel_size = None\n self.num_weights = None\n self.num_bias = None\n self.output_size = None\n\n name = '{}({})'.format(self.name, self.type_name)\n if len(name) > 17:\n col1 = '| {:<17}'.format('{}'.format(name[:14] + '...'))\n else:\n col1 = '| {:<17}'.format('{}'.format(name))\n\n col2 = '|{:^15}'.format('{}'.format(self.kernel_size))\n\n if 'stride' not in self.config.keys():\n col3 = '|{:^8}'.format('None')\n else:\n col3 = '|{:^8}'.format('{}'.format(int(self.config['stride'])))\n\n col4 = '|{:^12}'.format('{}'.format(self.activation))\n\n col5 = '|{:^17}'.format('{}'.format(self.output_size))\n\n num_paras = '{} / {}'.format(self.num_weights, self.num_bias)\n col6 = '|{:^22}|\\n'.format(num_paras)\n\n return col1 + col2 + col3 + col4 + col5 + col6\n\n\nclass InputLayer(Layer):\n '''\n Input layer\n \n Parameters\n ----------\n n_channels : int\n Specifies the number of channels of the input images.\n width : int\n Specifies the width of the input images.\n height : int\n Specifies the height of the input images.\n scale : double, between 0 and 1.\n Specifies the scaling parameter of the image.\n dropout : double, between 0 and 1\n Specifies the dropout rate.\n offsets : iter-of-doubles\n Specifies the offset values.\n name : str\n Specifies the name of the layer.\n src_layers : iter-of-Layers, optional\n Specifies the source layer(s).\n\n Returns\n -------\n :class:`InputLayer`\n\n '''\n\n def __init__(self, n_channels=3, width=224, height=224, scale=1,\n dropout=0, offsets=None, name=None, **kwargs):\n if offsets is None:\n offsets = [0] * n_channels\n config = locals()\n config = _unpack_config(config)\n config['type'] = 'input'\n Layer.__init__(self, name, config)\n self.color_code = '#F0FF00'\n self.type_name = 'Input'\n\n\nclass Conv2d(Layer):\n '''\n 2D convolutional layer\n\n Parameters\n ----------\n n_filters : int\n Specifies the number of filters.\n width : int\n Specifies the width of pooling window.\n height : int\n Specifies the height of pooling window.\n stride : int\n Specifies the step size of the moving window.\n act : str\n Specifies the activation types.\n dropout : double, between 0 and 1\n Specifies the dropout rate.\n name : str\n Specifies the name of the layer.\n src_layers : iter-of-Layers, optional\n Specifies the source layer(s).\n\n Returns\n -------\n :class:`Conv2d`\n\n '''\n\n def __init__(self, n_filters, width=None, height=None, stride=1,\n act='relu', dropout=0, name=None, src_layers=None, **kwargs):\n if (width is None) and (height is None):\n width = 3\n if width is None:\n width = height\n if height is None:\n height = width\n config = locals()\n config = _unpack_config(config)\n config['type'] = 'convo'\n Layer.__init__(self, name, config, src_layers)\n self.color_code = '#6CFF00'\n self.type_name = 'Convo.'\n\n\nclass Pooling(Layer):\n '''\n Pooling layer\n\n Parameters\n ----------\n width : int\n Specifies the width of pooling window.\n height : int\n Specifies the height of pooling window.\n stride : int\n Specifies the step size of the moving window.\n act : str\n Specifies the activation types.\n dropout : double, between 0 and 1\n Specifies the dropout rate.\n name : str\n Specifies the name of the layer.\n src_layers : iter-of-Layers, optional\n Specifies the source layer(s).\n\n Returns\n -------\n :class:`Pooling`\n\n '''\n\n def __init__(self, width=None, height=None, stride=None,\n pool='max', dropout=0, name=None, src_layers=None, **kwargs):\n if (width is None) and (height is None):\n width = 2\n if width is None:\n width = height\n if height is None:\n height = width\n if stride is None:\n stride = width\n config = locals()\n config = _unpack_config(config)\n config['type'] = 'pool'\n Layer.__init__(self, name, config, src_layers)\n self.activation = pool.title()\n self.color_code = '#FF9700'\n self.type_name = 'Pool'\n\n\nclass Dense(Layer):\n '''\n Fully connected layer\n\n Parameters\n ----------\n n : int\n Specifies the number of neurons.\n act : str\n Specifies the activation types.\n dropout : double, between 0 and 1\n Specifies the dropout rate.\n name : str\n Specifies the name of the layer.\n src_layers : iter-of-Layers, optional\n Specifies the source layer(s).\n\n Returns\n -------\n :class:`Dense`\n\n '''\n\n def __init__(self, n, act='relu', dropout=0,\n name=None, src_layers=None, **kwargs):\n config = locals()\n config = _unpack_config(config)\n config['type'] = 'fc'\n Layer.__init__(self, name, config, src_layers)\n self.color_code = '#00ECFF'\n self.type_name = 'F.C.'\n\n\nclass Recurrent(Layer):\n '''\n Recurrent layer\n\n Parameters\n ----------\n n : int\n Specifies the number of neurons.\n act : str\n Specifies the activation types.\n rnn_type : str\n Specifies the type of RNN gate.\n output_type : str\n Specifies the type of output neurons.\n reversed_ : bool\n Specifies whether to reverse the sequence.\n name : str\n Specifies the name of the layer.\n src_layers : iter-of-Layers, optional\n Specifies the source layer(s).\n\n Returns\n -------\n :class:`Recurrent`\n\n '''\n\n def __init__(self, n, act='AUTO', rnn_type='RNN', output_type='ENCODING',\n reversed_=False, name=None, src_layers=None, **kwargs):\n config = locals()\n config = _unpack_config(config)\n config['type'] = 'recurrent'\n Layer.__init__(self, name, config, src_layers)\n self.color_code = '#FFA4A4'\n self.type_name = 'Rec.'\n\n\nclass BN(Layer):\n '''\n Batch Normalization layer\n\n Parameters\n ----------\n act : str\n Specifies the activation types.\n name : str\n Specifies the name of the layer.\n src_layers : iter-of-Layers, optional\n Specifies the source layer(s).\n\n Returns\n -------\n :class:`BN`\n\n '''\n\n def __init__(self, act='AUTO', name=None, src_layers=None, **kwargs):\n config = locals()\n config = _unpack_config(config)\n config['type'] = 'batchnorm'\n Layer.__init__(self, name, config, src_layers)\n self.color_code = '#FFF999'\n self.type_name = 'B.N.'\n\n\nclass Res(Layer):\n '''\n Residual layer\n\n Parameters\n ----------\n act : str\n Specifies the activation types.\n name : str\n Specifies the name of the layer.\n src_layers : iter-of-Layers, optional.\n Specifies the source layer(s).\n\n Returns\n -------\n :class:`Res`\n\n '''\n\n def __init__(self, act='AUTO', name=None, src_layers=None, **kwargs):\n config = locals()\n config = _unpack_config(config)\n config['type'] = 'residual'\n Layer.__init__(self, name, config, src_layers)\n self.color_code = '#FF0000'\n self.type_name = 'Resid.'\n\n\nclass Concat(Layer):\n '''\n Concatenation layer\n\n Parameters\n ----------\n act : str\n Specifies the activation types.\n name : str\n Specifies the name of the layer.\n src_layers : iter-of-Layers, optional\n Specifies the source layer(s).\n\n Returns\n -------\n :class:`Concat`\n\n '''\n\n def __init__(self, act='AUTO', name=None, src_layers=None, **kwargs):\n config = locals()\n config = _unpack_config(config)\n config['type'] = 'concat'\n Layer.__init__(self, name, config, src_layers)\n self.color_code = '#DD5022'\n self.type_name = 'Concat.'\n\n\nclass Proj(Layer):\n '''\n Projection layer\n\n Parameters\n ----------\n name : str\n Specifies the name of the layer.\n src_layers : iter-of-Layers, optional\n Specifies the source layer(s).\n\n Returns\n -------\n :class:`Proj`\n\n '''\n\n def __init__(self, name=None, src_layers=None, **kwargs):\n config = locals()\n config = _unpack_config(config)\n config['type'] = 'projection'\n Layer.__init__(self, name, config, src_layers)\n self.color_code = '#FFA2A3'\n self.type_name = 'Proj.'\n\n\nclass OutputLayer(Layer):\n '''\n Output layer\n\n Parameters\n ----------\n n : int\n Specifies the number of output neurons.\n act : str\n Specifies the activation types.\n name : str\n Specifies the name of the layer.\n src_layers : iter-of-Layers, optional\n Specifies the source layer(s).\n\n Returns\n -------\n :class:`OutputLayer`\n \n '''\n\n def __init__(self, n=None, act='softmax', name=None, src_layers=None, **kwargs):\n config = locals()\n config = _unpack_config(config)\n config['type'] = 'output'\n if config['n'] is None:\n del config['n']\n Layer.__init__(self, name, config, src_layers)\n self.color_code = '#C8C8C8'\n self.type_name = 'Output.'\n\n\ndef _unpack_config(config):\n ''' Unpack the configuration from the keyword-argument-only input '''\n kwargs = config['kwargs']\n del config['self'], config['name'], config['kwargs']\n try:\n del config['src_layers']\n except:\n pass\n out = {}\n out.update(config)\n out.update(kwargs)\n for key in out:\n if '_' in key:\n new_key = key.replace('_', '')\n out[new_key] = out[key]\n out.pop(key)\n return out\n","sub_path":"dlpy/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":16548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"118440965","text":"import naoqi\nimport time\nimport almath\nimport math\n\nNIp = \"10.16.96.41\"\nPORT = 9559\n\nmotion = naoqi.ALProxy(\"ALMotion\", NIp, PORT)\nposture = naoqi.ALProxy(\"ALRobotPosture\", NIp, PORT)\ntts = naoqi.ALProxy(\"ALTextToSpeech\", NIp,PORT)\nmarkProxy = naoqi.ALProxy(\"ALLandMarkDetection\", NIp, PORT)\nanimatedMode = naoqi.ALProxy(\"ALAutonomousLife\", NIp, PORT)\n\nid = posture.goToPosture(\"Stand\", 1.)\n\ns = tts.post.say(\"I feel pretty!\")\nmotion.wait(s, 0)\nid = motion.post.moveTo(0, 0, math.pi / 2)\nmotion.wait(id, 0)\ns = tts.post.say(\"Does my ass look fat in this outfit?\")\nmotion.wait(s, 0)\nmotion.rest()\n\n","sub_path":"ifp.py","file_name":"ifp.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"415471063","text":"#\n# [3] Longest Substring Without Repeating Characters\n#\n# https://leetcode.com/problems/longest-substring-without-repeating-characters/description/\n#\n# algorithms\n# Medium (24.81%)\n# Total Accepted: 516.4K\n# Total Submissions: 2.1M\n# Testcase Example: '\"abcabcbb\"'\n#\n# Given a string, find the length of the longest substring without repeating\n# characters.\n# \n# Examples: \n# \n# Given \"abcabcbb\", the answer is \"abc\", which the length is 3.\n# \n# Given \"bbbbb\", the answer is \"b\", with the length of 1.\n# \n# Given \"pwwkew\", the answer is \"wke\", with the length of 3. Note that the\n# answer must be a substring, \"pwke\" is a subsequence and not a substring.\n#\nclass Solution:\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n l = 0 \n r = 0 \n dict = {}\n track = 0 \n while r < len(s): \n if s[r] not in dict.keys() or dict[s[r]] < l: \n dict[s[r]] = r \n track = max(r - l + 1, track) \n r = r + 1 \n else: \n l = dict[s[r]] + 1 \n dict[s[r]] = r\n track = max(r - l + 1, track) \n r = r + 1 \n return track \n","sub_path":"3.longest-substring-without-repeating-characters.python3.py","file_name":"3.longest-substring-without-repeating-characters.python3.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"399638731","text":"\"\"\"\n\nProgram: create_variant_seqs.py\n\nPurpose: Read in a variant table and a reference sequence, and use them to\n create a file of variant sequences.\n\nInputs: var_table_file (variant table)\n refseq_file (reference sequence file)\n out_file (output file)\n\nOutputs: csv file\n\nExecution: python3 create_variant_seqs.py \n \n\nNote: The variant table file is expected to be a .csv file with the following\n format:\n Column 1: variant name/label\n Column 2: sequence position\n Column 3: reference value\n Column 4: variant value\n\"\"\"\n\nimport argparse\nimport re\nfrom csv import reader\nfrom Bio import SeqIO\n\ndef main():\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"var_table_file\", type=str,\n help=\"Variant table file name\")\n parser.add_argument(\"refseq_file\", type=argparse.FileType(\"r\"),\n help=\"Reference sequence file name\")\n parser.add_argument(\"out_file\", type=argparse.FileType(\"w\"),\n help=\"Output file name\")\n\n args = parser.parse_args()\n\n changes_dict = {}\n inserts_dict = {}\n nonvar_insert_dict = {}\n seq_dict = {}\n\n # Read the variant table into a dictionary with the variant name/label as\n # the key, pointing to a list of variant locations and changes for each\n # variant. Make sure to skip the first row since it is the header row.\n with open(args.var_table_file, \"r\") as vt:\n file_lines = reader(vt)\n skip_header = next(file_lines)\n\n if skip_header is not None:\n for val_list in file_lines:\n line_dict = {}\n variant_name = val_list.pop(0)\n line_dict[\"variant_pos\"] = val_list.pop(0)\n line_dict[\"ref_val\"] = val_list.pop(0)\n line_dict[\"variant_val\"] = val_list.pop(0)\n\n if line_dict[\"ref_val\"] == \"+\":\n if variant_name not in inserts_dict:\n inserts_dict[variant_name] = []\n inserts_dict[variant_name].append(line_dict)\n if line_dict[\"variant_pos\"] not in nonvar_insert_dict:\n nonvar_insert_dict[line_dict[\"variant_pos\"]] = \"-\"\n else:\n line_dict[\"variant_pos\"] = int(line_dict[\"variant_pos\"])\n if variant_name not in changes_dict:\n changes_dict[variant_name] = []\n changes_dict[variant_name].append(line_dict)\n\n # Read in the reference sequence.\n ref_record = SeqIO.read(args.refseq_file, \"fasta\")\n ref_seq = str(ref_record.seq)\n seq_dict[ref_record.id] = list(ref_seq)\n\n # Process the changes (including deletions) first. Since Python is\n # 0-indexed, the position to be changed is one less than the position\n # listed for the variants in the file.\n for variant in changes_dict:\n seq_dict[variant] = list(ref_seq)\n for change_rec in changes_dict[variant]:\n seq_dict[variant][change_rec[\"variant_pos\"] - 1] = change_rec[\"variant_val\"]\n\n # Process the insertions. This is done as a separate step in order to\n # include the reference sequence in the processing.\n for seq in seq_dict:\n working_insert_dict = nonvar_insert_dict.copy()\n if seq in inserts_dict:\n for insert_rec in inserts_dict[seq]:\n working_insert_dict[insert_rec[\"variant_pos\"]] = insert_rec[\"variant_val\"]\n for insert_pos in sorted(working_insert_dict, reverse=True):\n int_pos = int(re.sub(\"[^\\d]\", \"\", insert_pos)) - 1\n seq_dict[seq].insert(int_pos, working_insert_dict[insert_pos])\n\n seq_dict[seq] = \"\".join(seq_dict[seq])\n args.out_file.write(f\">{seq}\\n\")\n args.out_file.write(f\"{seq_dict[seq]}\\n\")\n\n args.out_file.close()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"create_variant_seqs.py","file_name":"create_variant_seqs.py","file_ext":"py","file_size_in_byte":3941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"382595376","text":"\"\"\"\"\"\"\n\nimport importlib\nimport os\nimport traceback\nfrom collections import defaultdict\nfrom pathlib import Path\nfrom typing import Any, Callable\nfrom datetime import datetime, timedelta\nfrom threading import Thread\nfrom queue import Queue, Empty\nfrom copy import copy, deepcopy\nimport time\nimport psutil\nimport os\n\nfrom vnpy.event import Event, EventEngine\nfrom vnpy.trader.engine import BaseEngine, MainEngine\nfrom vnpy.trader.object import (\n OrderRequest,\n SubscribeRequest,\n HistoryRequest,\n LogData,\n TickData,\n BarData,\n ContractData\n)\nfrom vnpy.trader.event import (\n EVENT_TICK, \n EVENT_ORDER, \n EVENT_TRADE,\n EVENT_POSITION,\n EVENT_BAR,\n EVENT_ACCOUNT\n)\nfrom vnpy.trader.constant import (\n Direction, \n OrderType, \n Interval, \n Exchange, \n Offset, \n Status\n)\nfrom vnpy.trader.utility import load_json, save_json, extract_vt_symbol, round_to\nfrom vnpy.trader.database import database_manager\n# from vnpy.trader.rqdata import rqdata_client\n\nfrom .base import (\n APP_NAME,\n EVENT_CTA_LOG,\n EVENT_CTA_STRATEGY,\n EVENT_CTA_STOPORDER,\n EngineType,\n StopOrder,\n StopOrderStatus,\n STOPORDER_PREFIX\n)\nfrom .template import CtaTemplate\nfrom .converter import OffsetConverter\nfrom .DBMongo import dbMongo\n\nSTOP_STATUS_MAP = {\n Status.SUBMITTING: StopOrderStatus.WAITING,\n Status.NOTTRADED: StopOrderStatus.WAITING,\n Status.PARTTRADED: StopOrderStatus.TRIGGERED,\n Status.ALLTRADED: StopOrderStatus.TRIGGERED,\n Status.CANCELLED: StopOrderStatus.CANCELLED,\n Status.REJECTED: StopOrderStatus.CANCELLED\n}\n\n\nclass CtaEngine(BaseEngine):\n \"\"\"Cta引擎,提供Cta功能与主引擎的交互\"\"\"\n\n engine_type = EngineType.LIVE # live trading engine\n\n # 配置文件\n setting_filename = \"cta_strategy_setting.json\"\n data_filename = \"cta_strategy_data.json\"\n setting_dbname = \"cta_strategy_setting\"\n data_dbname = \"cta_strategy_data\"\n account_id = \"mytest\"\n\n def __init__(self, main_engine: MainEngine, event_engine: EventEngine):\n \"\"\"初始化,与其他模块一样,提供与主引擎交互的方法\"\"\"\n super(CtaEngine, self).__init__(\n main_engine, event_engine, APP_NAME)\n\n # 配置dict,数据dict\n self.strategy_setting = {} # strategy_name: dict\n self.strategy_data = {} # strategy_name: dict\n\n # 策略的类,策略名称\n self.classes = {} # class_name: stategy_class\n self.strategies = {} # strategy_name: strategy\n\n # 订阅的合约vt_symbol\n self.symbol_strategy_map = defaultdict(\n list) # vt_symbol: strategy list\n # 策略的order哪个orderid对应哪个strategy\n self.orderid_strategy_map = {} # vt_orderid: strategy\n # 策略名称对应orderid,一个策略对应多个id\n self.strategy_orderid_map = defaultdict(\n set) # strategy_name: orderid list\n\n # 停止单下单数量\n self.stop_order_count = 0 # for generating stop_orderid\n # 停止单id\n self.stop_orders = {} # stop_orderid: stop_order\n\n # 初始化线程\n self.init_thread = None\n # 初始化队列\n self.init_queue = Queue()\n\n self.rq_client = None\n self.rq_symbols = set()\n\n # 策略成交\n self.vt_tradeids = set() # for filtering duplicate trade\n\n # 转换\n self.offset_converter = OffsetConverter(self.main_engine)\n\n # 自主添加\n # DB 数据库\n self.db_mongo = dbMongo()\n self.db_thread = None\n self.db_queue = Queue()\n self.db_active = False\n self.db_count = 0\n\n def init_engine(self):\n \"\"\"\n 初始化引擎,初始化米匡\n 载入所有策略(类)\n 载入所有策略配置\n 载入所有策略数据\n 注册事件\n 引擎初始化\n \"\"\"\n # 开启策略线程\n self.db_start()\n \n # self.init_rqdata()\n self.load_strategy_class()\n self.load_strategy_setting()\n self.load_strategy_data()\n self.register_event()\n self.write_log(\"CTA策略引擎初始化成功\")\n\n def account_id_change(self, new_id):\n self.account_id = new_id\n\n def init_dbmongo(self, name=None, password=None, ip=\"localhost\", port=\"27017\"):\n self.db_name = name\n self.db_pwd = password\n self.db_mongo = dbMongo(name, password, ip, port)\n\n def close(self):\n \"\"\"\n 关闭所有策略\n \"\"\"\n self.stop_all_strategies()\n\n def register_event(self):\n \"\"\"注册事件,tick, order, trade, position, 少了一个account?\"\"\"\n self.event_engine.register(EVENT_TICK, self.process_tick_event)\n self.event_engine.register(EVENT_ORDER, self.process_order_event)\n self.event_engine.register(EVENT_TRADE, self.process_trade_event)\n self.event_engine.register(EVENT_POSITION, self.process_position_event)\n self.event_engine.register(EVENT_BAR, self.process_bar_event)\n self.event_engine.register(EVENT_ACCOUNT, self.process_account_event)\n\n def init_rqdata(self):\n \"\"\"\n Init RQData client.\n \"\"\"\n return\n\n def query_bar_from_rq(\n self, symbol: str, exchange: Exchange, interval: Interval, start: datetime, end: datetime\n ):\n \"\"\"\n Query bar data from RQData.\n \"\"\"\n return\n\n def process_tick_event(self, event: Event):\n \"\"\"处理tick事件,主要是向订阅了tick的策略推送\"\"\"\n tick = event.data\n\n strategies = self.symbol_strategy_map[tick.vt_symbol]\n if not strategies:\n return\n\n # 先根据tick检查本地停止单\n self.check_stop_order(tick)\n\n # 如果有策略,推送至策略的on_tick情况,由tick合成bar,进而由策略自己使用\n for strategy in strategies:\n if strategy.inited:\n self.call_strategy_func(strategy, strategy.on_tick, tick)\n\n def process_bar_event(self, event: Event):\n \"\"\"处理bar事件,主要是向订阅了bar的策略推送\"\"\"\n bar = deepcopy(event.data)\n\n strategies = self.symbol_strategy_map[bar.vt_symbol]\n if not strategies:\n return\n\n # Bar不检查停止单\n # self.check_stop_order(bar)\n\n # 如果有策略,推送至策略的on_bar情况,由分钟bar合成更大级别的bar,进而由策略自己使用\n for strategy in strategies:\n #if strategy.inited:\n # 日志记录时,要先显示发出,再由策略收到\n # self.write_log(\"engine process Bar_Data:\" + str(bar.__dict__), strategy)\n self.call_strategy_func(strategy, strategy.on_bar, bar)\n # =================================\n # 这里在测试的时候,写入数据库和log两种形式\n\n # 实盘中,只写入数据库中\n d = deepcopy(bar.__dict__)\n d[\"account_id\"] = self.account_id\n d[\"strategy_name\"] = strategy.strategy_name\n d[\"exchange\"] = d[\"exchange\"].value\n d[\"interval\"] = d[\"interval\"].value\n flt = {\n \"vt_symbol\": d[\"vt_symbol\"],\n \"interval\": d[\"interval\"],\n \"datetime\": d[\"datetime\"],\n }\n self.db_queue.put([\"update\", self.account_id, \"Bar_Data\", d, flt])\n\n # =================================\n\n def process_order_event(self, event: Event):\n \"\"\"处理order事件\"\"\"\n order = event.data\n d = deepcopy(order.__dict__)\n\n # 先转换order\n self.offset_converter.update_order(order)\n\n # 先根据订单号返回对应的策略\n strategy = self.orderid_strategy_map.get(order.vt_orderid, None)\n if not strategy:\n self.write_log(\"非程序化策略订单:\" + str(d))\n return\n\n # =================================\n # 这里在测试的时候,写入数据库和log两种形式\n\n # 实盘中,只写入数据库中\n d[\"account_id\"] = self.account_id\n d[\"strategy_name\"] = strategy.strategy_name\n d[\"exchange\"] = d[\"exchange\"].value\n d[\"type\"] = d[\"type\"].value\n d[\"direction\"] = d[\"direction\"].value\n d[\"offset\"] = d[\"offset\"].value\n d[\"status\"] = d[\"status\"].value\n\n flt = {\n \"vt_orderid\": d[\"vt_orderid\"],\n \"volume\": d[\"volume\"],\n \"status\": d[\"status\"],\n }\n self.db_queue.put([\"update\", self.account_id, \"Order_Data\", d, flt])\n\n self.write_log(\"Order_Data:\" + str(d), strategy)\n # =================================\n\n # Remove vt_orderid if order is no longer active.\n # 如果order_id已经成交了或者撤销了,删除这个订单。\n # 先返回所有这个策略的订单号\n vt_orderids = self.strategy_orderid_map[strategy.strategy_name]\n if order.vt_orderid in vt_orderids and not order.is_active():\n vt_orderids.remove(order.vt_orderid)\n\n # For server stop order, call strategy on_stop_order function\n # 如果是停止单,推送停止单到对应的策略中去\n if order.type == OrderType.STOP:\n so = StopOrder(\n vt_symbol=order.vt_symbol,\n direction=order.direction,\n offset=order.offset,\n price=order.price,\n volume=order.volume,\n stop_orderid=order.vt_orderid,\n strategy_name=strategy.strategy_name,\n status=STOP_STATUS_MAP[order.status],\n vt_orderids=[order.vt_orderid],\n )\n self.call_strategy_func(strategy, strategy.on_stop_order, so) \n\n # Call strategy on_order function\n # 最后,不管是停止单,还是删除编号的操作,最后都要调用策略的on_order操作\n self.call_strategy_func(strategy, strategy.on_order, order)\n\n def process_trade_event(self, event: Event):\n \"\"\"处理成交事件\"\"\"\n trade = event.data\n\n d = deepcopy(trade.__dict__)\n # Filter duplicate trade push\n # 如果推送过来的成交,不是此次运行期间的单子\n if trade.vt_tradeid in self.vt_tradeids:\n return\n # 将成交的订单添加至vt_tradeids 添加至本引擎中去\n self.vt_tradeids.add(trade.vt_tradeid)\n\n # 转换成交\n self.offset_converter.update_trade(trade)\n\n # 获取这个成交对应的策略\n strategy = self.orderid_strategy_map.get(trade.vt_orderid, None)\n if not strategy:\n self.write_log(\"非程序化策略成交:\" + str(d))\n return\n\n # =================================\n # 这里在测试的时候,写入数据库和log两种形式\n\n # 实盘中,只写入数据库中\n d[\"account_id\"] = self.account_id\n d[\"strategy_name\"] = strategy.strategy_name\n\n d[\"exchange\"] = d[\"exchange\"].value\n d[\"direction\"] = d[\"direction\"].value\n d[\"offset\"] = d[\"offset\"].value\n\n flt = {\n \"vt_orderid\": d[\"vt_orderid\"],\n \"vt_tradeid\": d[\"vt_tradeid\"],\n }\n self.db_queue.put([\"update\", self.account_id, \"Trade_Data\", d, flt])\n\n self.write_log(\"Trade_Data:\" + str(d), strategy)\n # =================================\n\n # 如果是多单,计算持仓时符号为正,如果是空单,计算持仓时符号为负\n if trade.direction == Direction.LONG:\n strategy.pos += trade.volume\n else:\n strategy.pos -= trade.volume\n\n # 仓位variable每次更新完都要在本地更新\n self.sync_strategy_data(strategy)\n\n # 调用策略函数\n self.call_strategy_func(strategy, strategy.on_trade, trade)\n # 发送策略事件,也就是策略有任何一项改变,就要发出,这个在double_ma_strategy内中\n # on_start on_bar on_init on_stop中,只要策略发生一些东西的变化,就触发put_strategy_event这个函数\n self.put_strategy_event(strategy)\n\n def process_position_event(self, event: Event):\n \"\"\"处理仓位 事件\"\"\"\n position = event.data\n\n d = deepcopy(position.__dict__)\n\n # 就是把他转换,然后更新,就好了\n self.offset_converter.update_position(position)\n\n # =================================\n # 这里在测试的时候,写入数据库和log两种形式\n\n # 实盘中,只写入数据库中\n d[\"account_id\"] = self.account_id\n d[\"exchange\"] = d[\"exchange\"].value\n d[\"direction\"] = d[\"direction\"].value\n d[\"datetime\"] = copy(datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%fZ\"))\n if d[\"volume\"] > 0:\n self.db_queue.put([\"insert\", self.account_id, \"Position_Data\", d])\n\n self.write_log(\"Position_Data:\" + str(d))\n # =================================\n\n def process_account_event(self, event: Event):\n \"\"\"处理账户 事件\"\"\"\n account = event.data\n\n d = deepcopy(account.__dict__)\n\n # =================================\n # 这里在测试的时候,写入数据库和log两种形式\n\n # 实盘中,只写入数据库中\n d[\"account_id\"] = self.account_id\n d[\"datetime\"] = copy(datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%fZ\"))\n if d[\"balance\"] > 0:\n self.db_queue.put([\"insert\", self.account_id, \"Account_Data\", d])\n\n self.write_log(\"Account_Data:\" + str(d))\n # =================================\n\n def check_stop_order(self, tick: TickData):\n \"\"\"检查停止单,每次收到tick的时候都要检查\"\"\"\n # 对于所有的当前停止单\n for stop_order in list(self.stop_orders.values()):\n # 如果停止单的vt_symbol与tick不同\n if stop_order.vt_symbol != tick.vt_symbol:\n # 进行下一个循环\n continue\n # 为了保证下单,要查看tick内涨停价和5档价格,如果都没有,返回\n if not tick.limit_up and not tick.bid_price_5:\n continue\n\n # 多头停止单,tick价格上穿止损价\n # 如果是buy的LONG + OPEN 的STOPORDER,当价格向上突破某一个价格的时候开仓\n # 如果是cover的LONG + CLOSE 的STOPORDER,当价格向上突破某一个价格的时候平仓,意思是止损\n long_triggered = (\n stop_order.direction == Direction.LONG and tick.last_price >= stop_order.price\n )\n # 空头停止单,tick价格下穿止损价\n # 如果是short的SHORT + OPEN 的STOPORDER,当价格向下突破某一个价格的时候开仓\n # 如果是sell的SHORT + CLOSE 的STOPORDER,当价格向下突破某一个价格的时候平仓,意思是止损\n short_triggered = (\n stop_order.direction == Direction.SHORT and tick.last_price <= stop_order.price\n )\n\n # 如果有触发条件的话\n if long_triggered or short_triggered:\n # 是哪个策略的停止单\n strategy = self.strategies[stop_order.strategy_name]\n\n # To get excuted immediately after stop order is\n # triggered, use limit price if available, otherwise\n # use ask_price_5 or bid_price_5\n # 停止单的下一步处理,如果有涨跌停,按涨跌停下单,如果没有涨跌停,按买五卖五价格下单\n if stop_order.direction == Direction.LONG:\n if tick.limit_up:\n price = tick.limit_up\n else:\n price = tick.ask_price_5\n else:\n if tick.limit_down:\n price = tick.limit_down\n else:\n price = tick.bid_price_5\n\n # 获取主引擎中对应的合约,包括交易所和代码\n contract = self.main_engine.get_contract(stop_order.vt_symbol)\n\n # stoporder的本质也是转换stop_order->limit_order\n vt_orderids = self.send_limit_order(\n strategy, \n contract,\n stop_order.direction, \n stop_order.offset, \n price, \n stop_order.volume,\n stop_order.lock\n )\n\n # 正常发单,会返回order_ids\n # Update stop order status if placed successfully\n if vt_orderids:\n # Remove from relation map.\n # 如果下的本地单被以限价单的形式取代了,就删掉本地停止单\n self.stop_orders.pop(stop_order.stop_orderid)\n\n # 获取下单的策略order_id\n strategy_vt_orderids = self.strategy_orderid_map[strategy.strategy_name]\n if stop_order.stop_orderid in strategy_vt_orderids:\n strategy_vt_orderids.remove(stop_order.stop_orderid)\n\n # Change stop order status to cancelled and update to strategy.\n # 改变此下单的状态,变成已触发\n stop_order.status = StopOrderStatus.TRIGGERED\n stop_order.vt_orderids = vt_orderids\n\n # 调用on_stop_order\n self.call_strategy_func(\n strategy, strategy.on_stop_order, stop_order\n )\n self.put_stop_order_event(stop_order)\n\n def send_server_order(\n self,\n strategy: CtaTemplate,\n contract: ContractData,\n direction: Direction,\n offset: Offset,\n price: float,\n volume: float,\n type: OrderType,\n lock: bool\n ):\n \"\"\"\n Send a new order to server.\n 服务器发单,有些服务器支持 云止损单 有些不支持 支持的就可以用这个\n \"\"\"\n # Create request and send order.\n original_req = OrderRequest(\n symbol=contract.symbol,\n exchange=contract.exchange,\n direction=direction,\n offset=offset,\n type=type,\n price=price,\n volume=volume,\n )\n\n # Convert with offset converter\n req_list = self.offset_converter.convert_order_request(original_req, lock)\n\n # Send Orders\n vt_orderids = []\n\n for req in req_list:\n vt_orderid = self.main_engine.send_order(\n req, contract.gateway_name)\n vt_orderids.append(vt_orderid)\n\n self.offset_converter.update_order_request(req, vt_orderid)\n \n # Save relationship between orderid and strategy.\n self.orderid_strategy_map[vt_orderid] = strategy\n self.strategy_orderid_map[strategy.strategy_name].add(vt_orderid)\n\n return vt_orderids\n \n def send_limit_order(\n self,\n strategy: CtaTemplate,\n contract: ContractData,\n direction: Direction,\n offset: Offset,\n price: float,\n volume: float,\n lock: bool\n ):\n \"\"\"\n Send a limit order to server.\n 限价单永远可以向服务器发送\n \"\"\"\n return self.send_server_order(\n strategy,\n contract,\n direction,\n offset,\n price,\n volume,\n OrderType.LIMIT,\n lock\n )\n \n def send_server_stop_order(\n self,\n strategy: CtaTemplate,\n contract: ContractData,\n direction: Direction,\n offset: Offset,\n price: float,\n volume: float,\n lock: bool\n ):\n \"\"\"\n Send a stop order to server.\n \n Should only be used if stop order supported \n on the trading server.\n 向服务器发送停止单,需要服务器支持\n \"\"\"\n return self.send_server_order(\n strategy,\n contract,\n direction,\n offset,\n price,\n volume,\n OrderType.STOP,\n lock\n )\n\n def send_local_stop_order(\n self,\n strategy: CtaTemplate,\n direction: Direction,\n offset: Offset,\n price: float,\n volume: float,\n lock: bool\n ):\n \"\"\"\n Create a new local stop order.\n 创建一个本地停止单,服务器不支持的时候用\n \"\"\"\n self.stop_order_count += 1\n stop_orderid = f\"{STOPORDER_PREFIX}.{self.stop_order_count}\"\n\n stop_order = StopOrder(\n vt_symbol=strategy.vt_symbol,\n direction=direction,\n offset=offset,\n price=price,\n volume=volume,\n stop_orderid=stop_orderid,\n strategy_name=strategy.strategy_name,\n lock=lock\n )\n\n self.stop_orders[stop_orderid] = stop_order\n\n vt_orderids = self.strategy_orderid_map[strategy.strategy_name]\n vt_orderids.add(stop_orderid)\n\n self.call_strategy_func(strategy, strategy.on_stop_order, stop_order)\n self.put_stop_order_event(stop_order)\n\n return stop_orderid\n\n def cancel_server_order(self, strategy: CtaTemplate, vt_orderid: str):\n \"\"\"\n Cancel existing order by vt_orderid.\n 撤单,取消服务器的单子\n \"\"\"\n order = self.main_engine.get_order(vt_orderid)\n if not order:\n self.write_log(f\"撤单失败,找不到委托{vt_orderid}\", strategy)\n return\n\n req = order.create_cancel_request()\n self.main_engine.cancel_order(req, order.gateway_name)\n\n def cancel_local_stop_order(self, strategy: CtaTemplate, stop_orderid: str):\n \"\"\"\n Cancel a local stop order.\n 撤销本地停止单\n \"\"\"\n stop_order = self.stop_orders.get(stop_orderid, None)\n if not stop_order:\n return\n strategy = self.strategies[stop_order.strategy_name]\n\n # Remove from relation map.\n self.stop_orders.pop(stop_orderid)\n\n vt_orderids = self.strategy_orderid_map[strategy.strategy_name]\n if stop_orderid in vt_orderids:\n vt_orderids.remove(stop_orderid)\n\n # Change stop order status to cancelled and update to strategy.\n stop_order.status = StopOrderStatus.CANCELLED\n\n self.call_strategy_func(strategy, strategy.on_stop_order, stop_order)\n self.put_stop_order_event(stop_order)\n\n def send_order(\n self,\n strategy: CtaTemplate,\n direction: Direction,\n offset: Offset,\n price: float,\n volume: float,\n stop: bool,\n lock: bool\n ):\n \"\"\"\n cta的下单\n \"\"\"\n contract = self.main_engine.get_contract(strategy.vt_symbol)\n if not contract:\n self.write_log(f\"委托失败,找不到合约:{strategy.vt_symbol}\", strategy)\n return \"\"\n \n # Round order price and volume to nearest incremental value\n # 价格,首先要对价格处理,变成可下单的价格,最小变动要保持一致\n price = round_to(price, contract.pricetick)\n volume = round_to(volume, contract.min_volume)\n\n # 如果是停止单\n if stop:\n # 如果服务器支持,发服务器的单子,从这里可以看出,如果是支持服务器停止单的,要写在查询合约的回调函数内\n if contract.stop_supported:\n return self.send_server_stop_order(strategy, contract, direction, offset, price, volume, lock)\n # 如果服务器不支持,发本地的单子\n else:\n return self.send_local_stop_order(strategy, direction, offset, price, volume, lock)\n else:\n # 如果不是停止单,就是限价单\n return self.send_limit_order(strategy, contract, direction, offset, price, volume, lock)\n\n def cancel_order(self, strategy: CtaTemplate, vt_orderid: str):\n \"\"\"\n 取消下单\n 取消本地停止单\n 取消服务器停止单\n \"\"\"\n if vt_orderid.startswith(STOPORDER_PREFIX):\n self.cancel_local_stop_order(strategy, vt_orderid)\n else:\n self.cancel_server_order(strategy, vt_orderid)\n\n def cancel_all(self, strategy: CtaTemplate):\n \"\"\"\n Cancel all active orders of a strategy.\n 一键取消所有的当前订单\n \"\"\"\n vt_orderids = self.strategy_orderid_map[strategy.strategy_name]\n if not vt_orderids:\n return\n\n for vt_orderid in copy(vt_orderids):\n self.cancel_order(strategy, vt_orderid)\n\n def get_engine_type(self):\n \"\"\"获取引擎模式,默认实盘模式\"\"\"\n return self.engine_type\n\n def load_bar(self, vt_symbol: str, days: int, interval: Interval, callback: Callable[[BarData], None]):\n \"\"\"载入历史bar\"\"\"\n symbol, exchange = extract_vt_symbol(vt_symbol)\n end = datetime.now()\n start = end - timedelta(days)\n\n # Query bars from RQData by default, if not found, load from database.\n # TODO\n # 这里CTA的载入历史数据是从米匡那里拿,这个必须修改,没有米匡账号!\n # 初步建议修改为在主引擎中发送query_history拿数据,由gateway回调数据\n # OKEX的历史数据由OKEX提供,FUTURES的历史数据由数据库提供,每个都不一样,因此,不能在这里统一,要改成在gaetway中分发\n bars = self.query_bar_from_rq(symbol, exchange, interval, start, end)\n if not bars:\n bars = database_manager.load_bar_data(\n symbol=symbol,\n exchange=exchange,\n interval=interval,\n start=start,\n end=end,\n )\n\n for bar in bars:\n callback(bar)\n\n def load_tick(self, vt_symbol: str, days: int, callback: Callable[[TickData], None]):\n \"\"\"同上\"\"\"\n symbol, exchange = extract_vt_symbol(vt_symbol)\n end = datetime.now()\n start = end - timedelta(days)\n\n ticks = database_manager.load_tick_data(\n symbol=symbol,\n exchange=exchange,\n start=start,\n end=end,\n )\n\n for tick in ticks:\n callback(tick)\n\n def call_strategy_func(self, strategy: CtaTemplate, func: Callable, params: Any = None):\n \"\"\"\n Call function of a strategy and catch any exception raised.\n 调用策略的函数,基本输入有:\n CtaTemplate,也就是每个策略实例,或者说策略模板\n Callable,回调函数,比如策略的strategy.on_tick或者strategy.on_order\n params,也就是Callable的参数,有些需要回调的参数,on_tick可以给tick on_order可以给order\n \"\"\"\n try:\n if params:\n func(params)\n else:\n func()\n except Exception:\n strategy.trading = False\n strategy.inited = False\n\n msg = f\"触发异常已停止\\n{traceback.format_exc()}\"\n self.write_log(msg, strategy)\n\n def add_strategy(self, class_name: str, strategy_name: str, vt_symbol: str, setting: dict):\n \"\"\"\n Add a new strategy.\n 添加一个策略,\n class_name,策略类的名称DoubleMaStrategy,这个是模板\n strategy_name,这个是实例名称,每个实例不同的名字,一个策略两个参数,就是不同的实例\n vt_symbol,这个是实例的品种\n \"\"\"\n if strategy_name in self.strategies:\n self.write_log(f\"创建策略失败,存在重名{strategy_name}\")\n return\n\n # 策略类,模板的意思CtaTemplate\n strategy_class = self.classes[class_name]\n\n # 创建策略,本地保存,用唯一的策略名称来保存\n # 创建一个策略,用一个具体实例,一个策略名称,vt_symbol,setting来创建\n # setting更新的是params也就是策略参数,不是策略的variables\n # 初始化的时候,就添加策略的params\n strategy = strategy_class(self, strategy_name, vt_symbol, setting)\n self.strategies[strategy_name] = strategy\n\n # 创建策略需要的vt_symbol,用来做字典\n # Add vt_symbol to strategy map.\n strategies = self.symbol_strategy_map[vt_symbol]\n strategies.append(strategy)\n\n # Update to setting file.\n # 更新策略配置\n # 添加classname进setting和vt_symbol\n self.update_strategy_setting(strategy_name, setting)\n\n # 加入策略事件\n self.put_strategy_event(strategy)\n\n def init_strategy(self, strategy_name: str):\n \"\"\"\n Init a strategy.\n \"\"\"\n # 初始化策略,写成队列的形式,防止初始化时,同一时间初始化太多的策略\n self.init_queue.put(strategy_name)\n\n # 如果没有开启线程,开启线程\n if not self.init_thread:\n self.init_thread = Thread(target=self._init_strategy)\n self.init_thread.start()\n\n def _init_strategy(self):\n \"\"\"\n Init strategies in queue.\n \"\"\"\n # 初始化策略的内部接口,对外不暴露\n while not self.init_queue.empty():\n strategy_name = self.init_queue.get()\n strategy = self.strategies[strategy_name]\n\n if strategy.inited:\n self.write_log(f\"{strategy_name}已经完成初始化,禁止重复操作\")\n continue\n\n # 设置策略初始化为真,如果此处不开始,则query_history数据回调用不了\n # strategy.inited = True\n\n self.write_log(f\"{strategy_name}开始执行初始化\")\n\n # Call on_init function of strategy\n # 对每个策略调用回调函数on_init\n #self.call_strategy_func(strategy, strategy.on_init)\n #self.write_log(\"engine start flag\")\n\n # Restore strategy data(variables)\n # 策略数据,获取策略数据\n # 这里的data指的是策略的variables\n\n data = self.strategy_data.get(strategy_name, None)\n if data:\n # 策略的variables\n for name in strategy.variables:\n value = data.get(name, None)\n if value:\n # 设置策略,名称,值 = strategy.name = value\n setattr(strategy, name, value)\n\n self.call_strategy_func(strategy, strategy.on_init)\n\n # Subscribe market data\n # 初始化,订阅合约\n # 由于OKEX Futures的本地机制,所有的订阅,不在这里写,在gateway里面写\n\n \"\"\"\n contract = self.main_engine.get_contract(strategy.vt_symbol)\n if contract:\n req = SubscribeRequest(\n symbol=contract.symbol, exchange=contract.exchange)\n self.main_engine.subscribe(req, contract.gateway_name)\n else:\n self.write_log(f\"行情订阅失败,找不到合约{strategy.vt_symbol}\", strategy)\n \"\"\"\n\n # Put event to update init completed status.\n # 设置策略初始化为真\n strategy.inited = True\n\n self.put_strategy_event(strategy)\n self.write_log(f\"{strategy_name}初始化完成\")\n\n # 由于初始化时间较长,因此每个设置完成之后,都要把线程关闭,以免浪费内存资源,否则策略加载过多,造成资源浪费\n self.init_thread = None\n\n def start_strategy(self, strategy_name: str):\n \"\"\"\n Start a strategy.\n 开始运行策略\n \"\"\"\n # 运行策略\n strategy = self.strategies[strategy_name]\n # 如果策略还没有启动,先启动初始化\n if not strategy.inited:\n self.write_log(f\"策略{strategy.strategy_name}启动失败,请先初始化\")\n print(f\"策略{strategy.strategy_name}启动失败,请先初始化\" + str(strategy.__dict__))\n return\n\n # 如果策略已经在运行,无需重复启动\n if strategy.trading:\n self.write_log(f\"{strategy_name}已经启动,请勿重复操作\")\n return\n\n # 开启策略\n self.call_strategy_func(strategy, strategy.on_start)\n strategy.trading = True\n\n # 发送策略事件\n self.put_strategy_event(strategy)\n\n def stop_strategy(self, strategy_name: str):\n \"\"\"\n Stop a strategy.\n 停止策略\n \"\"\"\n # 读取策略\n strategy = self.strategies[strategy_name]\n if not strategy.trading:\n return\n\n # Call on_stop function of the strategy\n # 调用on_stop策略\n self.call_strategy_func(strategy, strategy.on_stop)\n\n # Change trading status of strategy to False\n # 先关闭策略开启状态\n strategy.trading = False\n\n # Cancel all orders of the strategy\n # 取消所有的订单\n self.cancel_all(strategy)\n\n # Update GUI\n # 向UI内发送事件\n self.put_strategy_event(strategy)\n\n def edit_strategy(self, strategy_name: str, setting: dict):\n \"\"\"\n Edit parameters of a strategy.\n 编辑策略,也就是策略配置更新,一般用不到,除非策略停止\n \"\"\"\n strategy = self.strategies[strategy_name]\n strategy.update_setting(setting)\n\n self.update_strategy_setting(strategy_name, setting)\n self.put_strategy_event(strategy)\n\n def remove_strategy(self, strategy_name: str):\n \"\"\"\n Remove a strategy.\n 移除一个策略\n \"\"\"\n strategy = self.strategies[strategy_name]\n # 移除前先停止,否则报错\n if strategy.trading:\n self.write_log(f\"策略{strategy.strategy_name}移除失败,请先停止\")\n return\n\n # Remove setting\n # 移除配置\n self.remove_strategy_setting(strategy_name)\n\n # Remove from symbol strategy map\n # 从策略字典里面移除\n strategies = self.symbol_strategy_map[strategy.vt_symbol]\n strategies.remove(strategy)\n\n # 从活动里面移除\n # Remove from active orderid map\n if strategy_name in self.strategy_orderid_map:\n vt_orderids = self.strategy_orderid_map.pop(strategy_name)\n\n # Remove vt_orderid strategy map\n for vt_orderid in vt_orderids:\n if vt_orderid in self.orderid_strategy_map:\n self.orderid_strategy_map.pop(vt_orderid)\n\n # Remove from strategies\n self.strategies.pop(strategy_name)\n\n return True\n\n def load_strategy_class(self):\n \"\"\"\n Load strategy class from source code.\n 动态载入策���类,可以从两个地方载入:\n\n \"\"\"\n # 这里提供两个路径,实盘中,可以存在一个路径,也可以存在另一个路径,都可以\n path1 = Path(__file__).parent.joinpath(\"strategies\")\n self.load_strategy_class_from_folder(\n path1, \"vnpy.app.cta_strategy.strategies\")\n\n path2 = Path.cwd().joinpath(\"strategies\")\n self.load_strategy_class_from_folder(path2, \"strategies\")\n\n def load_strategy_class_from_folder(self, path: Path, module_name: str = \"\"):\n \"\"\"\n Load strategy class from certain folder.\n 从文件夹载入策略\n 所有带.py结尾的都是正常策略\n \"\"\"\n # dirpath是文件的路径,dirnames不知道,filenames是文件内所有的策略名称\n for dirpath, dirnames, filenames in os.walk(str(path)):\n # 要提取的是策略\n for filename in filenames:\n # 如果以.py为结尾,这里有个问题,就是__init__.py也是以这个为结尾,不严谨,尽管在下面的过程中排除掉\n if filename.endswith(\".py\"):\n # 策略名称,也就是.py的文件名称\n strategy_module_name = \".\".join(\n [module_name, filename.replace(\".py\", \"\")])\n self.load_strategy_class_from_module(strategy_module_name)\n\n def load_strategy_class_from_module(self, module_name: str):\n \"\"\"\n Load strategy class from module file.\n 从模块中载入策略,主要为improtlib模块的本地实现\n \"\"\"\n try:\n module = importlib.import_module(module_name)\n\n # 取这个模块内的所有东西\n for name in dir(module):\n # 获取模块的值\n value = getattr(module, name)\n # 1.是个type类型\n # 2.是CtaTemplate的子类\n # 3.不是CtaTemplate\n if (isinstance(value, type) and\n issubclass(value, CtaTemplate) and\n value is not CtaTemplate):\n # 每个值得名称就是他本身,比如AtrRsiStrategy\n self.classes[value.__name__] = value\n except: # noqa\n msg = f\"策略文件{module_name}加载失败,触发异常:\\n{traceback.format_exc()}\"\n self.write_log(msg)\n\n def load_strategy_data(self):\n \"\"\"\n Load strategy data from json file.\n 策略数据,策略的数据指的是什么,如果\n \"\"\"\n results = self.db_mongo.dbQuery(self.account_id, self.data_dbname, {})\n for result in results:\n self.strategy_data[result[\"strategy_name\"]] = result[\"data\"]\n # self.strategy_data = load_json(self.data_filename)\n\n def sync_strategy_data(self, strategy: CtaTemplate):\n \"\"\"\n Sync strategy data into json file.\n 同步策略数据到本地,I/O操作,要小心一点,每个成交都要修改\n \"\"\"\n data = strategy.get_variables()\n data.pop(\"inited\") # Strategy status (inited, trading) should not be synced.\n data.pop(\"trading\")\n\n self.strategy_data[strategy.strategy_name] = data\n d = {\n \"strategy_name\": strategy.strategy_name,\n \"data\": data,\n }\n flt = {\"strategy_name\": strategy.strategy_name}\n self.db_queue.put([\"update\", self.account_id, self.data_dbname, d, flt, True])\n\n #save_json(self.data_filename, self.strategy_data)\n\n def get_all_strategy_class_names(self):\n \"\"\"\n Return names of strategy classes loaded.\n 获取所有策略的类名\n \"\"\"\n return list(self.classes.keys())\n\n def get_strategy_class_parameters(self, class_name: str):\n \"\"\"\n Get default parameters of a strategy class.\n 获取所有策略的参数类\n \"\"\"\n strategy_class = self.classes[class_name]\n\n parameters = {}\n for name in strategy_class.parameters:\n parameters[name] = getattr(strategy_class, name)\n\n return parameters\n\n def get_strategy_parameters(self, strategy_name):\n \"\"\"\n Get parameters of a strategy.\n 获取策略参数\n \"\"\"\n strategy = self.strategies[strategy_name]\n return strategy.get_parameters()\n\n def init_all_strategies(self):\n \"\"\"\n 初始化所有策略\n \"\"\"\n for strategy_name in self.strategies.keys():\n self.init_strategy(strategy_name)\n\n def start_all_strategies(self):\n \"\"\"\n 启动所有策略\n \"\"\"\n for strategy_name in self.strategies.keys():\n self.start_strategy(strategy_name)\n\n def stop_all_strategies(self):\n \"\"\"\n 停止所有策略\n \"\"\"\n for strategy_name in self.strategies.keys():\n self.stop_strategy(strategy_name)\n\n def load_strategy_setting(self):\n \"\"\"\n Load setting file.\n 载入策略配置文件\n 这里修改很大,变成与数据库交互\n \"\"\"\n results = self.db_mongo.dbQuery(self.account_id, self.setting_dbname, {})\n for result in results:\n self.add_strategy(\n result[\"class_name\"],\n result[\"strategy_name\"],\n result[\"vt_symbol\"],\n result[\"setting\"]\n )\n\n \"\"\"\n self.strategy_setting = load_json(self.setting_filename)\n\n # 策略配置文件,由于策略名称统一,因此策略配置统一\n for strategy_name, strategy_config in self.strategy_setting.items():\n # 添加策略\n # 策略名称唯一\n # 添加类名称\n # 添加vt_symbol\n # 添加setting配置\n self.add_strategy(\n strategy_config[\"class_name\"], \n strategy_name,\n strategy_config[\"vt_symbol\"], \n strategy_config[\"setting\"]\n )\n \"\"\"\n\n def update_strategy_setting(self, strategy_name: str, setting: dict):\n \"\"\"\n Update setting file.\n 更新策略配置到本地\n \"\"\"\n strategy = self.strategies[strategy_name]\n\n self.strategy_setting[strategy_name] = {\n \"class_name\": strategy.__class__.__name__,\n \"vt_symbol\": strategy.vt_symbol,\n \"setting\": setting,\n }\n d = {\n \"strategy_name\": strategy_name,\n \"class_name\": strategy.__class__.__name__,\n \"vt_symbol\": strategy.vt_symbol,\n \"setting\": setting,\n }\n flt = {\n \"strategy_name\": strategy_name,\n \"class_name\": strategy.__class__.__name__,\n }\n self.db_queue.put([\"update\", self.account_id, self.setting_dbname, d, flt, True])\n # self.db_mongo.dbUpdate(self.account_id, self.setting_dbname, d, flt, True)\n \"\"\"\n # 更新完策略配置之后,要save_json到配置文件内\n save_json(self.setting_filename, self.strategy_setting)\n \"\"\"\n\n def remove_strategy_setting(self, strategy_name: str):\n \"\"\"\n Remove setting file.\n 移除策略配置\n \"\"\"\n if strategy_name not in self.strategy_setting:\n return\n\n # 删除策略配置,同样也需要save_json\n self.strategy_setting.pop(strategy_name)\n flt = {\n \"strategy_name\": strategy_name\n }\n self.db_mongo.dbDelete(self.account_id, self.setting_dbname, flt)\n\n \"\"\"\n #save_json(self.setting_filename, self.strategy_setting)\n \"\"\"\n\n def put_stop_order_event(self, stop_order: StopOrder):\n \"\"\"\n Put an event to update stop order status.\n \"\"\"\n # 发送停止单事件\n event = Event(EVENT_CTA_STOPORDER, stop_order)\n self.event_engine.put(event)\n\n def put_strategy_event(self, strategy: CtaTemplate):\n \"\"\"\n Put an event to update strategy status.\n \"\"\"\n # 发送策略事件\n data = strategy.get_data()\n event = Event(EVENT_CTA_STRATEGY, data)\n self.event_engine.put(event)\n\n def write_log(self, msg: str, strategy: CtaTemplate = None):\n \"\"\"\n Create cta engine log event.\n \"\"\"\n if strategy:\n msg = f\"{strategy.strategy_name} -> {msg}\"\n d = {\n \"datetime\": datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\"),\n \"gateway_name\": \"CtaStrategy\",\n \"msg\": msg\n }\n self.db_queue.put([\"insert\", self.account_id, \"Log\", d])\n \"\"\"\n log = LogData(msg=msg, gateway_name=\"CtaStrategy\")\n event = Event(type=EVENT_CTA_LOG, data=log)\n # 写日志\n self.event_engine.put(event)\n \"\"\"\n\n def send_email(self, msg: str, strategy: CtaTemplate = None):\n \"\"\"\n Send email to default receiver.\n 发送Email\n \"\"\"\n if strategy:\n subject = f\"{strategy.strategy_name}\"\n else:\n subject = \"CTA策略引擎\"\n\n self.main_engine.send_email(subject, msg)\n\n def db_start(self):\n \"\"\"开启DB的线程\"\"\"\n self.db_active = True\n self.db_thread = Thread(target=self.db_run)\n self.db_thread.start()\n\n def db_stop(self):\n self.db_active = False\n\n def db_run(self):\n \"\"\"数据库线程的运行\"\"\"\n while self.db_active:\n try:\n task = self.db_queue.get(timeout=1)\n if task[0] == \"update\":\n dbName = task[1]\n collectionName = task[2]\n d = task[3]\n flt = task[4]\n self.db_mongo.dbUpdate(dbName, collectionName, d, flt, True)\n elif task[0] == \"insert\":\n dbName = task[1]\n collectionName = task[2]\n d = task[3]\n self.db_mongo.dbInsert(dbName, collectionName, d)\n # task_type, data = task\n\n except Empty:\n self.db_count += 1\n # 设定每隔一小时左右\n if self.db_count >= 3600:\n while True:\n try:\n info = psutil.virtual_memory()\n self.write_log('重启内存使用:' + str(psutil.Process(os.getpid()).memory_info().rss))\n self.write_log('重启总内存:' + str(info.total))\n self.write_log('重启内存占比:' + str(info.percent))\n self.write_log('重启cpu个数:' + str(psutil.cpu_count()))\n self.write_log(\"数据库开始重启!!!\")\n # 先将run关闭\n self.db_active = False\n # 正常关闭Mongodb的连接\n self.db_mongo.dbClient.close()\n self.db_mongo = None\n # 重新开启dbMongo()\n self.db_mongo = dbMongo(self.db_name, self.db_pwd)\n # 重新开启run\n self.db_active = True\n self.write_log(\"数据库重启成功!!!\")\n self.db_count = 0\n break\n except Exception as e:\n self.write_log(\"数据库问题\" + str(e))\n except Exception as e:\n self.write_log(str(e))\n\n\n\n","sub_path":"vnpy/app/cta_strategy/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":46800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"158445023","text":"import glob\nimport sys\nimport os\nimport gzip\nimport argparse\nfrom tqdm import tqdm\nimport pandas as pd\n#from format import peek\nfrom . import peek\n#from format.utils import *\nfrom .utils import *\n\nextra_formatted_dir = '/formatted/'\n\ndef multi_delimiters_to_single(row):\n return \"\\t\".join(row.split())\n\n\ndef process_file(file):\n dirname = os.path.dirname(file)\n filename, file_extension = os.path.splitext(file)\n print(\"FILE: \"+file)\n print(\"DIRNAME: \"+dirname)\n create_formatted_directory(dirname)\n new_filename = dirname + extra_formatted_dir + '/formatted_' + os.path.basename(filename) + '.txt'\n temp_file = filename + '.tmp'\n unnamed_col = 'Unnamed: 0'\n main_sep = '\\t'\n sep = main_sep\n if file_extension == '.csv':\n sep = ','\n\n\n df = pd.read_csv(file, comment='#', sep=sep, dtype=str, error_bad_lines=False, warn_bad_lines=True, chunksize=1000000)\n\n header = None\n new_header = None\n what_changed = None\n\n first = True\n for chunk in df:\n\n # map headers\n header = chunk.columns.values\n chunk.rename(columns=known_header_transformations, inplace=True)\n new_header = chunk.columns.values\n what_changed = dict(zip(header, new_header))\n #print(\"PARSED HEADER: \"+str(new_header))\n\n\n if first:\n chunk.to_csv(temp_file, mode='w', header=True, sep=main_sep, na_rep=\"NA\")\n first = False\n else:\n chunk.to_csv(temp_file, mode='a', header=False, sep=main_sep, na_rep=\"NA\")\n\n\n if CHR_BP in new_header:\n # split the chr_bp field\n df = pd.read_csv(temp_file, usecols=[CHR_BP], comment='#', sep=main_sep, dtype=str, error_bad_lines=False, warn_bad_lines=True)\n df = df.join(df[CHR_BP].str.split('_|:', expand=True).add_prefix(CHR_BP).fillna('NA'))\n\n if CHR_BP + '1' in df:\n df[CHR] = df[CHR_BP + '0'].str.replace('CHR|chr|_|-', '')\n df[CHR] = df[CHR].apply(lambda i: i if i in VALID_CHROMS else 'NA')\n df[BP] = df[CHR_BP + '1']\n df = df.drop(CHR_BP + '1', axis=1)\n else:\n df[BP] = df[CHR_BP + '0']\n df = df.drop(CHR_BP, axis=1)\n df = df.drop(CHR_BP + '0', axis=1)\n\n chunks = pd.read_csv(temp_file, comment='#', sep=main_sep, dtype=str, error_bad_lines=False, warn_bad_lines=True, chunksize=1000000)\n first = True\n for chunk in chunks:\n result = pd.merge(chunk, df, left_index=True, right_index=True).drop([unnamed_col,CHR_BP],axis=1)\n result = ordered_columns(result)\n if first:\n result.to_csv(new_filename, mode='w', header=True, sep=main_sep, na_rep=\"NA\", index=False)\n first = False\n else:\n result.to_csv(new_filename, mode='a', header=False, sep=main_sep, na_rep=\"NA\", index=False)\n\n elif CHR in new_header:\n # clean the chr field\n chunks = pd.read_csv(temp_file, comment='#', sep=main_sep, dtype=str, error_bad_lines=False, warn_bad_lines=True, chunksize=1000000)\n first = True\n for chunk in chunks:\n if unnamed_col in chunk:\n chunk = chunk.drop(unnamed_col,axis=1)\n chunk = ordered_columns(chunk)\n if first:\n chunk.to_csv(new_filename, mode='w', header=True, sep=main_sep, na_rep=\"NA\", index=False)\n first = False\n else:\n chunk.to_csv(new_filename, mode='a', header=False, sep=main_sep, na_rep=\"NA\", index=False)\n\n elif CHR not in new_header and BP not in new_header and VARIANT in new_header:\n\n if VARIANT != 'rsID':\n # split the snp field\n df = pd.read_csv(temp_file, usecols=[VARIANT], comment='#', sep=main_sep, dtype=str, error_bad_lines=False, warn_bad_lines=True)\n\n df = df.join(df[VARIANT].str.split('_|:', expand=True).add_prefix(VARIANT).fillna('NA'))\n df[CHR] = df[VARIANT + '0'].str.replace('CHR|chr|_|-', '')\n df[CHR] = df[CHR].apply(lambda i: i if i in VALID_CHROMS else 'NA')\n if VARIANT + '1' in df.columns:\n df[BP] = df[VARIANT + '1']\n df = df.drop(VARIANT + '1', axis=1)\n df = df.drop(VARIANT + '0', axis=1)\n df = df.drop(VARIANT, axis=1)\n\n chunks = pd.read_csv(temp_file, comment='#', sep=main_sep, dtype=str, error_bad_lines=False, warn_bad_lines=True, chunksize=1000000)\n first = True\n for chunk in chunks:\n if VARIANT == 'rsID':\n result = chunk\n else:\n result = pd.merge(chunk, df, left_index=True, right_index=True).drop(VARIANT,axis=1)\n\n # Cleanup/order the columns\n if unnamed_col in result:\n result = result.drop(unnamed_col,axis=1)\n result = ordered_columns(result)\n\n if first:\n result.to_csv(new_filename, mode='w', header=True, sep=main_sep, na_rep=\"NA\", index=False)\n first = False\n else:\n result.to_csv(new_filename, mode='a', header=False, sep=main_sep, na_rep=\"NA\", index=False)\n\n else:\n print(\"Exiting because, couldn't map the headers\")\n os.remove(new_filename)\n sys.exit()\n\n if os.path.isfile(temp_file):\n os.remove(temp_file)\n\n if os.path.exists(new_filename):\n new_gzip_filename = new_filename+'.gz'\n input = open(new_filename, 'rb')\n file_content = input.read()\n input.close()\n\n compressed_file = gzip.open(new_gzip_filename, 'wb')\n compressed_file.write(file_content)\n compressed_file.close()\n\n print(\"\\n------> Output saved in file:\", new_gzip_filename, \"<------\\n\")\n print(\"Please use this file for any further formatting.\\n\")\n print(\"Showing how the headers where mapped below...\\n\")\n for key, value in what_changed.items():\n print(key, \" -> \", value)\n print(\"\\nPeeking into the new file...\")\n print(\"\\n\")\n peek.peek(new_gzip_filename)\n\n return new_gzip_filename\n\n\ndef ordered_columns(dataframe):\n new_header = []\n df_header = dataframe.columns.values\n # Order of expected columns\n for col in TO_DISPLAY_ORDER:\n if col in df_header:\n new_header.append(col)\n # Order of other columns\n for hcol in df_header:\n if not hcol in new_header:\n new_header.append(hcol)\n #print(\"PROCESSED HEADER: \"+str(new_header))\n return dataframe[new_header]\n\n\ndef create_formatted_directory(path):\n \"\"\" Creates directory for a given file \"\"\"\n path += extra_formatted_dir\n if not os.path.isdir(path):\n try:\n os.mkdir(path, 0o755)\n except OSError:\n print (\"Creation of the directory %s failed\" % path)\n exit()\n\ndef main():\n argparser = argparse.ArgumentParser()\n argparser.add_argument('-f', help='The name of the file to be processed', metavar='SCORING_FILE_NAME')\n argparser.add_argument('--dir', help='The name of the directory containing the files that need to processed')\n args = argparser.parse_args()\n\n new_file = None\n\n print('\\n#-------------------#\\n# File Formatting #\\n#-------------------#')\n if args.f and args.dir is None:\n file = args.f\n new_file = process_file(file)\n elif args.dir and args.f is None:\n dir = args.dir\n print(\"Processing the following files:\")\n for f in glob.glob(\"{}/*.*\".format(dir)):\n print(f)\n new_file = process_file(f)\n else:\n print(\"You must specify either -f OR --dir \")\n\n return new_file\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"curator_formatter/format/automatic_formatting.py","file_name":"automatic_formatting.py","file_ext":"py","file_size_in_byte":7698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"64851113","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 28 20:47:11 2016\n\n@author: Duan Yutong (dyt@physics.bu.edu, dyt@lbl.gov)\n\n\"\"\"\n\n#%% function\n\ndef segmentation_photometry(path_file_abs,\n bkg_sigma = 3.0,\n source_snr = 3.0,\n fwhm_kernel = 2.0,\n x_size_kernel = 3,\n y_size_kernel = 3,\n save_fig_pdf = True,\n clobber = False):\n\n \"\"\"\n\n given a fits file (master image), this function calculates\n aperture photometry by source segmentation.\n\n make_source_mask not yet available in photutils v0.2.2, this version\n manually creates a source mask for determining background.\n\n \"\"\"\n\n import os\n import copy\n import glob\n import pickle\n import numpy as np\n from scipy import ndimage\n import matplotlib\n import matplotlib.pyplot as plt\n from astropy.io import fits, ascii\n from astropy.convolution import Gaussian2DKernel\n from astropy.stats import sigma_clipped_stats, gaussian_fwhm_to_sigma\n# from astropy.table import Table\n from astropy.visualization import (LogStretch, mpl_normalize)\n# from astropy.extern.six.moves import StringIO\n from photutils import (detect_threshold, EllipticalAperture,\n source_properties, properties_table)\n from photutils.detection import detect_sources\n from photutils.utils import random_cmap\n\n # create preliminary mask\n #from photutils import make_source_mask\n #masterMask = make_source_mask(master, snr=2, npixels=5, dilate_size=11)\n\n# if LEDoff was used, get threshold from LEDoff/background\n# path_dataset = os.path.dirname(path_file_abs) + os.path.sep\n# filenameCombined = '\\t'.join(\n# os.listdir(os.path.join(datasetDirLocal, 'master')))\n# if 'master_ledoff_subtracted' in filename:\n# print('Using master_ledoff')\n# # path_file_abs = os.path.join(datasetDir, 'master', filename)\n# hdu = fits.open(path_file_abs)[0]\n# data_subtracted = hdu.data\n# # calculate threadhold\n# ledoff_pred = np.mean(data_subtracted) * \\\n# np.ones(data_subtracted.shape)\n# mse = mean_squared_error(data_subtracted, ledoff_pred)\n# rmse = np.sqrt(mse)\n# threshold = 7.0 * rmse\n# threshold_value = threshold\n# if no LEDoff was used, background subtraction is needed\n# there should exist no file named \"subtracted\"\n# if 'master.fit' in filenameCombined \\\n# or 'master_normalised.fit' in filenameCombined:\n\n filename = os.path.basename(path_file_abs)\n dir_save = os.path.dirname(path_file_abs)\n filenames_combined = '\\t'.join(os.listdir(os.path.dirname(path_file_abs)))\n\n if clobber == False \\\n and 'segm.obj' in filenames_combined \\\n and 'props.obj' in filenames_combined \\\n and 'props.csv' in filenames_combined\\\n and 'props.ecsv' in filenames_combined:\n print('Photometry properties table already exists. Reading objects...')\n segm = pickle.load(open(glob.glob(os.path.join(\n dir_save, '*segm.obj*'))[0],\n 'rb'))\n props = pickle.load(open(glob.glob(os.path.join(\n dir_save, '*props.obj*'))[0],\n 'rb'))\n\n return [segm, props]\n\n if 'master' in path_file_abs:\n if 'normalised' in path_file_abs:\n print('Performing photometry to '\n + 'normalised master object image {}...'.format(path_file_abs))\n else:\n print('Performing photometry to '\n + 'un-normalised master image {}...'.format(path_file_abs))\n else:\n print('Warning: Photometry being performed to '\n + 'a single exposure {}...'.format(path_file_abs))\n\n hdu = fits.open(path_file_abs)[0]\n data = hdu.data\n header = hdu.header\n\n if 'EXPREQ' in header:\n exptime = header['EXPREQ']\n elif 'EXPTIME' in header:\n exptime = header['EXPTIME']\n else:\n print('Exposure time not found in header. Cannot determine magnitude.')\n exptime = np.nan\n\n # === Iteratively determine background level ===\n\n # assuming background is homogenous, estimate background by sigma clipping\n # if background noise varies across image, generate 2D background instead\n print('Determining background noise level...''')\n [mean, median, std] = sigma_clipped_stats(data, sigma=bkg_sigma, iters=5)\n threshold = median + (std * 2.0)\n segm = detect_sources(data, threshold, npixels=5)\n # turn segm into a mask\n mask = segm.data.astype(np.bool)\n # dilate the source mask to ensure complete masking of detected sources\n dilate_structure = np.ones((5, 5))\n mask_dilated = ndimage.binary_dilation(mask, structure=dilate_structure)\n # get sigma clipping stats of background, without sources that are masekd\n [bkg_mean, bkg_median, bkg_std] = sigma_clipped_stats(\n data, sigma=bkg_sigma, mask=mask_dilated, iters = 3)\n\n # === Detect sources by segmentation ===\n\n print('Determining threshold for source detection...')\n # determine threshold for source detection\n # in current implementation, if all inputs are present, the formula is\n # threshold = background + (background_error * snr)\n threshold = detect_threshold(data,\n background = bkg_median,\n error = bkg_std,\n snr = source_snr)\n print('Preparing 2D Gaussian kernal...')\n sigma_kernel = fwhm_kernel * gaussian_fwhm_to_sigma\n kernel = Gaussian2DKernel(sigma_kernel,\n x_size = x_size_kernel,\n y_size = y_size_kernel)\n # normalise kernel\n # The kernel models are normalized per default, ∫∞−∞f(x)dx=1∫−∞∞f(x)dx=1.\n # But because of the limited kernel array size, the normalization\n # for kernels with an infinite response can differ from one.\n kernel.normalize()\n # obtain a SegmentationImage object with the same shape as the data,\n # where sources are labeled by different positive integer values.\n # A value of zero is always reserved for the background.\n # if the threshold includes the background level as above, then the image\n # input into detect_sources() should not be background subtracted.\n print('Segmentation processing...')\n segm = detect_sources(data, threshold, npixels=5, filter_kernel=kernel)\n print('Segmentation labels are: ', repr(segm.labels))\n\n # === Measure regional source properties ===\n\n # source_properties() assumes that the data have been background-subtracted.\n # Background is the background level that was previously present\n # in the input data.\n # The input background does not get subtracted from the input data,\n # which should already be background-subtracted.\n print('Extracting source properties...')\n props = source_properties(data-bkg_median, segm, background=bkg_median)\n # add flux and instrumental magnitude to properties\n # flux = source_sum / exptime\n # instrumental magnitude = -2.5 * log10(flux)\n for i in range(len(props)):\n # source_sum is by definition background-subtracted already\n props[i].flux = props[i].source_sum/exptime\n props[i].mag_instr = -2.5 * np.log10(props[i].flux)\n # make plots and save to images\n # define approximate isophotal ellipses for each object\n apertures = []\n r = 2.8 # approximate isophotal extent\n for prop in props:\n position = (prop.xcentroid.value, prop.ycentroid.value)\n a = prop.semimajor_axis_sigma.value * r\n b = prop.semiminor_axis_sigma.value * r\n theta = prop.orientation.value\n apertures.append(EllipticalAperture(position, a, b, theta=theta))\n\n # create a table of properties\n try:\n props_table = properties_table(props)\n except:\n print('No source detected in {}'.format(path_file_abs))\n return [None, None]\n\n props_table['flux'] = [props[i].flux for i in range(len(props))]\n props_table['mag_instr'] = [props[i].mag_instr for i in range(len(props))]\n # add custom columns to the table: mag_instru and flux\n\n # plot centroid and segmentation using approximate elliptical apertures\n norm = mpl_normalize.ImageNormalize(stretch = LogStretch())\n rand_cmap = random_cmap(segm.max + 1, random_state=12345)\n [fig1, (ax1, ax2)] = plt.subplots(1, 2, figsize = (12, 6))\n ax1.imshow(data, origin='lower', cmap=plt.cm.gray, norm=norm)\n ax1.plot(\n props_table['xcentroid'], props_table['ycentroid'],\n ls='none', color='blue', marker='+', ms=10, lw=1.5)\n ax2.imshow(segm, origin='lower', cmap=rand_cmap)\n for aperture in apertures:\n aperture.plot(ax=ax1, lw=1.0, alpha=1.0, color='red')\n aperture.plot(ax=ax2, lw=1.0, alpha=1.0, color='red')\n # plot using actual segmentation outlines (to be improved)\n [fig2, ax3] = plt.subplots(figsize = (6, 6))\n ax3.imshow(data, origin='lower', cmap=plt.cm.gray, norm=norm)\n segm_outline = np.array(segm.outline_segments(), dtype=float)\n segm_outline[segm_outline<1] = np.nan\n # get a copy of the gray color map\n segm_outline_cmap = copy.copy(plt.cm.get_cmap('autumn'))\n # set how the colormap handles 'bad' values\n segm_outline_cmap.set_bad(alpha=0)\n ax3.imshow(segm_outline, origin='lower', cmap=segm_outline_cmap)\n\n # === save ===\n # Save segm, porps to object files, and also save props to table file.\n print('Saving segmentation and source properties to {}...'.format(dir_save))\n try:\n # if filename ends with fits, remove it in the filename\n if filename[-5:] == '.fits':\n dir_save_prefix = os.path.join(dir_save, filename[0:-5])\n else:\n dir_save_prefix = os.path.join(dir_save, filename)\n # Enhanced CSV allows preserving table meta-data such as\n # column data types and units.\n # In this way a data table can be stored and read back as ASCII\n # with no loss of information.\n ascii.write(props_table, dir_save_prefix + '-phot_props.ecsv',\n format = 'ecsv')\n # csv for readability in MS excel\n ascii.write(props_table,dir_save_prefix + '-phot_props.csv',\n format = 'csv')\n\n # dump segmentation and properties to object files in binary mode\n file_segm = open(dir_save_prefix + '-phot_segm.obj', 'wb')\n pickle.dump(segm, file_segm)\n file_props = open(dir_save_prefix + '-phot_props.obj', 'wb')\n pickle.dump(props, file_props)\n\n # save figures\n fig1.savefig(dir_save_prefix + '-phot_segm_fig1.png', dpi=600)\n\n\n fig2.savefig(dir_save_prefix + '-phot_segm_fig2.png', dpi=600)\n\n if save_fig_pdf:\n\n matplotlib.rcParams['text.usetex'] = True\n matplotlib.rcParams['text.latex.unicode'] = True\n from matplotlib.backends.backend_pdf import PdfPages\n\n pp1 = PdfPages(dir_save_prefix + '-phot_segm_fig1.pdf')\n pp1.savefig(fig1)\n pp1.close()\n\n pp2 = PdfPages(dir_save_prefix + '-phot_segm_fig2.pdf')\n pp2.savefig(fig2)\n pp2.close()\n\n print('Segmentation, properties objects, tables, and images saved to',\n dir_save)\n except:\n print('Unable to write to disk, check permissions.')\n\n return [segm, props]\n","sub_path":"pd_fpc_analyses_of_parker/photometry.py","file_name":"photometry.py","file_ext":"py","file_size_in_byte":11646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"454081572","text":"from __future__ import unicode_literals\nimport requests\nfrom requests_oauthlib import OAuth1\nimport Config.config as config\n\nREQUEST_TOKEN_URL = config.REQUEST_TOKEN_URL\nAUTHORIZE_URL = config.AUTHORIZE_URL\nACCESS_TOKEN_URL = config.ACCESS_TOKEN_URL\n\nCONSUMER_KEY = config.CONSUMER_KEY\nCONSUMER_SECRET = config.CONSUMER_SECRET\n\nOAUTH_TOKEN = \"\"\nOAUTH_TOKEN_SECRET = \"\"\n\ndef setup_oauth():\n \"\"\"Authorize your app via identifier.\"\"\"\n oauth = OAuth1(CONSUMER_KEY, client_secret=CONSUMER_SECRET)\n r = requests.post(url=REQUEST_TOKEN_URL, auth=oauth)\n resource_owner_key = r.content.split('&')[0].split('=')[1]\n resource_owner_secret = r.content.split('&')[1].split('=')[1]\n authorize_url = AUTHORIZE_URL + resource_owner_key\n return authorize_url, resource_owner_key, resource_owner_secret\n\ndef tverifier(verifier, resource_owner_key, resource_owner_secret):\n \"\"\"Verify your account via pin\"\"\"\n oauth = OAuth1(CONSUMER_KEY,\n client_secret=CONSUMER_SECRET,\n resource_owner_key=resource_owner_key,\n resource_owner_secret=resource_owner_secret,\n verifier=verifier)\n\n # Finally, Obtain the Access Token\n r = requests.post(url=ACCESS_TOKEN_URL, auth=oauth)\n token = r.content.split('&')[0].split('=')[1]\n secret = r.content.split('&')[1].split('=')[1]\n screen_name = r.content.split('&')[3].split('=')[1]\n return token, secret, screen_name\n\ndef get_oauth(oauth_token, oauth_token_secret):\n \"\"\"Get the authorization to tweet\"\"\"\n oauth = OAuth1(CONSUMER_KEY,\n client_secret=CONSUMER_SECRET,\n resource_owner_key=oauth_token,\n resource_owner_secret=oauth_token_secret)\n return oauth\n","sub_path":"modules/oauth.py","file_name":"oauth.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"652621579","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# python/motorcycle_linesearch.py Author \"Nathan Wycoff \" Date 07.12.2019\n#TODO: Does consensus optimization require us to consider the effect of nets on one another? Here, I am doing the gradient norms separately. Is that a problem?\n\n# Run a CGAN on the motorcycle data.\nimport keras\nimport numpy as np\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\n\nnp.random.seed(123)\nimport tensorflow as tf\nfrom scipy.optimize import line_search\ntf.enable_eager_execution()\ntf.set_random_seed(123)\n\nP = 1 # Dim of X data (to be conditioned on)\nR = 1 # Dim of latent error variable\nQ = 1 # Dim of y data (to be generated)\nH = 40# Number of hidden units\nepochs = 1000\ndoubleback_const = 0.1\n\n# Load and pre-process data\nmcycle = np.genfromtxt('./data/mcycle.csv', delimiter=',', skip_header = 1)\nN = mcycle.shape[0]\nx = mcycle[:,0].reshape([N,P])\ny = mcycle[:,1].reshape([N,Q])\n#x /= max(x)\n#y = (y-min(y)) / (max(y) - min(y))\nx = (x - np.mean(x)) / np.std(x)\ny = (y - np.mean(y)) / np.std(y)\n\n# Build the generator, accepts X and Z as inputs\ngen = tf.keras.Sequential()\ngen.add(tf.keras.layers.Dense(H, input_dim = P + R, activation = tf.keras.activations.elu))\ngen.add(tf.keras.layers.Dense(H, activation = tf.keras.activations.elu))\ngen.add(tf.keras.layers.Dense(Q))\n\n# Build the discriminator, accepts an X and a Y as inputs.\ndisc = tf.keras.Sequential()\ndisc.add(tf.keras.layers.Dense(H, input_dim = P + Q, activation = tf.keras.activations.elu))\ndisc.add(tf.keras.layers.Dense(H, activation = tf.keras.activations.elu))\ndisc.add(tf.keras.layers.Dense(1, activation = tf.keras.activations.sigmoid))\n\ngen.summary()\ndisc.summary()\n\n# NOTE: Compilation of discriminator needs to occur BEFORE we set its weights untrainable below, as these changes will not be reflected until disc is compiled again. So also be wary of compiling disc later, as its weights may not change.\n#TODO: the above is a mess, find a better way.\n#disc.compile(tf.keras.optimizers.Adam(), 'binary_crossentropy')\ndisc.compile(tf.train.GradientDescentOptimizer(learning_rate = 1.0), 'binary_crossentropy')\n\nnoise = tf.keras.layers.Input(shape = (R,))\nxdat = tf.keras.layers.Input(shape = (P,))\n\ngenin = tf.keras.layers.concatenate([xdat, noise])\ngenout = gen(genin)\n\ndiscin = tf.keras.layers.concatenate([xdat, genout])\nvalidity = disc(discin)\n\n#NOTE: Next lin possible issue in ordering of inputs?\nboth_mod = tf.keras.models.Model([xdat, noise], validity)\nboth_mod.layers[5].trainable = False\n\n#both_mod.compile(tf.keras.optimizers.Adam(), 'binary_crossentropy')\n#both_mod.compile(tf.train.AdamOptimizer(), 'binary_crossentropy')\nboth_mod.compile(tf.train.GradientDescentOptimizer(learning_rate = 1.0), 'binary_crossentropy')\n\n## Custom training with double backprop\n#genloss = lambda: both_mod.output\n#genopt = tf.keras.optimizers.Adam(genloss, both_mod.trainable_variables)\n\ndef par2mat(weights, nnet):\n \"\"\"\n Turn a weight vector into a list of weights suitable for assignment to a neural net. First arg is the vec, second the net.\n \"\"\"\n weights_list = []\n used_weights = 0\n for l in nnet.layers:\n nin = l.input_shape[1]\n nout = l.output_shape[1]\n weights_list.append(weights[(used_weights):(used_weights+nin*nout)].reshape((nin,nout)))\n used_weights += nin*nout\n weights_list.append(weights[(used_weights):(used_weights+nout)].flatten())\n used_weights += nout\n\n if used_weights < len(weights):\n print(\"Warning: weight input is longer than required for this neural network.\")\n\n return(weights_list)\n\n# Do the training!\nfor epoch in tqdm(range(epochs)):\n # Sample some noise\n #TODO: Batch size\n some_noise = np.random.normal(size=[N,R])\n\n gen_dat = gen.predict(np.hstack([x, some_noise]))\n\n # Train discriminator\n #NOTE: Minor discrepency in losses from the manual loop below and from keras's built in: follow up if there appears to be bugs.\n #disc_rl = disc.train_on_batch(np.hstack([x, y]), np.ones(N))\n #disc_fl = disc.train_on_batch(np.hstack([x, gen_dat]), np.zeros(N))\n #disc_loss = 0.5 * np.add(disc_rl, disc_fl)\n\n #TODO: mat2par\n def disc_obj(weights, grad = False):\n\n weights_list = par2mat(weights, disc)\n disc.set_weights(weights_list)\n\n disc.trainable = True\n with tf.GradientTape() as td:\n with tf.GradientTape() as t:\n #preds_real = disc(tf.cast(np.concatenate([x, y]).reshape([N,P+Q]), tf.float32))\n #preds_fake = disc(tf.cast(np.concatenate([x, gen_dat]).reshape([N,P+Q]), tf.float32))\n preds_real = disc(tf.cast(np.hstack([x, y.reshape([N,Q])]), tf.float32))\n preds_fake = disc(tf.cast(np.hstack([x, gen_dat]), tf.float32))\n dl_real = tf.reduce_mean(keras.losses.binary_crossentropy(np.ones(N).reshape([N,1]), tf.cast(preds_real, tf.float64)))\n dl_fake = tf.reduce_mean(keras.losses.binary_crossentropy(np.zeros(N).reshape([N,1]), tf.cast(preds_fake, tf.float64)))\n dl = 0.5*tf.add(dl_real, dl_fake)\n\n grads = t.gradient(dl, disc.trainable_variables)\n grads_norm = 0\n for i in range(len(grads)):\n #grads_norm += tf.reduce_sum(tf.square(grads[i]))\n grads_norm += tf.reduce_mean(tf.square(grads[i]))\n grads_norm /= float(len(grads))\n total_cost = tf.cast(dl, tf.float32) + doubleback_const * grads_norm\n\n double_grads = td.gradient(grads_norm, disc.trainable_variables)\n\n both_grads = [grads[i] + doubleback_const*double_grads[i] for i in range(len(grads))]\n\n if grad:\n return(np.concatenate([x.numpy().flatten() for x in both_grads]))\n else:\n return(total_cost.numpy())\n\n # Do SGD with line search\n weight_vec = np.concatenate([x.flatten() for x in disc.get_weights()])\n dgrad = disc_obj(weight_vec, grad = True)\n ls = line_search(disc_obj, lambda x: disc_obj(x, grad = True), weight_vec, -dgrad)\n if ls[0] is not None:\n step = min(ls[0], 1.0)\n else:\n step = 1.0\n new_weight_vec = weight_vec - step * dgrad\n disc.set_weights(par2mat(new_weight_vec, disc))\n #grads_n_vars = [(double_grads[i], disc.trainable_variables[i]) for i in range(len(grads))]\n #disc.optimizer.apply_gradients(grads_n_vars)\n #disc.trainable = False\n\n print(\"Disc step: %f\"%step)\n\n # Train generator\n #both_mod.train_on_batch([x, some_noise], np.ones(N))\n # Manually compute and apply gradient\n\n def gen_obj(weights, grad = False):\n\n weights_list = par2mat(weights, gen)\n gen.set_weights(weights_list)\n\n with tf.GradientTape() as td:\n with tf.GradientTape() as t:\n #preds = both_mod([tf.cast(x, tf.float32), tf.cast(some_noise, tf.float32)])\n #gen_dat = gen(tf.cast(np.hstack([x, some_noise]), tf.float32))\n #preds = disc(tf.cast(np.hstack([x, gen_dat]), tf.float32))\n gen_dat = gen(tf.cast(tf.concat([x, some_noise], 1), tf.float32))\n preds = disc(tf.cast(tf.concat([x, gen_dat], 1), tf.float32))\n bl = tf.reduce_mean(keras.losses.binary_crossentropy(np.ones(N).reshape([N,1]), tf.cast(preds, tf.float64)))\n #bl = tf.losses.sigmoid_cross_entropy(preds, np.ones(N).reshape([N,1]))\n\n grads = t.gradient(bl, gen.trainable_variables)\n grads_norm = 0\n for i in range(len(grads)):\n #grads_norm += tf.reduce_sum(tf.square(grads[i]))\n grads_norm += tf.reduce_mean(tf.square(grads[i]))\n grads_norm /= float(len(grads))\n total_cost = tf.cast(bl, tf.float32) + doubleback_const * grads_norm\n\n double_grads = td.gradient(grads_norm, gen.trainable_variables)\n\n both_grads = [grads[i] + doubleback_const*double_grads[i] for i in range(len(grads))]\n\n if grad:\n return(np.concatenate([x.numpy().flatten() for x in both_grads]))\n else:\n return(total_cost.numpy())\n\n # Do SGD with line search\n weight_vec = np.concatenate([x.flatten() for x in gen.get_weights()])\n dgrad = gen_obj(weight_vec, grad = True)\n ls = line_search(gen_obj, lambda x: gen_obj(x, grad = True), weight_vec, -dgrad)\n if ls[0] is not None:\n step = min(ls[0], 1.0)\n else:\n step = 1.0\n new_weight_vec = weight_vec - step * dgrad\n gen.set_weights(par2mat(new_weight_vec, gen))\n #grads_n_vars = [(grads[i] + doubleback_const*double_grads[i], both_mod.trainable_variables[i]) for i in range(len(grads))]\n #both_mod.optimizer.apply_gradients(grads_n_vars)\n\n print(\"Gen step: %f\"%step)\n\n# Plot the results\nfig = plt.figure()\nplt.scatter(x, y)\nsome_noise = np.random.normal(size=[N,P])\npreds = gen.predict(np.hstack([x, some_noise]))\nplt.scatter(x, preds)\n#plt.savefig(\"images/motor_scatter.pdf\")\nplt.savefig(\"temp.pdf\")\n","sub_path":"python/motorcycle_linesearch.py","file_name":"motorcycle_linesearch.py","file_ext":"py","file_size_in_byte":8961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"603562930","text":"#!/usr/bin/env python3\n\nimport os\nimport argparse\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom prdepth import sampler\nfrom prdepth import metric\nimport prdepth.utils as ut\nfrom prdepth.optimization.interactive_optimizer import AnnotationOptimizer as Optimizer\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n '--n_estimation', default=10, type=int, help='number of estimations')\nparser.add_argument(\n '--save_dir', default=None, help='save predictions to where')\nopts = parser.parse_args()\nsave_dir = opts.save_dir\n\nTLIST = 'data/test.txt'\nMAXITER = 200\nTOLERANCE = 1e-8\nREGION_SIZE = 50\n# Slowly increasing weight for diversity cost.\nLMD = 10. * 2**(np.arange(50) / (50. - 1.) - 1.)\n\n#########################################################################\n\ndepth_sampler = sampler.Sampler(nsamples=100, read_gt=True)\n\noptimizer = Optimizer(depth_sampler, REGION_SIZE)\n\nsess = tf.Session()\ndepth_sampler.load_model(sess)\n\n#########################################################################\nflist = [i.strip('\\n') for i in open(TLIST).readlines()]\ndepths, preds = [], []\n\nfor filename in flist:\n # Run VAE to sample patch-wise predictions.\n depth_sampler.sample_predictions(filename, sess)\n depth = sess.run(depth_sampler.image_depth).squeeze().astype(np.float64)\n\n optimizer.initialize_diversity_cost(sess)\n\n diverse_estimations, rmses = [], []\n for m in range(opts.n_estimation):\n optimizer.initialize_optimization(sess)\n\n for i in range(MAXITER):\n lmd = LMD[i] if i < len(LMD) else LMD[-1]\n global_current = optimizer.update_global_estimation(sess)\n diff = optimizer.update_sample_selection(lmd, sess)\n\n if diff < TOLERANCE and i >= len(LMD):\n break\n pred = optimizer.update_global_estimation(sess)\n\n pred = np.clip(pred.squeeze(), 0.01, 1.).astype(np.float64)\n diverse_estimations.append(pred)\n\n rmse = metric.get_metrics(\n [depth], [pred], projection_mask=True, rmse_only=True)\n rmses.append(rmse)\n\n # Simulate the user annotation of the erroneous region in the returned\n # prediction.\n erroneous_mask = optimizer.simulate_user_annotation(depth, sess)\n optimizer.update_diversity_cost(erroneous_mask, sess)\n\n # Select the best from multiple diverse estimations.\n pred = diverse_estimations[np.argmin(rmses)]\n preds.append(pred)\n depths.append(depth)\n\n if save_dir is not None:\n print(np.argmin(rmses))\n nm = os.path.join(save_dir, os.path.basename(filename))\n min_depth = np.maximum(0.01, np.min(depth))\n max_depth = np.minimum(1., np.max(depth))\n ut.save_color_depth(nm + '_gt.png', depth, min_depth, max_depth)\n ut.save_color_depth(\n nm + '_interactive_best.png', pred, min_depth, max_depth)\n\nmetrics = metric.get_metrics(depths, preds, projection_mask=True)\nfor k in metric.METRIC_NAMES:\n print(\"%s: %.3f\" % (k, metrics[k]))\n","sub_path":"interactive_estimation.py","file_name":"interactive_estimation.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"169202233","text":"#!/usr/bin/env python\nfrom os import listdir, rename, makedirs\nfrom os.path import isdir, expanduser\nfrom subprocess import run, Popen\neditor = \"nvim\"\ntrash = expanduser(\"~/.local/trash/\")\n\ndef move(oldfile, newfile):\n if \"/\" in newfile:\n k = newfile.rfind(\"/\")\n folder = newfile[:k]\n if not isdir(folder):\n makedirs(folder)\n rename(oldfile, newfile)\n\ndef getnames(files):\n tmp_file = \"/tmp/bulkrename\"\n\n text = files[0]\n for file in files[1:]:\n text = text +\"\\n\"+file\n with open(tmp_file, \"w\") as f:\n f.write(text)\n\n run([editor, tmp_file])\n files_new = []\n with open(tmp_file, \"r\") as f:\n for line in f.readlines():\n files_new.append(line[:-1])\n\n Popen([\"rm\", tmp_file])\n return files_new\n\n\nfiles = sorted(listdir())\nfiles_new = getnames(files)\nn = len(files)\n\nif len(files_new) == n:\n for i in range(0, n):\n if files_new[i] == \"rm\":\n move(files[i], trash+files[i])\n else:\n if files[i] != files_new[i]:\n move(files[i], files_new[i])\nelse:\n print(\"The numbers of new files is changed.\")\n","sub_path":"bulkrename.py","file_name":"bulkrename.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"426502264","text":"\n\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n \n def __repr__(self):\t\t\n if self:\t\t\n return \"{} -> {}\".format(self.val, self.next)\n \nimport heapq\nclass Solution(object):\n def mergeKLists(self, lists):\n \"\"\"\n :type lists: List[ListNode]\n :rtype: ListNode\n \"\"\"\n heap=[]\n cnt = 0 # used as tie breaker\n for node in lists:\n if node:\n heapq.heappush(heap, (node.val, cnt, node)) # Wrong! does not support duplicate, ListNode can not be used as tie breaker\n cnt += 1\n \n head=ListNode(-1)\n curr=head\n while heap:\n smallest=heapq.heappop(heap)[2]\n curr.next=smallest\n curr=curr.next\n if smallest.next:\n heapq.heappush(heap,(smallest.next.val, cnt, smallest.next))\n cnt += 1\n \n return head.next\n \n#class Solution(object):\n# def mergeKLists(self, lists):\n# \"\"\"\n# :type lists: List[ListNode]\n# :rtype: ListNode\n# \"\"\"\n# if not lists:\n# return None\n# n=len(lists)\n# end=n-1 # n lists need n-1 merge\n# while end>0:\n# start=0\n# while startl2.val:\n# tmp=l2.next\n# l2.next=l1\n# prev.next=l2\n# l2=tmp\n# else:\n# l1=l1.next\n# prev=prev.next \n# if l2:\n# prev.next=l2\n# \n# return dummy.next\n \n \nif __name__ == \"__main__\":\n list1 = ListNode(1)\n list1.next = ListNode(5)\n list2 = ListNode(2)\n list2.next = ListNode(4)\n list3 = ListNode(3)\n list3.next = ListNode(6)\n print(Solution().mergeKLists([list1, list2, list3]))\n \n list1 = ListNode(1)\n list1.next = ListNode(5)\n list2 = ListNode(1)\n list2.next = ListNode(4)\n list3 = ListNode(1)\n list3.next = ListNode(6)\n print(Solution().mergeKLists([list1, list2, list3]))","sub_path":"23. Merge k Sorted Lists.py","file_name":"23. Merge k Sorted Lists.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"572683651","text":"items = \"Whats the simpliest way to add the list items to a dictionary \"\n\nstatsi = {}\nfor i in items:\n if i in statsi:\n statsi[i] += 1\n else:\n statsi[i] = 1\n\n# bonus\nprint(statsi, i)\n","sub_path":"pythonwork/ttt.py","file_name":"ttt.py","file_ext":"py","file_size_in_byte":203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"282030602","text":"import pkg_resources\nimport json\nimport gzip\nimport re\n\nfrom random import randrange\n\nDICTIONARY = json.loads(gzip.decompress(pkg_resources.resource_string(__name__, 'data/dictionary.json.gz')))\nSENTENCES = json.loads(gzip.decompress(pkg_resources.resource_string(__name__, 'data/sentences.json.gz')))\n\n\ndef get_madlib():\n sentence = SENTENCES[randrange(len(SENTENCES))]\n\n # Sometimes there is punctuation that split won't handle\n sentence = sentence.replace('[[', ' [[').replace(']]', ']] ')\n words = sentence.split()\n for i, word in enumerate(words):\n if word[:2] == '[[' and word[-2:] == ']]':\n type = word[2:-2]\n type_list = DICTIONARY[type]\n word = type_list[randrange(len(type_list))]\n words[i] = word\n return re.sub(r'\\s([?.!,:;\\'\"](?:\\s|$))', r'\\1', ' '.join(words))\n","sub_path":"src/madlib/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"587296734","text":"#!/usr/bin/env python\n\"\"\"This script copies figures into the figures directory.\"\"\"\n\nimport os\nimport sys\nimport shutil\n\n\ndef fix_eps(fpath):\n \"\"\"Fix carriage returns in EPS files caused by Arial font.\"\"\"\n txt = b\"\"\n with open(fpath, \"rb\") as f:\n for line in f:\n if b\"\\r\\rHebrew\" in line:\n line = line.replace(b\"\\r\\rHebrew\", b\"Hebrew\")\n txt += line\n with open(fpath, \"wb\") as f:\n f.write(txt)\n\n\nif __name__ == \"__main__\":\n # Get RM2 figs\n figdir = os.path.join(\"RM2-tow-tank\", \"Figures\")\n figlist = [\"cp_curves.eps\",\n \"cd_curves.eps\",\n \"perf_re_dep.eps\",\n \t \"meancontquiv.eps\",\n \"k_contours.eps\",\n \t \"K_trans_bar_graph.eps\",\n \t \"no_blades_all.eps\",\n \t \"perf_covers.eps\"]\n for fig in figlist:\n shutil.copy2(os.path.join(figdir, fig), os.path.join(\"figures\", fig))\n\n # Get RVAT-Re-dep figs\n figdir = os.path.join(\"RVAT-Re-dep\", \"Figures\")\n figlist = [\"meancontquiv_10.eps\", \"k_contours_10.eps\", \"perf_re_dep.eps\"]\n\n for fig in figlist:\n fix_eps(os.path.join(figdir, fig))\n fign = \"RVAT-Re-dep-\" + fig\n shutil.copy2(os.path.join(figdir, fig), os.path.join(\"figures\", fign))\n","sub_path":"scripts/getfigs.py","file_name":"getfigs.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"7901943","text":"###set operations .remove() .discard() .pop()\n\n\nn = int(input())\ns = set(map(int, input().split()))\nm=int(input())\nfor i in range(m):\n arg=input().split(\" \")\n if arg[0]==\"pop\":\n s.pop()\n elif arg[0]==\"remove\":\n s.remove(int(arg[1]))\n elif arg[0]==\"discard\":\n s.discard(int(arg[1]))\nprint(sum(s))\n\n\"\"\" ---------------------------------------------------------------------------------------\"\"\"\n#set .union() and .intersection() .difference() operation\nm=int(input())\ns1=set(map(int,input().split()))\nn=int(input())\ns2=set(map(int,input().split()))\n#s=s1.union(s2) #also be written as s=s1|s2\n#s=s1.intersection(s2) #intersection of s1 and s2\n#s=s1.difference(s2) #difference of s1 and s2\ns=s1.symmetric_difference(s2) #symmetric difference of s1 and s2\nprint(len(s))","sub_path":"set operations.py","file_name":"set operations.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"583679766","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 8 21:14:55 2021\n\n@author: JZ2018\n\"\"\"\n\nimport streamlit as st\nimport pandas as pd\nimport altair as alt\nimport datetime\nimport urllib\nimport plotly.express as px\nfrom gsheet_fun import *\nfrom electricity_scrape import *\n#from pycaret.regression import *\n\nimport plotly.graph_objects as go\nfrom plotly.offline import plot\nfrom plotly.subplots import make_subplots\n\n#https://docs.google.com/spreadsheets/d/1nf6qwqHwficHPX4gB0mMJtEm3YE31VJHgJtZ8teJJGI/edit?usp=sharing\n#@st.cache\n#d2 = pd.read_csv('aeso_hpp.csv')\n#d2 = d2.drop(d2.columns[0], axis = 1)\n#Gsheet_Append(d2, aeso_hpp_id, sheet_range)\n#aeso_hpp = Gsheet_Download(aeso_hpp_id, sheet_range)\n#aeso_hpp['Date (HE)'] = aeso_hpp['Date (HE)'].apply(pd.to_datetime)\n#dftest = aeso_hpp[0:2]\n#Gsheet_Append(dftest, aeso_hpp_id, sheet_range)\n#test_model = load_model('final_model1')\n\n#function to retrieve data from google sheet\ndef get_data(sheet_id, sheet_range):\n #df = pd.read_csv('aeso_hpp.csv')\n # here enter the id of your google sheet\n #aeso_hpp_id = '1sRkTyY8jlv-NGizn-0ulBSIgIjQmVvpBVnofy49-NPM'\n #weather_daily_id = '1niPYt8HCYKWLFqnJbSv-7p-kuk9qheIx-igeL5hIy0s'\n #weather_hourly_id = '1k_41_j8CpYeGDNdRWRlIyx_2cx58ROp-6bQ3RcFZidg'\n #sheet_range = 'A1:AA1000000'\n \n #download google sheet with sheet id and excel style range (everything in string format)\n df = Gsheet_Download(aeso_hpp_id, sheet_range)\n #convert datetime column to appropriate format\n df['DATETIME'] = df['DATETIME'].apply(pd.to_datetime)\n #convert numerical columns to appropriate format\n #num_cols = ['Price ($)', '30Ravg ($)', 'AIL Demand (MW)']\n num_cols = ['PRICE']\n df[num_cols] = df[num_cols].apply(pd.to_numeric, errors = 'coerce')\n # if df.columns.values[0] == 'Unnamed: 0':\n # df.columns.values[0] = 'RowID'\n # else:\n # df['RowID'] = df.index+1\n return df\n\ndef uca_price_conversion(price):\n consumer_price = 1.1104*price/1000 + 0.0116\n return consumer_price\n\n#function to append new data to google sheet\ndef append_newdata(data, sheetid, sheet_range):\n #get max date available in downloaded google sheet data\n maxdate = max(data['DATETIME'])\n #get current date time\n currdate = datetime.datetime.now()\n dateformat = '%Y-%m-%d'\n \n #use existing scrape functions to get new data if current date < maxdate in google sheet\n if maxdate < currdate - datetime.timedelta(days=2):\n #call scrape function from electricity_scrape\n append_data = aeso_download_range('HistoricalPoolPrice', 'html', maxdate.strftime(dateformat), currdate.strftime(dateformat), dateformat)\n #convert column types\n append_data['Date (HE)'] = append_data['Date (HE)'].apply(pd.to_datetime)\n num_cols = ['Price ($)', '30Ravg ($)', 'AIL Demand (MW)']\n append_data[num_cols] = append_data[num_cols].apply(pd.to_numeric, errors='coerce')\n #append together new scraped data with historical data from google sheet\n append_data2 = append_data[['Date (HE)', 'Price ($)']]\n append_data2.columns = ['DATETIME','PRICE']\n data2 = data.append(append_data2).reset_index(drop=True).drop_duplicates(subset='DATETIME', keep='last').sort_values('DATETIME')\n \n #convert everything to string to prepare for google sheet upload\n upload_data = data2.copy()\n upload_data['Date'] = upload_data['DATETIME'].dt.date\n upload_data_sum = upload_data.groupby('Date').agg({'PRICE':'mean'}).reset_index()\n upload_data_sum.columns = ['DATETIME','PRICE']\n #Gsheet_Append(upload_data, sheetid, sheet_range)\n #upload new data to replace all data in google sheet\n Gsheet_updateAll(upload_data_sum.applymap(str), sheetid, sheet_range)\n print(str(upload_data_sum.shape[0]) + ' rows added to google sheet data')\n \n else:\n data2 = data.copy()\n return data2\n\n\n# def Gen_Pred_df(model, data):\n# currdate = datetime.datetime.now()\n# maxdate = max(data['Date (HE)'])\ndf_preds = pd.read_parquet('combine_preds2.parquet') \ndf_preds['Date'] = df_preds['Date'].apply(pd.to_datetime)\ntry:\n #google sheet id for electricity prices and demand (from Historical Pool Price)\n aeso_hpp_id = '1nf6qwqHwficHPX4gB0mMJtEm3YE31VJHgJtZ8teJJGI'\n #aeso_hpp_id = '1sRkTyY8jlv-NGizn-0ulBSIgIjQmVvpBVnofy49-NPM'\n #define max sheet ranges to look for data in google sheet\n sheet_range = 'A1:AA1000000'\n #get data from google sheet\n data_gsheet = get_data(aeso_hpp_id, sheet_range)\n #check if new data needs to be appended to google sheet\n data_new = append_newdata(data_gsheet, aeso_hpp_id, sheet_range)\n #clean and sort data\n data_new2 = data_new.reset_index(drop=True).drop_duplicates().sort_values('DATETIME')\n data_new2.columns = ['Date', 'Predicted Price $']\n data_new2['Data Source'] = 'AESO_HPP_Historical'\n data = df_preds.append(data_new2).sort_values(['Data Source', 'Date']).reset_index(drop=True)\n data_models = data['Data Source'].unique().tolist()\n data_models.remove('AESO_HPP_Historical')\n #data['Date'] = data['Date'].apply(pd.to_datetime)\n data['Electricity Price $/kwh'] = uca_price_conversion(data['Predicted Price $'])\n #data = data.rename(columns={'Date (HE)':'Date'})\n #data['Date'] = data['Date'].apply(pd.to_datetime)\n \n #print out current datetime in streamlit\n st.write('Current Date '+str(datetime.datetime.now().strftime('%Y-%m-%d'))) \n #streamlit input to filter plot range by minimum date\n mindate = st.date_input(\n 'Plot Start Date', datetime.date(2020,1,1)\n )\n #streamlit input to update plot with defined range\n # st.write('Click below to update plot time range')\n # dateupdate = st.button('Update Plot Time Range')\n # #streamlit input for user's input electricity price quote\n st.sidebar.write('Enter your quoted electricity price below in $/kwh')\n user_priceinput = st.sidebar.number_input('Price', value = 0.05)\n st.sidebar.write(f'Your price is {user_priceinput} $/kwh')\n #streamlit input for user's input electricity price quote period\n st.sidebar.write('Enter your electricity price lock-in time')\n #user_locktime = st.number_input('Years', format = '%i')\n user_locktime = st.sidebar.slider('Years', 0, 5, 1)\n user_locktime_int = int(user_locktime)\n st.sidebar.write(f'Your quoted price is locked in for {user_locktime_int} years')\n \n user_select_mod = st.sidebar.selectbox(label = 'Select Model', options=data_models)\n \n #convert minimum plot range date to appropriate format\n mindate = datetime.datetime.strptime(str(mindate), '%Y-%m-%d')\n maxdate = datetime.datetime.now() + datetime.timedelta(days=user_locktime_int*365)\n maxdate = maxdate.strftime('%Y-%m-%d')\n maxdate = datetime.datetime.strptime(str(maxdate), '%Y-%m-%d')\n #execute only if \"mindate\" exists\n if not mindate:\n st.error(\"Please select start date for plot range\")\n else:\n # #update plot ranges via filtering the table to dates newer than mindate only\n # if dateupdate:\n # df = data.loc[data['Date']>=mindate]\n # else:\n # df = data.loc[data['Date']>=datetime.datetime.strptime('2020-01-01', '%Y-%m-%d')]\n df = data.loc[data['Date']>=mindate]\n df = df.loc[df['Date']<=maxdate]\n df['DailyCost'] = df['Electricity Price $/kwh'] * 20\n df_calcs = df[df['Data Source'] == user_select_mod]\n df_calcs = df_calcs.loc[df_calcs['Date']>=datetime.datetime.now().strftime('%Y-%m-%d')]\n df_calcs['CumCost'] = df_calcs['DailyCost'].cumsum()\n user_cost = 7300*user_priceinput*user_locktime_int\n cost_diff = round(df_calcs['CumCost'].max() - user_cost, 2)\n if cost_diff > 0:\n out_txt = f'Your Quote is predicted to save ${abs(cost_diff)} dollars compared to variable price over {user_locktime_int} years'\n st.markdown(f'{out_txt}', unsafe_allow_html=True)\n else:\n out_txt = f'Your Quote is predicted to cost ${abs(cost_diff)} more dollars compared to variable price over {user_locktime_int} years'\n st.markdown(f'{out_txt}', unsafe_allow_html=True)\n \n #write a header line and dataframe for visualization\n # st.write(\"AESO Historical Data\", df)\n\n # #test Altair charting with electricity price over time\n # chart1 = (\n # alt.Chart(df)\n # .mark_line(opacity=0.5)\n # .encode(\n # x=\"Date:T\",\n # y=alt.Y(\"Electricity Price $/kwh:Q\", stack=None)\n # )\n # )\n \n # chart2 = (\n # alt.Chart(df)\n # .mark_line(opacity=0.5)\n # .encode(\n # x=\"Date:T\",\n # y=alt.Y(\"AIL Demand (MW):Q\", stack=None)\n # )\n # )\n \n #test plotly charting with AIL Demand over time\n # chart2 = px.scatter(df, x='Date', y='AIL Demand (MW)')\n \n # st.write('Alberta Electricity Price History')\n # st.altair_chart(chart1, use_container_width=True)\n # st.write('Alberta Electricity Demand Hsitory')\n # st.plotly_chart(chart2, use_container_width=True)\n \n fig=go.Figure()\n plt_types = df['Data Source'].unique().tolist()\n for p in plt_types:\n subdf = df.loc[df['Data Source']==p]\n if p == 'AESO_HPP_Historical':\n plt_mod = 'markers'\n else:\n plt_mod = 'lines'\n fig.add_trace(go.Scatter(x=subdf['Date'], y=subdf['Electricity Price $/kwh'], mode = plt_mod, name = p))\n fig.add_hline(y=user_priceinput)\n fig.update_yaxes(type='log')\n fig.update_layout(width = 900,\n title = 'Prediction and Historical Prices',\n xaxis_title = 'Date',\n yaxis_title = 'Electricity Price $/kwh',\n legend_title = 'Plot Data Sources',\n font = dict(family='Courier New, monospace',size=15,color='RebeccaPurple'))\n st.write('Alberta Electricity Demand History')\n st.plotly_chart(fig, use_container_width=False)\n \n#error handling function \nexcept urllib.error.URLError as e:\n st.error(\n \"\"\"\n **error**\n\n Connection error: %s\n \"\"\"\n % e.reason\n )","sub_path":"streamlit_test2.py","file_name":"streamlit_test2.py","file_ext":"py","file_size_in_byte":10503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"551715449","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport traceback\nimport json\nfrom enum import Enum\nfrom opensslcmd import OpenSSLCmd, OpenSSLCmdStatus\n\n\nclass VaultStatus(Enum):\n OK = 1\n ERR_CREATE = 2\n FILE_EXISTS = 3\n OPENSSL_ERROR = 4\n VAULT_CLOSED = 5\n NOT_FOUND = 6\n JSON_ERROR = 7\n\n\nclass Vault:\n def __init__(self, config):\n self.data = None\n self.config = config\n self.vault_file = config.get('path_vault')\n\n def create(self, secret, reinitialize=False, debug=False):\n if reinitialize and os.path.exists(self.vault_file):\n try:\n os.remove(self.vault_file)\n except IOError:\n if debug:\n traceback.print_exc()\n return VaultStatus.ERR_CREATE\n vault_folder = os.path.dirname(self.vault_file)\n if not os.path.exists(vault_folder):\n try:\n os.makedirs(vault_folder)\n except IOError:\n if debug:\n traceback.print_exc()\n return VaultStatus.ERR_CREATE\n if os.path.exists(self.vault_file):\n return VaultStatus.FILE_EXISTS\n try:\n self.data = json.loads('{}')\n except json.JSONDecodeError:\n if debug:\n traceback.print_exc()\n return VaultStatus.JSON_ERROR\n status = self.save(secret)\n self.data = None\n return status\n\n def save(self, secret):\n if self.data is not None:\n cmd = self.config.get('openssl_cmd.vault_encode').replace('$OUT', self.vault_file).replace('$PW', secret)\n status, _ = OpenSSLCmd.execute(cmd, stdin_bytes=json.dumps(self.data).encode())\n if status != OpenSSLCmdStatus.OK:\n return VaultStatus.OPENSSL_ERROR\n return VaultStatus.OK\n else:\n return VaultStatus.VAULT_CLOSED\n\n def open(self, secret, debug=False):\n if not os.path.exists(self.vault_file):\n return VaultStatus.NOT_FOUND\n cmd = self.config.get('openssl_cmd.vault_decode').replace('$IN', self.vault_file).replace('$PW', secret)\n status, data = OpenSSLCmd.execute(cmd, fetch_stdout_bytes=True)\n if status != OpenSSLCmdStatus.OK:\n return VaultStatus.OPENSSL_ERROR\n try:\n self.data = json.loads(data.decode())\n except json.JSONDecodeError:\n if debug:\n traceback.print_exc()\n return VaultStatus.JSON_ERROR\n return VaultStatus.OK\n\n def isopen(self):\n if self.data:\n return True\n return False\n\n def close(self):\n self.data = None\n","sub_path":"vaulty/vault.py","file_name":"vault.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"260793566","text":"import requests\nimport re\nfrom argparse import ArgumentParser\nimport sys\nfrom bs4 import BeautifulSoup\n\ngrep_list = None\n\narguments = None\n\ndef print_banner():\n print('''\\nDescription: \n CloudScraper is a tool to search through the source code of websites in order to find cloud resources belonging to a target.\n by Jordan Potti\n @ok_bye_now\\n'''\n ) \n\nheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'\n }\n\ndef start(target, depth):\n print(\"Beginning search for cloud resources in \", target, \"\\n\")\n try:\n start_page = requests.get(target,allow_redirects=True,headers=headers)\n except requests.exceptions.RequestException as e:\n if 'https' in target:\n try:\n start_page = requests.get(target.replace('https','http'),allow_redirects=True,headers=headers)\n except requests.exceptions.RequestException as e:\n print(e)\n links = []\n soup = BeautifulSoup(start_page.text, \"lxml\")\n for link in soup.findAll('a', attrs={'href':re.compile(\"^http://\")}):\n links.append(link.get('href'))\n for link in soup.findAll('a', attrs={'href':re.compile(\"^https://\")}): \n links.append(link.get('href'))\n for link in soup.findAll('link', attrs={'href':re.compile(\"^http://\")}): \n links.append(link.get('href'))\n for link in soup.findAll('link', attrs={'href':re.compile(\"^https://\")}): \n links.append(link.get('href'))\n\n urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',start_page.text)\n links.extend(urls)\n spider(links,target,depth)\n\ndef spider(links,target,depth):\n target_clean = target.replace(\"https://\",\"\")\n target_clean_2 = target_clean.replace(\"http://\",\"\")\n for url in links:\n if (target_clean_2 in url) and url.count(\"/\") < depth+2:\n try:\n page = requests.get(url, allow_redirects=True, headers=headers)\n soup = BeautifulSoup(page.text, \"lxml\")\n for link in soup.findAll('a', attrs={'href':re.compile(\"^http://\")}):\n links.append(link.get('href'))\n for link in soup.findAll('a', attrs={'href':re.compile(\"^https://\")}): \n links.append(link.get('href'))\n for link in soup.findAll('link', attrs={'href':re.compile(\"^http://\")}): \n links.append(link.get('href'))\n for link in soup.findAll('link', attrs={'href':re.compile(\"^https://\")}): \n links.append(link.get('href'))\n except requests.exceptions.RequestException as e: # This is the correct syntax\n if 'https' in target: \n try:\n page = requests.get(target.replace('https','http'),allow_redirects=True,headers=headers)\n soup = BeautifulSoup(page.text, \"lxml\")\n for link in soup.findAll('a', attrs={'href':re.compile(\"^http://\")}):\n links.append(link.get('href'))\n for link in soup.findAll('a', attrs={'href':re.compile(\"^https://\")}): \n links.append(link.get('href'))\n for link in soup.findAll('link', attrs={'href':re.compile(\"^http://\")}): \n links.append(link.get('href'))\n for link in soup.findAll('link', attrs={'href':re.compile(\"^https://\")}): \n links.append(link.get('href'))\n except requests.exceptions.RequestException as e:\n print(e)\n urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',page.text)\n links.extend(urls)\n links = list(set(links))\n parser(links)\n\n\ndef parser(links):\n matches = []\n cloud_matches=['amazonaws.com','digitaloceanspaces.com','windows.net']\n for strings in cloud_matches:\n for link in links:\n if strings in link:\n matches.append(link)\n matches = list(set(matches))\n if len(matches) == 0:\n print(\"There were no matches!\")\n else:\n print(\"\\nThere were \", len(matches), \" matches for this search!\")\n for match in matches:\n print(match, \"\\n\")\n\ndef main():\n global arguments\n global grep_list\n parser = ArgumentParser()\n parser.add_argument(\"-u\", dest=\"URL\", required=False, help=\"Target Scope\") \n parser.add_argument(\"-d\", dest=\"depth\",type=int, required=False, default=25, help=\"Max Depth of links Default: 25\")\n parser.add_argument(\"-l\", dest=\"targetlist\", required=False, help=\"Location of text file of Line Delimited targets\") \n\n if len(sys.argv) == 1:\n parser.error(\"No arguments given.\")\n parser.print_usage\n sys.exit()\n\n#ouput parsed arguments into a usable object\n arguments = parser.parse_args()\n\n if arguments.targetlist:\n with open (arguments.targetlist, 'r') as target_list:\n for line in target_list:\n if 'http' not in line:\n line_mod = \"https://\"+line\n start(line_mod.rstrip(), arguments.depth)\n else:\n start(line, arguments.depth)\n else: \n if 'http' not in arguments.URL:\n line_mod = \"https://\"+arguments.URL\n start(line_mod.rstrip(), arguments.depth)\n else:\n start(arguments.URL, arguments.depth)\nprint_banner()\nmain()\n","sub_path":"CloudScraper.py","file_name":"CloudScraper.py","file_ext":"py","file_size_in_byte":5627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"507281412","text":"# purpose: to draw detector's hitmap\n\nimport random\n\nimport numpy as np\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n# log scale colorbar with imshow\nimport matplotlib.colors as mcolors\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\n\n# make test data\ndata = np.array([[random.randint(0, 100) for row in range(66)]\n for column in range(4)])\nfor row in [0, 61]:\n for column in [0, 2]:\n data_tmp = random.randint(0, 100)\n data[column][row:row+5] = data_tmp\n data[column+1][row:row+5] = data_tmp\nfor row in range(5, 61, 7):\n for column in [0, 3]:\n data[column][row:row+7] = random.randint(0, 100)\nprint('data:', data)\n\n# make log scale colorbar\nnorm = mcolors.SymLogNorm(linthresh=1, vmin=0, vmax=data.max()*10)\n# plot imshow and colorbar\nimage_imshow = ax.imshow(data, cmap=\"viridis\", aspect='auto', norm=norm)\nfig.colorbar(image_imshow, orientation='horizontal')\n\n# hide ticks and it's label\nax.set_xticks([])\nax.set_yticks([])\nax.xaxis.set_ticklabels([])\nax.yaxis.set_ticklabels([])\n\n# overlay rectangular area on plot\nfor x in range(5, 61):\n for y in range(2):\n center_area = plt.Rectangle(\n # (x,y) of upper left corner, width, hight\n (-0.5 + x, 0.5 + y), 1, 1,\n edgecolor=\"Black\", fill=False)\n ax.add_patch(center_area)\n\nfor x in [0 - 0.5, 61 - 0.5]:\n for y in [-0.5, 1.5]:\n leftright_area = plt.Rectangle(\n (x, y), 5, 2,\n edgecolor=\"Black\", fill=False)\n ax.add_patch(leftright_area)\n\nfor x in range(5, 60, 7):\n for y in [-0.5, 2.5]:\n topbottom_area = plt.Rectangle(\n (-0.5 + x, y), 7, 1,\n edgecolor=\"Black\", fill=False)\n ax.add_patch(topbottom_area)\n\nplt.show()\n","sub_path":"hitmap.py","file_name":"hitmap.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"220823621","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- \n\n## Here we imported both Gtk library and the WebKit2 engine. \nimport gi\ngi.require_version('Gtk', '3.0')\ngi.require_version('WebKit2', '4.0')\nfrom gi.repository import Gtk, GdkPixbuf, Gdk, GLib, WebKit2\n\nimport time\nimport threading\nimport json\nimport os.path\n\nfrom math import pi, sin, cos, atan2\n\nimport roslib; roslib.load_manifest('graupner_serial')\nimport rospy\nimport roslaunch\nfrom sensor_msgs.msg import NavSatFix\nfrom geographic_msgs.msg import GeoPoint\n\nfrom graupner_serial.msg import DesiredTrajectory, MissionWP, MissionStartStop, BatteryStatus, SelectedUAV, RCchannelData, PlotData, BuildingPoints\n\n# import local files\nfrom GMLParser import GMLParser\nfrom GoogleMapsWebWrapper import GoogleMapsJSWrapper, MapHTMLgenerator\n\n# All points are in the form of (Longitude, Latitude) !!!!!\nclass MapApp(threading.Thread):\n def __init__(self):\n #threading.Thread.__init__(self)\n self.rosInit = False\n\n# /* GTK */\n self.builder = Gtk.Builder()\n self.builder.add_from_file(roslib.packages.get_pkg_dir('graupner_serial')+'/scripts/map.glade')\n self.window = self.builder.get_object('map_window')\n self.builder.connect_signals(self)\n\n # GTK elements\n self.parcelEntry = self.builder.get_object('dropdown_parcels_entry')\n self.parcelListStore = self.builder.get_object('dropdown_parcels_liststore')\n self.parcelComboBox = self.builder.get_object('parcel_combobox')\n self.sendBuildingMarkersButton = self.builder.get_object('send_building_markers_button')\n self.mouseLatLabel = self.builder.get_object('mouse_latitude_label')\n self.mouseLongLabel = self.builder.get_object('mouse_longitude_label')\n self.mouseCoordSystemLabel = self.builder.get_object('coordinate_system_label')\n self.mouseLatLabelFix = self.builder.get_object('mouse_latitude_label_fix')\n self.mouseLongLabelFix = self.builder.get_object('mouse_longitude_label_fix')\n self.mouseCoordSystemLabelFix = self.builder.get_object('coordinate_system_label_fix')\n self.mouseLatLabelCustom = self.builder.get_object('mouse_latitude_label_custom')\n self.mouseLongLabelCustom = self.builder.get_object('mouse_longitude_label_custom')\n self.mouseCoordSystemLabelCustom = self.builder.get_object('coordinate_system_label_custom')\n self.hideMarkersCheckbox = self.builder.get_object('hideMarkers_cb')\n self.hidePolygonCheckbox = self.builder.get_object('hidePolygon_cb')\n self.hideTrajectoryCheckBox = self.builder.get_object('hide_trajectory_cb')\n self.UAVredImg = self.builder.get_object('uav_red_img')\n self.UAVgreenImg = self.builder.get_object('uav_green_img')\n self.UAVblueImg = self.builder.get_object('uav_blue_img')\n self.UAVredLatLabel = self.builder.get_object('uav_red_lat_label')\n self.UAVredLongLabel = self.builder.get_object('uav_red_long_label')\n self.UAVgreenLatLabel = self.builder.get_object('uav_green_lat_label')\n self.UAVgreenLongLabel = self.builder.get_object('uav_green_long_label')\n self.UAVblueLatLabel = self.builder.get_object('uav_blue_lat_label')\n self.UAVblueLongLabel = self.builder.get_object('uav_blue_long_label')\n self.UAVsizeSpinButton = self.builder.get_object('uav_icon_size_spinbutton')\n self.markerSizeSpinButton = self.builder.get_object('marker_size_spinbutton')\n self.trajectorySizeSpinButton = self.builder.get_object('trajectory_marker_size_spinbutton')\n self.markerColorButton = self.builder.get_object('marker_color_colorbutton')\n self.polygonColorButton = self.builder.get_object('polygon_color_colorbutton')\n self.trajectoryColorButton = self.builder.get_object('trajectory_colorbutton')\n self.polygonOpacityAdjustment = self.builder.get_object('polygon_opacity_adjustment')\n self.centerOfRotationLabel = self.builder.get_object('center_of_rotation_label')\n self.centerOfRotationCombobox = self.builder.get_object('center_of_rotation_combobox')\n self.centerOfRotationEntry = self.builder.get_object('center_of_rotation_entry')\n self.markerListStore = self.builder.get_object('dropdown_markers_liststore')\n self.polygonDragCheckButton = self.builder.get_object('polygon_drag_checkbutton')\n self.polygonRotateCheckButton = self.builder.get_object('polygon_rotate_checkbutton')\n self.addMarkersToggleButton = self.builder.get_object('add_markers_togglebutton')\n self.deleteLastMarkerButton = self.builder.get_object('delete_last_marker_button')\n self.resetNewMarkersButton = self.builder.get_object('reset_new_markers_button')\n self.acceptNewMarkersButton = self.builder.get_object('accept_new_markers_button')\n\n fileChooser = self.builder.get_object('file_chooser')\n GMLFileFilter = self.builder.get_object('GMLfile_filter')\n fileChooser.add_filter(GMLFileFilter)\n\n # scale and add images\n height = -1\n width = 30\n imgPath = roslib.packages.get_pkg_dir('graupner_serial')+\"/scripts/resources/UAV-red.svg\"\n pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(imgPath, width, height, True)\n self.UAVredImg.set_from_pixbuf(pixbuf)\n imgPath = roslib.packages.get_pkg_dir('graupner_serial')+\"/scripts/resources/UAV-green.svg\"\n pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(imgPath, width, height, True)\n self.UAVgreenImg.set_from_pixbuf(pixbuf)\n imgPath = roslib.packages.get_pkg_dir('graupner_serial')+\"/scripts/resources/UAV-blue.svg\"\n pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(imgPath, width, height, True)\n self.UAVblueImg.set_from_pixbuf(pixbuf)\n\n rgba = self.markerColorButton.get_rgba()\n self.markerColorHex = \"#{:02x}{:02x}{:02x}\".format(int(rgba.red*255), int(rgba.green*255), int(rgba.blue*255))\n rgba = self.polygonColorButton.get_rgba()\n self.polygonColorHex = \"#{:02x}{:02x}{:02x}\".format(int(rgba.red*255), int(rgba.green*255), int(rgba.blue*255))\n rgba = self.trajectoryColorButton.get_rgba()\n self.trajectoryColorHex = \"#{:02x}{:02x}{:02x}\".format(int(rgba.red*255), int(rgba.green*255), int(rgba.blue*255))\n self.markerColorButton.connect('notify::color', self.onMarkerColorChange)\n self.polygonColorButton.connect('notify::color', self.onPolygonColorChange)\n self.trajectoryColorButton.connect('notify::color', self.onTrajectoryColorChange)\n\n styleProvider = Gtk.CssProvider()\n styleProvider.load_from_data('''\n #add_markers_togglebutton { \n background: #DA3030; \n color: #C5B9C4;\n }\n ''')\n Gtk.StyleContext.add_provider(\n self.addMarkersToggleButton.get_style_context(),\n styleProvider,\n Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION\n )\n\n self.activeParcelTreeIter = None\n\n\n# /* Gmaps and WebKit2 */\n self.mapHolder = WebKit2.WebView()\n self.jsWrapper = GoogleMapsJSWrapper(self.mapHolder)\n\n self.coords = []\n self.adjustedCoords = []\n self.customCoords = []\n self.trajectory_coords = []\n self.phi0 = 0; self.R = 6370000 # earth radius\n self.v_translate = [0, 0]; self.alpha_rotate = 0\n self.UAVnames = [\"UAV\", \"red\", \"blue\", \"yellow\"]\n self.UAVpositions = {}\n self.js_loaded = False\n\n # print console log\n settings = self.mapHolder.get_settings()\n settings.set_enable_write_console_messages_to_stdout(True)\n settings.set_allow_universal_access_from_file_urls(True)\n self.mapHolder.set_settings(settings)\n\n # generate map.html\n HTMLgenerator = MapHTMLgenerator(0, 0, 1, apikey='AIzaSyD6rPVY-FLb97DdWua_O9u2nc316GsEtSw')\n HTMLfile = os.path.dirname(os.path.abspath(__file__)) + \"/map.html\"\n HTMLgenerator.draw(HTMLfile)\n\n # JS -> Python connection\n self.mapHolder.connect('notify::title', self.js2py)\n self.mapHolder.connect('load-changed', self.load_finished) # connect() je iz GObject-a\n\n # mapHolder.load_html(open('map.html').read(), None) # ne radi\n # mapHolder.load_uri(\"http://127.0.0.1:5000\")\n self.mapHolder.load_uri(\"file://\" + HTMLfile)\n # time.sleep(2)\n\n self.mapBox = self.builder.get_object('map_box')\n self.mapBox.pack_start(self.mapHolder, True, True, 0)\n\n# /* ROS */\n rospy.init_node('MultiUAV_GUI_Map_Node')\n rospy.Subscriber(\"red/mavros/global_position/global\", NavSatFix, self.ROS_global_odometry_callback, callback_args=\"red\")\n # rospy.Subscriber(\"blue/mavros/global_position/global\", NavSatFix, self.ROS_global_odometry_callback, callback_args=\"green\")\n # rospy.Subscriber(\"yellow/mavros/global_position/global\", NavSatFix, self.ROS_global_odometry_callback, callback_args=\"blue\")\n # rospy.Subscriber(\"\", coordinates_global, self.ROS_trajectory_callback)\n # rospy.Subscriber(\"PlotData\", PlotData, self.PlotCallback)\n self.building_points_pub = rospy.Publisher(\"BuildingPoints\", BuildingPoints, queue_size=10)\n time.sleep(0.5)\n\n self.mapHolder.show_all()\n\n self.window.connect('delete-event', self.destroy) \n self.window.show_all() \n\n\n def load_finished(self, webview, event):\n if event == WebKit2.LoadEvent.FINISHED:\n self.js_loaded = True\n #add UAVs\n self.jsWrapper.add_UAV(\"red\")\n self.jsWrapper.add_UAV('green')\n self.jsWrapper.add_UAV('blue')\n self.jsWrapper.execute()\n print(\"Map loaded\")\n\n\n# /* ROS */\n def ROS_global_odometry_callback(self, data, UAV):\n # self.set_UAV_position(UAV, [data.longitude, data.latitude])\n self.UAVpositions[UAV] = [data.longitude, data.latitude]\n\n def ROS_trajectory_callback(self, data):\n self.trajectory_coords = []\n for i in range(len(data.latitude)):\n self.trajectory_coords.append([data.plot_longitude[i], data.plot_latitude[i]])\n \n angles = []\n phi0 = self.trajectory_coords[0][1] * pi/180\n for i in range(len(self.trajectory_coords-1)):\n x = self.R*self.trajectory_coords[i][0]*pi/180*cos(phi0)\n y = self.R*self.trajectory_coords[i][1]*pi/180\n x_next = self.R*self.trajectory_coords[i+1][0]*pi/180*cos(phi0)\n y_next = self.R*self.trajectory_coords[i][1]*pi/180\n alpha = atan2(y_next, x_next) - atan2(y, x)\n angles.append(alpha)\n angles.append(alpha)\n\n self.jsWrapper.add_markers_trajectory(self.trajectory_coords, angles)\n self.jsWrapper.execute()\n\n def ROS_send_building_points(self, coords):\n longitudes = []; latitudes = []; pointIDs = []\n for i in range(len(coords)):\n pointIDs.append(i)\n longitudes.append(coords[i][0])\n latitudes.append(coords[i][1])\n buildingPoints = BuildingPoints()\n buildingPoints.pointIDs = pointIDs\n buildingPoints.latitudes = latitudes\n buildingPoints.longitudes = longitudes\n self.building_points_pub.publish(buildingPoints)\n \n\n def set_UAV_position(self, color, coords):\n coords = self.apply_adjustment(coords)\n if color == 'red':\n self.jsWrapper.set_UAV_position('red', coords)\n self.UAVredLatLabel.set_text(\"%14.10f\" % coords[1])\n self.UAVredLongLabel.set_text(\"%14.10f\" % coords[0])\n elif color == 'green':\n self.jsWrapper.set_UAV_position('green', coords)\n self.UAVgreenLatLabel.set_text(\"%14.10f\" % coords[1])\n self.UAVgreenLongLabel.set_text(\"%14.10f\" % coords[0])\n elif color == 'blue':\n self.jsWrapper.set_UAV_position('blue', coords)\n self.UAVblueLatLabel.set_text(\"%14.10f\" % coords[1])\n self.UAVblueLongLabel.set_text(\"%14.10f\" % coords[0])\n else:\n print(\"ERROR: MapApp.set_UAV_position: Referencing non existing UAV\")\n return\n self.jsWrapper.execute()\n\n\n def js2py(self, webview, event):\n try:\n msg = json.loads(self.mapHolder.get_title())\n except:\n print(\"Warning: No JSON can be loaded from document title\")\n return\n self.mouseLatLabel.set_text(\"%16.12f\" % msg['mouseCoords']['lat'])\n self.mouseLongLabel.set_text(\"%16.12f\" % msg['mouseCoords']['lng'])\n self.mouseLatLabelFix.set_text(\"%16.12f\" % msg['mouseCoords']['lat'])\n self.mouseLongLabelFix.set_text(\"%16.12f\" % msg['mouseCoords']['lng'])\n self.mouseLatLabelCustom.set_text(\"%16.12f\" % msg['mouseCoords']['lat'])\n self.mouseLongLabelCustom.set_text(\"%16.12f\" % msg['mouseCoords']['lng'])\n\n if msg['origin'] == 'marker_rotate_mouseup':\n self.adjustedCoords = msg['markerCoords']\n self.jsWrapper.set_polygon_drag(self.polygonDragCheckButton.get_active())\n self.jsWrapper.execute()\n self.set_transformation_parameters()\n elif msg['origin'] == 'polygon_drag_end':\n self.adjustedCoords = msg['markerCoords']\n self.set_transformation_parameters()\n elif msg['origin'] == 'markers_custom':\n self.customCoords = msg['customMarkerCoords']\n\n\n def set_transformation_parameters(self):\n assert(self.activeParcelTreeIter is not None)\n parcelID = self.parcelListStore[self.activeParcelTreeIter][0]\n coords = self.coords[parcelID]\n\n center = self.center_coords(coords)\n\n self.phi0 = center[1]*pi/180\n\n centerX = self.R*center[0]*pi/180*cos(self.phi0)\n centerY = self.R*center[1]*pi/180\n\n adjustedCenter = self.center_coords(self.adjustedCoords)\n\n adjustedCenterX = self.R*adjustedCenter[0]*pi/180*cos(self.phi0)\n adjustedCenterY = self.R*adjustedCenter[1]*pi/180\n\n self.v_translate = [adjustedCenterX - centerX, adjustedCenterY - centerY]\n \n markerX = self.R*coords[0][0]*pi/180*cos(self.phi0)\n markerY = self.R*coords[0][1]*pi/180\n angle = atan2(markerY - centerY, markerX - centerX)\n\n adjustedMarkerX = self.R*self.adjustedCoords[0][0]*pi/180*cos(self.phi0)\n adjustedMarkerY = self.R*self.adjustedCoords[0][1]*pi/180\n adjustedAngle = atan2(adjustedMarkerY - adjustedCenterY, \n adjustedMarkerX - adjustedCenterX)\n\n self.alpha_rotate = adjustedAngle - angle\n\n def apply_adjustment(self, coords):\n if self.activeParcelTreeIter is None:\n return coords\n parcelID = self.parcelListStore[self.activeParcelTreeIter][0]\n markerCoords = self.coords[parcelID]\n\n center = self.center_coords(markerCoords)\n centerX = self.R*center[0]*pi/180*cos(self.phi0)\n centerY = self.R*center[1]*pi/180\n\n posPlanarX = self.R*coords[0]*pi/180*cos(self.phi0)\n posPlanarY = self.R*coords[1]*pi/180\n\n rm = [[cos(self.alpha_rotate), -sin(self.alpha_rotate)],\n [sin(self.alpha_rotate), cos(self.alpha_rotate)]] # rotation matrix\n v = [posPlanarX - centerX, posPlanarY - centerY] # vector to rotate\n\n v_rotated = [rm[0][0]*v[0] + rm[0][1]*v[1], rm[1][0]*v[0] + rm[1][1]*v[1]]\n pos_rotated = [centerX + v_rotated[0], centerY + v_rotated[1]]\n\n pos_rotated_translated = [pos_rotated[0] + self.v_translate[0], \n pos_rotated[1] + self.v_translate[1]]\n adjustedPosition = [pos_rotated_translated[0] / (self.R*pi/180*cos(self.phi0)),\n pos_rotated_translated[1] / (self.R*pi/180)]\n return adjustedPosition\n\n def center_coords(self, coords):\n center = [0, 0]\n for c in coords[:-1]:\n center[0] += c[0]\n center[1] += c[1]\n center[0] /= len(coords[:-1])\n center[1] /= len(coords[:-1])\n return center\n\n\n def reset_config(self, coords):\n self.hideMarkersCheckbox.set_active(False)\n self.hidePolygonCheckbox.set_active(False)\n self.polygonDragCheckButton.set_active(False)\n self.polygonRotateCheckButton.set_active(False)\n\n self.markerListStore.clear()\n self.markerListStore.append([-1, \"Automatic\"])\n for i in range(len(coords)-1):\n s = \"Marker\" + str(i+1)\n self.markerListStore.append([i, s])\n treeModel = self.centerOfRotationCombobox.get_model()\n self.centerOfRotationCombobox.set_active_iter(treeModel.get_iter_first())\n\n self.alpha_rotate = 0\n self.v_translate = [0,0]\n\n def parcel_changed(self):\n assert(self.activeParcelTreeIter is not None)\n parcelID = self.parcelListStore[self.activeParcelTreeIter][0]\n coords = self.coords[parcelID] \n\n self.reset_config(coords)\n \n center = self.center_coords(coords)\n \n self.jsWrapper.clear_map()\n self.jsWrapper.set_map(center, 19) # zoom = 19\n self.jsWrapper.add_markers(coords[:-1], color=self.markerColorHex, size=self.markerSizeSpinButton.get_value())\n self.jsWrapper.add_polygon(coords, color=self.polygonColorHex, opacity=self.polygonOpacityAdjustment.get_value())\n self.jsWrapper.execute()\n\n\n \n########################## GTK Handlers ############################\n def onDropdownEntryActivate(self, parcelEntry):\n if self.activeParcelTreeIter is not None:\n treeModel = self.parcelComboBox.get_model()\n treeModel[self.activeParcelTreeIter][1] = parcelEntry.get_text()\n \n\n def onComboChange(self, parcelComboBox):\n treeIter = parcelComboBox.get_active_iter()\n if treeIter is not None:\n treeModel = parcelComboBox.get_model()\n parcelID, parcelName = treeModel[treeIter][:2]\n print(\"parcel ID: %d, parcel name: %s\" % (parcelID, parcelName))\n tmpActiveParcelTreeIter = self.activeParcelTreeIter\n self.activeParcelTreeIter = treeIter\n if tmpActiveParcelTreeIter is not None:\n if parcelID != treeModel[tmpActiveParcelTreeIter][0]:\n self.parcel_changed()\n else:\n self.parcel_changed()\n\n\n def onGMLFileUpload(self, fileChooser):\n GMLfile = fileChooser.get_filename()\n parser = GMLParser()\n parser.parse(GMLfile)\n coords_dict = parser.getCoordinatesDictionary()\n self.coords = coords_dict['coordinates']\n print(self.coords)\n self.parcelListStore.clear()\n for i in range(len(self.coords)):\n s = \"Parcel\" + str(i+1)\n self.parcelListStore.append([i, s])\n \n self.parcelEntry.set_text(\"\")\n self.reset_config([])\n self.activeParcelTreeIter = None\n\n\n def onMarkerComboChange(self, markerCombobox):\n if markerCombobox.get_active_iter() is None or not self.polygonRotateCheckButton.get_active():\n return\n self.jsWrapper.remove_marker_rotation_listener()\n treeModel = markerCombobox.get_model()\n treeIter = markerCombobox.get_active_iter()\n centerOfRotationMarkerID = treeModel[treeIter][0]\n self.jsWrapper.add_marker_rotation_listener(centerOfRotationMarkerID)\n self.jsWrapper.execute()\n\n\n def onHideMarkersCheckboxToggle(self, cbButton):\n if self.activeParcelTreeIter is None:\n cbButton.set_active(False)\n else:\n self.jsWrapper.hide_markers(cbButton.get_active())\n self.jsWrapper.execute()\n\n def onHidePolygonCheckboxToggle(self, cbButton):\n if self.activeParcelTreeIter is None:\n cbButton.set_active(False)\n else:\n self.jsWrapper.hide_polygon(cbButton.get_active())\n self.jsWrapper.execute()\n\n def onHideTrajectory(self, cbButton):\n print(\"not implemented\")\n\n def onSendBuildingMarkers(self, button):\n if self.activeParcelTreeIter is not None:\n parcelID = self.parcelListStore[self.activeParcelTreeIter][0]\n coords = self.coords[parcelID]\n self.ROS_send_building_points(coords[:-1])\n \n\n# /* Fix Markers */\n def onPolygonDragToggle(self, cbButton):\n if self.activeParcelTreeIter is None:\n cbButton.set_active(False)\n else:\n self.jsWrapper.set_polygon_drag(cbButton.get_active())\n self.jsWrapper.execute()\n\n \n def onPolygonRotateToggle(self, cbButton):\n if self.activeParcelTreeIter is None:\n cbButton.set_active(False)\n elif cbButton.get_active():\n self.centerOfRotationLabel.set_sensitive(True)\n self.centerOfRotationCombobox.set_sensitive(True)\n treeModel = self.centerOfRotationCombobox.get_model()\n treeIter = self.centerOfRotationCombobox.get_active_iter()\n centerOfRotationMarkerID = treeModel[treeIter][0]\n self.jsWrapper.add_marker_rotation_listener(centerOfRotationMarkerID)\n self.jsWrapper.execute()\n else:\n self.centerOfRotationLabel.set_sensitive(False)\n self.centerOfRotationCombobox.set_sensitive(False)\n self.jsWrapper.remove_marker_rotation_listener()\n self.jsWrapper.execute()\n\n\n def onFitBuildingPlanResetClicked(self, button):\n if self.activeParcelTreeIter is not None:\n self.parcel_changed()\n\n\n def onLoadConfig(self, button):\n dialog = Gtk.FileChooserDialog(\n title=\"Load Configuration File\", \n action=Gtk.FileChooserAction.OPEN,\n parent=self.window\n )\n dialog.add_buttons(\n Gtk.STOCK_CANCEL,\n Gtk.ResponseType.CANCEL,\n Gtk.STOCK_OPEN,\n Gtk.ResponseType.OK,\n )\n configFileFilter = self.builder.get_object('config_file_filter')\n dialog.add_filter(configFileFilter)\n dialog.run()\n configFile = dialog.get_filename()\n dialog.destroy()\n try:\n config = json.loads(open(configFile, 'r').read())\n except:\n print(\"MapError: %s is corrupted, cannot parse as JSON\" % configFile)\n return\n self.coords = config['coordinates']\n self.adjustedCoords = config['adjusted_coordinates']\n parcelID = config['parcelID']\n self.coords[parcelID] = self.adjustedCoords\n\n self.parcelListStore.clear()\n for i in range(len(self.coords)):\n s = \"Parcel\" + str(i+1)\n self.parcelListStore.append([i, s])\n self.activeParcelTreeIter = None\n self.parcelComboBox.set_active(parcelID)\n \n center = self.center_coords(self.coords[parcelID])\n \n self.jsWrapper.clear_map()\n self.jsWrapper.set_map(center, 19) # zoom = 19\n self.jsWrapper.add_markers(self.adjustedCoords[:-1], color=self.markerColorHex, size=self.markerSizeSpinButton.get_value())\n self.jsWrapper.add_polygon(self.adjustedCoords, color=self.polygonColorHex, opacity=self.polygonOpacityAdjustment.get_value())\n self.jsWrapper.execute()\n\n time.sleep(0.1)\n self.v_translate = config['v_translate']\n self.alpha_rotate = config['alpha_rotate']\n self.phi0 = config['phi0']\n\n\n def onSaveConfig(self, button):\n dialog = Gtk.FileChooserDialog(\n title=\"Save Configuration File\", \n action=Gtk.FileChooserAction.SAVE,\n parent=self.window\n )\n dialog.add_buttons(\n Gtk.STOCK_CANCEL,\n Gtk.ResponseType.CANCEL,\n Gtk.STOCK_SAVE,\n Gtk.ResponseType.ACCEPT,\n )\n dialog.set_do_overwrite_confirmation(True)\n dialog.run()\n configFile = dialog.get_filename()\n dialog.destroy()\n\n if configFile is None:\n return\n if not configFile.endswith('.config'):\n configFile = configFile + '.config'\n \n parcelID = self.parcelListStore[self.activeParcelTreeIter][0]\n config = {\n 'coordinates': self.coords,\n 'adjusted_coordinates': self.adjustedCoords,\n 'parcelID': parcelID,\n 'phi0': self.phi0,\n 'v_translate': self.v_translate,\n 'alpha_rotate': self.alpha_rotate\n }\n with open(configFile, 'w') as f:\n f.write( json.dumps(config, indent=4) )\n\n\n\n def onAddMarkersToggle(self, togglebutton):\n styleProvider = Gtk.CssProvider()\n if togglebutton.get_active():\n styleProvider.load_from_data('#add_markers_togglebutton { background: #3B54DC; }')\n else:\n styleProvider.load_from_data('#add_markers_togglebutton { background: #DA3030; }')\n Gtk.StyleContext.add_provider(\n togglebutton.get_style_context(),\n styleProvider,\n Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION\n )\n\n self.hideMarkersCheckbox.set_active(togglebutton.get_active())\n self.hidePolygonCheckbox.set_active(togglebutton.get_active())\n self.jsWrapper.custom_markers(togglebutton.get_active())\n self.jsWrapper.execute()\n\n def onResetNewMarkersClick(self, button):\n self.jsWrapper.remove_custom_markers()\n self.jsWrapper.execute()\n\n def onDeleteLastNewMarkerClick(self, button):\n self.jsWrapper.delete_last_custom_marker()\n self.jsWrapper.execute()\n\n def onAcceptNewMarkersClick(self, button):\n if(len(self.customCoords) < 3):\n infodialog = Gtk.MessageDialog(\n transient_for=self.window,\n flags=0,\n message_type=Gtk.MessageType.INFO,\n buttons=Gtk.ButtonsType.OK,\n text=\"Not enough points selected\"\n )\n infodialog.format_secondary_text(\"At least 3 points are needed to construct Building Ground Plan\")\n infodialog.run()\n infodialog.destroy()\n return\n\n dialog = Gtk.MessageDialog(\n transient_for=self.window,\n flags=0,\n message_type=Gtk.MessageType.INFO,\n buttons=Gtk.ButtonsType.OK_CANCEL,\n text='Your selection will be saved as building'\n )\n dialog.format_secondary_text(\"Selection is saved temporarily, if you want to save it permenantly save it as configuration file (Save Config)\")\n response = dialog.run()\n dialog.destroy()\n\n if response == Gtk.ResponseType.OK:\n newParcelID = len(self.coords)\n newParcelName = \"Parcel\" + str(newParcelID+1)\n self.parcelListStore.append([newParcelID, newParcelName])\n self.customCoords.append(self.customCoords[0])\n self.coords.append(self.customCoords)\n self.activeParcelTreeIter = None\n self.parcelComboBox.set_active(newParcelID)\n\n infodialog = Gtk.MessageDialog(\n transient_for=self.window,\n flags=0,\n message_type=Gtk.MessageType.INFO,\n buttons=Gtk.ButtonsType.OK,\n text=\"New Building Ground Plan is saved as \" + newParcelName\n )\n infodialog.run()\n infodialog.destroy()\n\n self.onResetNewMarkersClick(None)\n self.addMarkersToggleButton.set_active(False)\n\n\n# /* Customization */\n def onUAVMarkerSizeChange(self, spinButton):\n self.jsWrapper.set_UAV_marker_size(spinButton.get_value())\n self.jsWrapper.execute()\n \n def onMarkerSizeChange(self, spinButton):\n self.jsWrapper.set_marker_size(spinButton.get_value())\n self.jsWrapper.execute()\n\n def onMarkerColorChange(self, colorButton, *args):\n rgba = colorButton.get_rgba()\n self.markerColorHex = \"#{:02x}{:02x}{:02x}\".format(int(rgba.red*255), int(rgba.green*255), int(rgba.blue*255))\n if self.activeParcelTreeIter is not None:\n self.jsWrapper.set_marker_color(self.markerColorHex)\n self.jsWrapper.execute()\n \n def onPolygonColorChange(self, colorButton, *args):\n rgba = colorButton.get_rgba()\n self.polygonColorHex = \"#{:02x}{:02x}{:02x}\".format(int(rgba.red*255), int(rgba.green*255), int(rgba.blue*255))\n if self.activeParcelTreeIter is not None:\n self.jsWrapper.set_polygon_color(self.polygonColorHex)\n self.jsWrapper.execute()\n\n def onPolygonOpacityChange(self, ranger):\n if self.activeParcelTreeIter is not None:\n self.jsWrapper.set_polygon_opacity(ranger.get_value())\n self.jsWrapper.execute()\n\n def onTrajectoryMarkerSizeChange(self, spinButton):\n self.jsWrapper.set_trajectory_marker_size(spinButton.get_value())\n self.jsWrapper.execute()\n\n def onTrajectoryColorChange(self, colorButton, *args):\n rgba = colorButton.get_rgba()\n self.markerColorHex = \"#{:02x}{:02x}{:02x}\".format(int(rgba.red*255), int(rgba.green*255), int(rgba.blue*255))\n if self.trajectory_coords:\n self.jsWrapper.set_trajectory_marker_color(self.markerColorHex)\n self.jsWrapper.execute()\n\n def onResetTemplate(self, button):\n self.UAVsizeSpinButton.set_value(1.0)\n self.markerSizeSpinButton.set_value(1.0)\n markerColor = Gdk.RGBA()\n markerColor.parse(\"#0000FF\")\n self.markerColorButton.set_rgba(markerColor)\n polygonColor = Gdk.RGBA()\n polygonColor.parse(\"#6495ED\")\n self.polygonColorButton.set_rgba(polygonColor)\n self.polygonOpacityAdjustment.set_value(0.3)\n\n def onLoadTemplate(self, button):\n dialog = Gtk.FileChooserDialog(\n title=\"Load Template File\", \n action=Gtk.FileChooserAction.OPEN,\n parent=self.window\n )\n dialog.add_buttons(\n Gtk.STOCK_CANCEL,\n Gtk.ResponseType.CANCEL,\n Gtk.STOCK_OPEN,\n Gtk.ResponseType.OK,\n )\n templateFileFilter = self.builder.get_object('template_file_filter')\n dialog.add_filter(templateFileFilter)\n dialog.run()\n templateFile = dialog.get_filename()\n dialog.destroy()\n try:\n template = json.loads(open(templateFile, 'r').read())\n except:\n print(\"MapError: %s is corrupted, cannot parse as JSON\" % templateFile)\n return\n rgba = Gdk.RGBA()\n self.markerSizeSpinButton.set_value(template['marker_size'])\n rgba.parse(template['marker_color'])\n self.markerColorButton.set_rgba(rgba)\n self.UAVsizeSpinButton.set_value(template['uav_size'])\n rgba.parse(template['polygon_color'])\n self.polygonColorButton.set_rgba(rgba)\n self.polygonOpacityAdjustment.set_value(template['polygon_opacity'])\n\n def onSaveTemplate(self, button):\n dialog = Gtk.FileChooserDialog(\n title=\"Save Template File\", \n action=Gtk.FileChooserAction.SAVE,\n parent=self.window\n )\n dialog.add_buttons(\n Gtk.STOCK_CANCEL,\n Gtk.ResponseType.CANCEL,\n Gtk.STOCK_SAVE,\n Gtk.ResponseType.ACCEPT,\n )\n dialog.set_do_overwrite_confirmation(True)\n dialog.run()\n templateFile = dialog.get_filename()\n dialog.destroy()\n\n if templateFile is None:\n return\n if not templateFile.endswith('.temp'):\n templateFile = templateFile + '.temp'\n\n template = {\n 'marker_size': self.markerSizeSpinButton.get_value(),\n 'marker_color': self.markerColorHex,\n 'uav_size': self.UAVsizeSpinButton.get_value(),\n 'polygon_color': self.polygonColorHex,\n 'polygon_opacity': self.polygonOpacityAdjustment.get_value()\n }\n with open(templateFile, 'w') as f:\n f.write( json.dumps(template, indent=4) )\n\n\n def destroy(self, *args):\n Gtk.main_quit(*args)\n\n def run(self):\n if not self.js_loaded:\n print(\"Warning: Map was not successfully loaded, please restart map\")\n return 1\n if 'red' in self.UAVpositions:\n self.set_UAV_position('red', self.UAVpositions['red'])\n if 'green' in self.UAVpositions:\n self.set_UAV_position('green', self.UAVpositions['green'])\n if 'blue' in self.UAVpositions:\n self.set_UAV_position('blue', self.UAVpositions['blue'])\n return 1\n\n\nif __name__ == \"__main__\":\n app = MapApp()\n # app.start()\n GLib.timeout_add(100, app.run)\n Gtk.main()\n # while(app.is_alive()):\n # sleep(1)\n\n# builder.connect_signals(Handler()) --> handlers = {\"onDestroy\": Gtk.main_quit \\n ...}\n## To disallow editing the webpage. \n# mapHolder.set_editable(True)","sub_path":"scripts/map_glade.py","file_name":"map_glade.py","file_ext":"py","file_size_in_byte":32847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"2969365","text":"import json\nimport requests\nfrom flask import request\nfrom app.models.base import db\nfrom app.models.wx_user import WxUser\nfrom utils import log, black_list\n\n\nclass WxUserViewModel:\n\n def __init__(self):\n self.xnjd = {\n 'appid': 'wx3d24fe5cf403823a',\n 'secret': '6c81d88a062fb6bcd7155bc16dd5acd8'\n }\n self.scsd = {\n 'appid': 'wx5f40198c782e865b',\n 'secret': '1343a83fa60222e6c927c7669822bb0d'\n }\n self.scdx = {\n 'appid': 'wxae01f112939fbfe5',\n 'secret': 'fe08d6eb833b2bce19968e9352f2a526'\n }\n\n self.zjcm = {\n 'appid': 'wxae01f112939fbfe5',\n 'secret': 'fe08d6eb833b2bce19968e9352f2a526'\n }\n\n def get_openid(self, college):\n resp = {'code': 200, 'msg': '操作成功', 'data': {}}\n req = request.values\n code = req['code'] if 'code' in req else ''\n if not code or len(code) < 1:\n resp['code'] = -1\n resp['msg'] = '需要code'\n log('获取个人信息时,无有效code')\n return resp\n\n url = \"https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code\" % \\\n (college['appid'], college['secret'], code)\n r = requests.get(url)\n res = json.loads(r.text)\n\n user = WxUser()\n user_data = {\n 'nickname': req['nickName'],\n 'gender': req['gender'],\n 'avatar_url': req['avatarUrl'],\n 'city': req['city'],\n 'province': req['province'],\n 'session_key': res['session_key'],\n 'openid': res['openid'],\n }\n\n wx_user = WxUser.query.filter_by(openid=user_data['openid']).first()\n if wx_user:\n with db.auto_commit():\n wx_user.setattr(user_data)\n else:\n with db.auto_commit():\n user.setattr(user_data)\n db.session.add(user)\n exce = ['gender', 'session_key', 'city', 'province']\n user_info = black_list(user_data, exce)\n resp['data'] = user_info\n return resp\n\n def main(self, college):\n if college == '西南交通大学':\n data = self.get_openid(self.xnjd)\n return data\n elif college == '四川大学':\n data = self.get_openid(self.scdx)\n return data\n elif college == '四川师范大学':\n data = self.get_openid(self.scsd)\n return data\n elif college == '浙江传媒学院':\n data = self.get_openid(self.zjcm)\n return data\n","sub_path":"app/view_models/wx_user.py","file_name":"wx_user.py","file_ext":"py","file_size_in_byte":2639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"135171257","text":"from django.conf.urls import patterns, url\n\n\n## Note in regex - the 'P' before the is a Parameter\n\nurlpatterns = patterns(\n\n 'myblog.views',\n\n url(r'^$',\n 'list_view',\n name=\"blog_index\"),\n url(r'^posts/(?P\\d+)/$',\n 'detail_view',\n name=\"blog_detail\"),\n\n url(r'^categories/$',\n 'categories_view',\n name=\"blog_categories\"),\n url(r'^category/(?P\\d+)/$',\n 'category_view',\n name=\"blog_category\"),\n\n)\n","sub_path":"myblog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"467781564","text":"import requests\nfrom tkinter import Tk,Label,Button,Entry,Frame\nfrom random import choice\nclass Val:\n\tdef __init__(self,value=None):\n\t\tself.val=value\ndef check(word):\n\tif word.strip()=='':\n\t\treturn False,'ты пропустил(а) слово'\n\tparams = {'text':word, 'lang':'ru'}\n\tr = requests.get('http://speller.yandex.net/services/spellservice.json/checkText', params=params)\n\tif len(r.json())>0:\n\t\treturn False,'«'+[v for v in r.json()[0]['s']][0]+'»'\n\telse:\n\t\treturn True,''\nroot=Tk()\nroot.title('Составь из слова')\nscore=Val(0)\nfull=Val(choice(['теплостанция','смекалка','редактирование','подготовка','переадресация','закодирование','безупречность','покупатель','мюнгхаузен','стоматология','информация','учительница','астронавт']))\nlfl=Label(root,text='Из «'+full.val+'»')\nlfl.pack()\nlst=[full.val]\nsc=Label(root,fg='#ff0000')\nsc.pack()\nfrm=Frame(root)\nfrm.pack()\nwrd=Entry(frm)\nwrd.grid(row=1,column=1)\nout=Label(root)\nout.pack()\ndef nxt():\n\tval=wrd.get()\n\twrd.delete(0,'end')\n\twrd.insert('end',val.lower())\n\tres=check(wrd.get())\n\tif res[0]:\n\t\tfv=full.val\n\t\tfor i in wrd.get():\n\t\t\tif not i in fv:\n\t\t\t\tout.config(text=f'Нет. Нельзя «{i}»')\n\t\t\t\tbreak\n\t\t\tfv=list(fv)\n\t\t\tfv.remove(i)\n\t\t\tfv=''.join(fv)\n\t\telse:\n\t\t\tif not wrd.get() in lst:\n\t\t\t\tlst.append(wrd.get())\n\t\t\t\tscore.val+=1\n\t\t\t\tsc.config(text=score.val*'★')\n\t\t\t\tout.config(text='Да!!!')\n\t\t\telse:\n\t\t\t\tout.config(text='Уже было.')\n\telse:\n\t\tif res[1].lower()==wrd.get():\n\t\t\tout.config(text='Имена собственные запрещены!')\n\t\telse:\n\t\t\tout.config(text='Нет такого слова. Наверное, '+res[1])\nok=Button(frm,text='OK',command=nxt)\nok.grid(row=1,column=2)\nroot.mainloop()","sub_path":"word.py","file_name":"word.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"333041587","text":"'''\nCreated on Jan 20, 2014\n\n@author: fbolton\n'''\n\nimport os\nimport shutil\nimport ccms.client\nimport lxml.etree\n\n\nclass MockClient(ccms.client.CCMSClient):\n '''\n Provide a mock implementation of a Pressgang client\n '''\n\n def __init__(self):\n self.rootdir = os.path.abspath('target/mock')\n if not os.path.exists(self.rootdir + '/topics'):\n os.makedirs(self.rootdir + '/topics')\n if not os.path.exists(self.rootdir + '/images'):\n os.makedirs(self.rootdir + '/images')\n self.read_counters()\n return\n \n def write_counters(self):\n filename = self.rootdir + '/counters'\n f = open(filename, 'w')\n f.write(str(self.topicCounter) + '\\n')\n f.write(str(self.topicVersion) + '\\n')\n f.write(str(self.imageCounter) + '\\n')\n f.write(str(self.imageVersion) + '\\n')\n f.close()\n return\n \n def read_counters(self):\n filename = self.rootdir + '/counters'\n if os.path.exists(filename):\n f = open(filename, 'r')\n self.topicCounter = int(f.readline().strip())\n self.topicVersion = int(f.readline().strip())\n self.imageCounter = int(f.readline().strip())\n self.imageVersion = int(f.readline().strip())\n f.close()\n else:\n self.topicCounter = 4000\n self.topicVersion = 1000\n self.imageCounter = 5000\n self.imageVersion = 2000\n return\n\n def createTopic(self,element,title,locale,description,project,categoriesAndTags):\n content = lxml.etree.tostring(element)\n topicID = self.topicCounter\n version = self.topicVersion\n topicdir = self.rootdir + '/topics/' + str(topicID)\n os.makedirs(topicdir)\n f = open(topicdir + '/content.xml', 'w')\n f.write(content)\n f.close()\n f = open(topicdir + '/metadata', 'w')\n f.write('title = ' + title + '\\n')\n f.write('locale = ' + locale + '\\n')\n f.write('description = ' + description + '\\n')\n f.write('project = ' + project + '\\n')\n f.write('categoriesAndTags = ' + str(categoriesAndTags) + '\\n')\n f.close()\n f = open(topicdir + '/version', 'w')\n f.write(str(version) + '\\n')\n f.close()\n self.topicCounter += 1\n self.topicVersion += 1\n self.write_counters()\n # Return the tuple (topicID, version)\n return (str(topicID), str(version))\n \n def createImage(self,fileName,shortFileName,locale,description):\n imageID = self.imageCounter\n version = self.imageVersion\n splitFile = shortFileName.split('.')\n suffix = splitFile[-1]\n imagedir = self.rootdir + '/images/' + str(imageID)\n os.makedirs(imagedir)\n shutil.copyfile(fileName, imagedir + '/' + str(imageID) + '.' + suffix)\n f = open(imagedir + '/metadata', 'w')\n f.write('locale = ' + locale + '\\n')\n f.write('description = ' + description + '\\n')\n f.write('originalFileName = ' + shortFileName + '\\n')\n f.close()\n f = open(imagedir + '/version', 'w')\n f.write(str(version) + '\\n')\n f.close()\n self.imageCounter += 1\n self.imageVersion += 1\n self.write_counters()\n # Return the tuple (imageID, version, localeSpecificID, localeSpecificRev)\n return (str(imageID), str(version),str(imageID), str(version))\n\n def updateTopic(self,element,topicID,locale,revComment):\n content = lxml.etree.tostring(element)\n version = self.topicVersion\n topicdir = self.rootdir + '/topics/' + str(topicID)\n if not os.path.exists(topicdir):\n raise Exception('Tried to update non-existent topic: ' + str(topicID))\n f = open(topicdir + '/content.xml', 'w')\n f.write(content)\n f.close()\n f = open(topicdir + '/log', 'a')\n f.write(str(version) + ': ' + revComment + '\\n')\n f.close()\n f = open(topicdir + '/version', 'w')\n f.write(str(version) + '\\n')\n f.close()\n self.topicVersion += 1\n self.write_counters()\n return str(version)\n\n def updateImage(self,fileName,shortFileName,imageID,localeSpecificID,locale,revComment):\n version = self.imageVersion\n splitFile = fileName.split('.')\n suffix = splitFile[-1]\n imagedir = self.rootdir + '/images/' + str(imageID)\n if not os.path.exists(imagedir):\n raise Exception('Tried to update non-existent image: ' + str(imageID))\n shutil.copyfile(fileName, imagedir + '/' + str(imageID) + '.' + suffix)\n f = open(imagedir + '/log', 'a')\n f.write(str(version) + ': ' + revComment + '\\n')\n f.close()\n f = open(imagedir + '/version', 'w')\n f.write(str(version) + '\\n')\n f.close()\n self.imageVersion += 1\n self.write_counters()\n return (str(version),str(version))\n\n def isOlderTopicVersion(self,topicID,version,locale='en-US'):\n return False\n\n def isOlderImageVersion(self,topicID,version,locale='en-US'):\n return False\n","sub_path":"src/ccms/mock.py","file_name":"mock.py","file_ext":"py","file_size_in_byte":4644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"380032231","text":"\"\"\" for lab 4 ch.14\nresponse = input(\"Enter the string with $: \")\nfor i in range (len(response)-1, -1, -1): #method 1\n if response[i] != \"$\"\n print(response[: i + 1])\n break\n\nwhile response.endswith(\"$\"):\n response = response[:len(response)-1] #method 2\nprint(response)\n\"\"\"\n\n\"\"\"\nIF STATEMENTS:\nif 'variable' == 1:\n print('whatever')\nelif:\n print('whatever')\nelse:\n print('whatever')\n\n\"\"\"\n\"\"\"\nword = input(\"Enter a word: \")\nif word.isalpha() == True:\n print(\"The word contains only letters.\")\nif word.isupper() == True:\n print(\"All string in the word are uppercase letters.\")\nif word.islower() == True:\n print(\"All string in the word are lowercase letters.\")\nif word.isnumeric() == True:\n print(\"The word contains only digits.\")\nif word.isalnum() == True:\n print(\"The word contains either letters or numbers.\")\nif word[0].isupper() == True:\n print(\"The word starts with a capital letter.\")\nif word[-1].endswith('.') == True:\n print(\"The word ends with a period.\")\n\"\"\"\n\nuser_grade = input(\"Enter a letter grade: \").capitalize()\nif user_grade[0] == 'A':\n numericValue = 4.0\nelif user_grade[0] == 'B':\n numericValue = 3.0\nelif user_grade[0] == 'C':\n numericValue = 2.0\nelif user_grade[0] == 'D':\n numericValue = 1.0\nelif user_grade[0] == 'F':\n numericValue = 0.0\n\nif numericValue != 0.0:\n if len(user_grade) == 2:\n if user_grade[1] == '+' and numericValue != 4.0:\n numericValue = numericValue + 0.3\n elif user_grade[1] == '-':\n numericValue = numericValue - 0.3\n\nprint(\"The numeric value is\", numericValue)\n\n","sub_path":"python/notes/dates/091019.py","file_name":"091019.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"57137275","text":"from mythic_payloadtype_container.MythicCommandBase import *\nfrom mythic_payloadtype_container.MythicRPC import *\n\nclass InstallPkgArguments(TaskArguments):\n def __init__(self, command_line):\n super().__init__(command_line)\n self.args = {\n \"file\": CommandParameter(\n name=\"file\", type=ParameterType.File, description=\"Pkg to install, must be signed. Can use the TLS cert of the MDM server.\"\n )\n }\n\n async def parse_arguments(self):\n if len(self.command_line) > 0:\n if self.command_line[0] == \"{\":\n self.load_args_from_json_string(self.command_line)\n else:\n raise ValueError(\"Missing JSON arguments\")\n else:\n raise ValueError(\"Missing arguments\")\n\n\nclass InstallPkgCommand(CommandBase):\n cmd = \"install_pkg\"\n needs_admin = False\n help_cmd = \"install_pkg\"\n description = \"Installs a pkg on the device. The pkg must be signed with the SSL cert of the mdm web server.\"\n version = 1\n is_exit = False\n is_file_browse = False\n is_process_list = False\n is_download_file = False\n is_remove_file = False\n is_upload_file = True\n author = \"@rookuu\"\n argument_class = InstallPkgArguments\n attackmapping = []\n\n async def create_tasking(self, task: MythicTask) -> MythicTask:\n original_file_name = json.loads(task.original_params)[\"file\"]\n\n file_resp = await MythicRPC().execute(\"create_file\", task_id=task.id,\n file=base64.b64encode(task.args.get_arg(\"file\")).decode(),\n saved_file_name=original_file_name,\n delete_after_fetch=True,\n )\n \n if file_resp.status != MythicStatus.Success:\n raise Exception(\"Error from Mythic: \" + response.error_message)\n\n return task\n\n async def process_response(self, response: AgentResponse):\n pass","sub_path":"Payload_Type/orthrus/mythic/agent_functions/install_pkg.py","file_name":"install_pkg.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"221132685","text":"from collections import Counter\n\nN = int(input())\nS = input()\nc = Counter(S[1:])\nE_count = c['E']\nmin_count = E_count\n\nW_left = 0\nE_right = E_count\nfor i in range(1, N):\n if S[i - 1] == 'W':\n W_left += 1\n if S[i] == 'E':\n E_right -= 1\n if W_left + E_right < min_count:\n min_count = W_left + E_right\nprint(min_count)","sub_path":"ABC098/C_Attention.py","file_name":"C_Attention.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"101474698","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# File : core.classifiers.RCNLPTextClassifier.py\n# Description : Echo State Network for text classification.\n# Auteur : Nils Schaetti \n# Date : 01.02.2017 17:59:05\n# Lieu : Nyon, Suisse\n#\n# This file is part of the Reservoir Computing NLP Project.\n# The Reservoir Computing Memory Project is a set of free software:\n# you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Foobar 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# You should have received a copy of the GNU General Public License\n# along with Foobar. If not, see .\n#\n\nimport argparse\nimport os\nfrom shutil import copyfile\nimport logging\n\n#########################################################################\n# Experience settings\n#########################################################################\n\n####################################################\n# Main function\n####################################################\n\nif __name__ == \"__main__\":\n\n # Argument parser\n parser = argparse.ArgumentParser(description=\"RCNLP - Word prediction with Echo State Network and one-hot vector\")\n\n # Argument\n parser.add_argument(\"--dataset\", type=str, help=\"Dataset's directory\", required=True)\n parser.add_argument(\"--output\", type=str, help=\"Output directory\", required=True)\n parser.add_argument(\"--log-level\", type=int, help=\"Log level\", default=20)\n args = parser.parse_args()\n\n # Init logging\n logging.basicConfig(level=args.log_level)\n logger = logging.getLogger(name=\"RCNLP\")\n\n # For each author path\n index = 0\n for author_file in os.listdir(args.dataset):\n # Author path\n author_path = os.path.join(args.dataset, author_file)\n\n # For each author's text\n for author_text in os.listdir(author_path):\n # File path\n file_path = os.path.join(author_path, author_text)\n\n # Destination path\n destination_path = os.path.join(args.output, str(index) + \".txt\")\n\n # Copy file\n copyfile(file_path, destination_path)\n\n # Increment index\n index += 1\n # end for\n # end for\n\n# end if\n","sub_path":"flatten_reuters_dataset.py","file_name":"flatten_reuters_dataset.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"492155278","text":"import requests\nfrom lunch_orders_2_0 import settings\nfrom logging import Handler\n\nCOLOURS = {\n 'INFO': '#BDE5F8',\n 'SUCCESS': '#DFF2BF',\n 'WARNING': '#FEEFB3',\n 'ERROR': '#F35A00',\n 'CRITICAL': '#F35A00'\n}\n\n\nclass SlackLogHandler(Handler):\n def __init__(self, slack_webhook):\n Handler.__init__(self)\n self.webhook_url = slack_webhook\n\n @staticmethod\n def _build_message(record):\n payload = {\n \"text\": \"Alert from Lunch Orders and the Wasp\",\n \"attachments\": [\n {\n \"color\": COLOURS[record.levelname],\n \"fields\": [\n {\n \"title\": \"Filename:line\",\n \"value\": '{}/{}:{}'.format(record.pathname, record.filename, record.lineno)\n },\n {\n \"title\": \"module\",\n \"value\": record.module\n },\n {\n \"title\": \"Message\",\n \"value\": record.getMessage()\n }\n ]\n }\n ]\n }\n\n return payload\n\n def emit(self, record):\n # https://hooks.slack.com/services/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 # the_wasp_shit_herself\n if not settings.SLACK_NOTIFY:\n return\n\n requests.post(self.webhook_url, json=self._build_message(record))\n","sub_path":"lunch_orders/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"262354868","text":"\n\"\"\"\nДанный файл будет реализовывать запуск браузера (мозилы) \nпереход на сдо , сохранения кукисов , и сборки полной ссылки до страницы \nавторизации \n\"\"\"\n\n#!/usr/bin/env python3\nimport sys\nimport requests\nfrom selenium.webdriver.common.proxy import * # эта бибилиотека нужна ждя пуска мозилы через порт 8080\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import WebDriverException\nfrom browsermobproxy import Server, Client # попробую реализовать схему скрипт firefox->browsermobproxy->burpsuite\n\n\n#====================================================================================\nclass Config_firefox_start():\n \"\"\"\n Без этих настроек proxy firefox не запускался \n через Burpsuite т.к настройки в запускаемой копии \n firefox настраивались по умолчанию на работу без прокси .\n Заебался расшифровывать модули библиотеки selenium\n \"\"\"\n \n def __init__(self,link_url): # link_url при создании обЪекта передаю нужный адрес сайта\n self.url = link_url # link_url хранит адрес сайта который нужен для перехода\n\n \"\"\" настройка вкладки \"Сеть\" запускаемого браузера\"\"\"\n self.myProxy = \"localhost:8081\"\n self.proxy_my = Proxy({\n 'proxyType' : ProxyType.MANUAL,\n 'httpProxy' : self.myProxy,\n 'ftpProxy' : self.myProxy,\n 'sslProxy' : self.myProxy,\n 'socksProxy' : self.myProxy, \n 'noProxy' : '' # set this value as desired\n })\n \n self.profile = webdriver.FirefoxProfile()\n self.profile.set_preference(\"network.proxy.type\", 1)\n self.profile.set_preference(\"network.proxy.http\", \"localhost\")\n self.profile.set_preference(\"network.proxy.http_port\", 8081)\n self.profile.set_proxy(self.proxy_my)\n\n \"\"\"Запуск браузера с настроенными настройками(prifile)и переход на сайт\"\"\"\n self.driver = webdriver.Firefox(self.profile)\n self.driver.get(self.url)\n\n#==================================================================================\n\nclass BMP_FF():\n \"\"\"\n Класс для работы браузера Firefox через прокси browsermobproxy\n для перехвата и анализа Get запросов.\n Разобраться как удалять har\n разобраться как удалять экземпляр класса с помощью del\n \"\"\"\n \n def __init__(self):\n \"\"\"инициализация настроек браузера Firefox для работы через прокси\"\"\"\n #путь прописывать полностью от home до бинарника который скачивается отдельно не через pip install\n self.bmpproxy = Server(r'//home//sirius//project//python_sir//SBBs_sdo//lib//python3.5//site-packages//browsermob-proxy//bin//browsermob-proxy',{'port':8082}) # указываю путь к бинарнику и на каком порту слушать трафик\n self.bmpproxy.start() # start browsermobproxy\n self.bmp_port = self.bmpproxy.create_proxy() # назначение порта неизвестно\n self.resp = requests.post('http://localhost:8082/proxy',{}) # отправляю запрос для получения №порта на котором поднял проксик browsermobproxy\n self.browser_port = self.resp.json()['port'] # через этот порт работает браузер\n self.port_ff_net = 'localhost:' + str(self.browser_port) # получаю строку типа \"localhost : 8082\"\n\n self.proxy_my_ff = Proxy({\n 'proxyType' : ProxyType.MANUAL,\n 'httpProxy' : self.port_ff_net,\n 'ftpProxy' : self.port_ff_net,\n 'sslProxy' : self.port_ff_net,\n 'socksProxy': self.port_ff_net,\n 'noProxy' : ''\n })\n self.profile = webdriver.FirefoxProfile()\n self.profile.set_preference(\"network.proxy.type\" , 1)\n self.profile.set_preference(\"network.proxy.http\" , \"localhost\")\n self.profile.set_preference(\"network.proxy.http_port\" , self.browser_port) \n self.profile.set_proxy(self.proxy_my_ff)\n\n\n\n def start_firefox_url(self,site_url): #site_url адрес нужного сайта\n \"\"\"метод вызова браузера с заданными настройками прокси в\n методе __init__ и переход на заданный адрес сайта\"\"\"\n try:\n self.url = 'http://www.' + site_url\n self.driver = webdriver.Firefox(self.profile)\n self.resp= requests.put('http://localhost:8082/proxy/' + str(self.browser_port) + '/har', {\"initialPageRef\": \"\"})# начинаю сессию мониторинга\n self.driver.get(self.url)\n self.resp = requests.get('http://localhost:8082/proxy/' + str(self.browser_port) + '/har') #read data in har\n sys.stdout.write('порт прокси браузера = ' + str(self.browser_port) + '\\n' + 'порт для har = ' + str(self.browser_port) + '\\n' )\n\n except WebDriverException as err:\n print('отработало исключение в методе start_firefox_url')\n self.bmp_stop()\n print('объект уничтожен')\n\n def start_data_proxy(self):\n \"\"\"метод выводит какие данные прошли через прокси bmpproxy\"\"\"\n self.resp_har = requests.put('http://localhost:8082/proxy/' + str(self.bmp_port.port) + '/har', {\"initialPageRef\": \"\"})# начинаю сессию мониторинга\n def read_data_proxy(self):\n self.resp = requests.get('http://localhost:8082/proxy/' + str(self.bmp_port.port) + '/har')\n self.resp.content\n self.resp.json()\n \n def bmp_stop(self):\n \"\"\"метод отстановки browsermobproxy но порты почему то заняты остаются (((\"\"\"\n self.bmpproxy.stop()\n sys.stdout.write('brouwsermobproxy остановлен, объект уничтожен' + '\\n')\n#======================================================================================\nclass BMP_FF_getRequests(BMP_FF):\n \"\"\"\n данный класс будет уметь обрабатывать Get request\n \"\"\"\n pass\n \n\n\n\n\n#=====================================================================================\nclass Working_coockies(Config_firefox_start):\n \"\"\"\n Этот класс является потомком класса Config_firefox_start()\n класс работает с куками, но проблема в перехвате GET запросов\n для перехвата страницы, которая нужна для парсинга ссылки на \n страницу авторизации. Для перехвата GET запросов нужно попробовать \n использовать библиотеку BrowserMob Proxy и тогда схема коннекта \n скрипта ffstart.py будет выглядеть следующим образом - класс Config_firefox_start()\n будет конектится к прокси BrowserMob Proxy а BrowserMob Prox к Burpsuite для визуального\n отображения процесса. При установке Browsermobproxy импортировать сертификаты ssl в браузер который будет использоваться классом Working_coockies()\n \"\"\"\n def site_cookie(self):\n try:\n self.cookie = {\"name\": \"key\",\"value\":\"value\" , \"path\" : \"/\"}\n self.driver.add_cookie(self.cookie)\n self.all_cookies = self.driver.get_cookies()\n print(self.all_cookies)\n except:\n print('что пошло не так в классе Working_cookies')\n\n\n#===================================================================================\n\n\nclass BMP_FF_Working_coockies(BMP_FF):\n \"\"\"\n Этот класс является потомком класса BMP_FF()\n класс работает с куками, но проблема в перехвате GET запросов\n для перехвата страницы, которая нужна для парсинга ссылки на \n страницу авторизации. Для перехвата GET запросов нужно попробовать \n использовать библиотеку BrowserMob Proxy и тогда схема коннекта \n скрипта ffstart.py будет выглядеть следующим образом - класс Config_firefox_start()\n будет конектится к прокси BrowserMob Proxy а BrowserMob Prox к Burpsuite для визуального\n отображения процесса. При установке Browsermobproxy импортировать сертификаты ssl в браузер который будет использоваться классом Working_coockies()\n \"\"\"\n def site_cookie(self):\n try:\n self.cookie = {\"name\": \"key\",\"value\":\"value\" , \"path\" : \"/\"}\n self.driver.add_cookie(self.cookie)\n self.all_cookies = self.driver.get_cookies()\n print(self.all_cookies)\n except:\n print('что пошло не так в классе BMP_FF_Working_cookies')\n\n#==================================================================================\n\nif __name__ == '__main__':\n A = BMP_FF()\n A.start_firefox_url('google.ru')\n A.bmp_stop()\n\n B = BMP_FF()\n B.start_firefox_url('vk.com')\n B.bmp_stop()\n# pdb.set_trace()\n# A = Working_coockies('http://www.sdo.rzd.ru/lms')\n# A.site_cookie()\n\n#=================================================================================\n\n \"\"\"\n План:\n \n 1) настроить схему выхода в сеть : firefox ->(port) -> browsermob-proxy -> (port) -> Burpsuite -> net\n\n \"\"\" \n\"\"\" \n proxy.new_har(\"google\")\n print(proxy.har)\n# print(resp.content) # информация о приложении слушающее порт \n# client = Client(r'//home//sirius//project//python_sir//SBBs_sdo//lib//python3.5//site-packages//browsermob-proxy//bin//browsermob-proxy',{'port':8082})\n# client.Har()\n# client.port\n# client.new_har('google')\n# client.har\n\n\"\"\"\n","sub_path":"ffstart.py","file_name":"ffstart.py","file_ext":"py","file_size_in_byte":11243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"39635633","text":"# обычный 'while'\na = 1\nwhile a <= 10:\n print(a ** 2)\n a += 1\n\n# по окончанию 'while' выполнится блок 'else'\ni = 1\nwhile i <= 10:\n print(i)\n i += 1\nelse:\n print('Цикл окончен, i =', i)","sub_path":"While.py","file_name":"While.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"653723609","text":"from flask_restplus import Namespace, Resource\n\nfrom willstores.service import ProductService\nfrom willstores.util import Marshalling\nfrom willstores.controller import ErrorHandler\n\nstartAPI = Namespace(\"Start\", description=\"Store initial operations.\", url_prefix=\"/start\")\n\nmarshalling = Marshalling(startAPI)\n\nOUTCOUNTMODEL = marshalling.out_countmodel(\"Count\")\n\n\n@startAPI.route(\"/\", strict_slashes=False)\nclass StartController(Resource):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.__productservice = ProductService()\n\n @startAPI.marshal_with(OUTCOUNTMODEL, description=\"Provides initial information about the store.\", mask=False)\n def get(self):\n \"\"\"Total products registered.\"\"\"\n try:\n numproducts = self.__productservice.num_products()\n return {\"count\": numproducts}\n except Exception as error:\n return ErrorHandler(error).handle_error()\n","sub_path":"willstores/willstores/controller/apis/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"374272791","text":"#!/usr/bin/env python\nimport tkinter as tk\n\n#imports\nfrom tkinter import ttk \nfrom tkinter import scrolledtext\nfrom tkinter import Menu\nfrom tkinter import Spinbox\nfrom tkinter import messagebox\n\n#由于tkinter中没有ToolTip功能,自定义如下\nclass ToolTip(object):\n def __init__(self, widget):\n self.widget = widget\n self.tipwindow = None\n self.id = None\n self.x = self.y = 0\n\n def showtip(self, text):\n \"Display text in tooltip window\"\n self.text = text \n if self.tipwindow or not self.text:\n return\n x,y,_cx,cy = self.widget.bbox('insert')\n x = x + self.widget.winfo_rootx() + 27\n y = y + cy + self.widget.winfo_rooty() + 27\n self.tipwindow = tw = tk.Toplevel(self.widget)\n tw.wm_overrideredirect(1)\n tw.wm_geometry(\"+%d+%d\" %(x, y))\n\n label = tk.Label(tw, text=self.text, justify=tk.LEFT, background=\"#ffffe0\",\n relief=tk.SOLID, borderwidth=1, font=(\"tahoma\",\"8\",\"normal\"))\n label.pack(ipadx=1)\n \n def hidetip(self):\n tw = self.tipwindow\n self.tipwindow = None\n if tw:\n tw.destroy()\n\n\ndef createToolTip(widget, text):\n toolTip = ToolTip(widget)\n def enter(event):\n toolTip.showtip(text)\n def leave(event):\n toolTip.hidetip()\n widget.bind('', enter)\n widget.bind('', leave)\n\n#create instance\nroot = tk.Tk()\nroot.title(\"Python 图形用户界面\")\n#disable resizing the GUI\nroot.resizable(0, 0)\n\n#Tab Control\n\n#create tab control\ntabControl = ttk.Notebook(root)\n\n#create the first tab and add the tab\ntab1 = ttk.Frame(tabControl)\ntabControl.add(tab1, text='第一页')\n#create the second tab and add the tab\ntab2 = ttk.Frame(tabControl)\ntabControl.add(tab2, text='第二页')\n#create the third tab and add the tab\ntab3 = ttk.Frame(tabControl)\ntabControl.add(tab3, text='第三页')\n\n#pack to make visible\ntabControl.pack(expand=1, fill=\"both\")\n\n#Tab1 控件介绍\n#we are creating a container tab3 to hold all other widgets\nmonty = ttk.LabelFrame(tab1, text = '控件示范区1')\nmonty.grid(column = 0, row = 0, padx = 8, pady = 4)\n#modified button click function\ndef clickMe():\n action.configure(text = 'Hello\\n' + name.get())\n action.configure(state = 'disabled')\n\n#changing our label\nttk.Label(monty, text = '输入文字:').grid(column = 0, row = 0, sticky = 'W')\n#adding a Textbox Entry widget\nname = tk.StringVar()\nnameEntered = ttk.Entry(monty, width = 12, textvariable = name)\nnameEntered.grid(column = 0, row = 1, sticky = 'W')\n\n#adding a button\naction = ttk.Button(monty, text = '点击之后\\n按钮失效', width = 10, command = clickMe)\naction.grid(column = 2, row = 1, rowspan = 2, ipady = 7)\n\n\nttk.Label(monty, text = '请选择一本书:').grid(column = 1, row = 0, sticky = 'W')\n#add a combobox\nbook = tk.StringVar()\nbookChosen = ttk.Combobox(monty, width = 12, textvariable = book)\nbookChosen['values'] = ('平凡的世界', '亲爱的安德鲁', '看见', '白夜行')\nbookChosen.grid(column = 1, row = 1)\nbookChosen.current(0) #设置初识显示值\nbookChosen.config(state = 'readonly')\n\n#spinbox callback\ndef _spin():\n value = spin.get()\n #print(value)\n scr.insert(tk.INSERT, value + '\\n')\n\ndef _spin2():\n value = spin2.get()\n scr.insert(tk.INSERT, value + '\\n')\n\n#add 2 spinbox widget using a set of values\nspin = Spinbox(monty, from_ = 10, to = 25, width = 5, bd = 8, command = _spin)\nspin.grid(column = 0, row = 2)\n\nspin2 = Spinbox(monty, values = ('Python3入门', 'C语言', 'C++', \"Java\", 'OpenCV'), width = 13, bd = 3, command = _spin2)\nspin2.grid(column = 1, row = 2, sticky = 'W')\n\n#using a scrolled text control\nscrolW = 30; scrolH = 5\nscr = scrolledtext.ScrolledText(monty, width = scrolW, height = scrolH, wrap = tk.WORD)\nscr.grid(column = 0, row = 3, sticky = 'WE', columnspan = 3)\n\n#add tooltip\ncreateToolTip(spin, '这是一个Spinbox')\ncreateToolTip(spin2, '这是一个Spinbox')\ncreateToolTip(action, '这是一个Button')\ncreateToolTip(nameEntered, '这是一个Entry')\ncreateToolTip(bookChosen, '这是一个Combobox')\ncreateToolTip(scr, '这是一个ScrolledText')\n\n#一次性控制各控件之间的距离\nfor child in monty.winfo_children():\n child.grid_configure(padx = 3, pady = 1)\n\n\naction.grid(column = 2, row = 1, rowspan = 2, padx = 6)\n#end\n\n#Tab2 控件介绍\nmonty2 = ttk.LabelFrame(tab2, text = '控件示范区2')\nmonty2.grid(column = 0, row = 0, padx = 8, pady = 4)\n#create three checkbuttons\nchVarDis = tk.IntVar()\ncheck1 = tk.Checkbutton(monty2, text = '失效选项', variable = chVarDis, state = 'disabled')\ncheck1.select()\ncheck1.grid(column = 0, row = 0, sticky = tk.W)\n\nchVarUn = tk.IntVar()\ncheck2 = tk.Checkbutton(monty2, text = '遵从内心', variable = chVarUn)\ncheck2.deselect()\ncheck2.grid(column = 1, row = 0, sticky = tk.W)\n\nchVarEn = tk.IntVar()\ncheck3 = tk.Checkbutton(monty2, text = '屈于现实', variable = chVarEn)\ncheck3.deselect()\ncheck3.grid(column = 2, row = 0, sticky = tk.W)\n\n#GUI Callback function\ndef checkCallback(*ignoredArgs):\n #only enable one checkbutton\n if chVarUn.get() :\n check3.configure(state = 'disabled')\n else:\n check3.configure(state = 'normal')\n if chVarEn.get() :\n check2.configure(state = 'disabled')\n else:\n check2.configure(state = 'normal')\n\n#trace the state of the two checkbuttons\nchVarUn.trace('w', lambda unused0, unused1, unused2 : checkCallback())\nchVarEn.trace('w', lambda unused0, unused1, unused2 : checkCallback())\n\n#radiobutton list\nvalues = [\"富强民主\", \"文明和谐\", \"自由平等\", \"公正法治\", \"爱国敬业\", \"诚信友善\"]\n#radiobutton callback\ndef radbtnCallback():\n radSel = radVar.get()\n if radSel == 0 : monty2.configure(text = '富强民主')\n elif radSel == 1 : monty2.configure(text = '文明和谐')\n elif radSel == 2 : monty2.configure(text = '自由平等')\n elif radSel == 3 : monty2.configure(text = '公正法治')\n elif radSel == 4 : monty2.configure(text = '爱国敬业')\n elif radSel == 5 : monty2.configure(text = '诚信友善')\n\n\n#create three radiobutton using one variable\nradVar = tk.IntVar()\nradVar.set(99)\n#create all three radiobutton widgets within one loop\nfor col in range(4):\n curRad = tk.Radiobutton(monty2, text = values[col], variable = radVar, value = col, command = radbtnCallback)\n curRad.grid(column = col, row = 6, sticky = tk.W, columnspan = 3)\nfor col in range(4, 6):\n curRad = tk.Radiobutton(monty2, text = values[col], variable = radVar, value = col, command = radbtnCallback)\n curRad.grid(column = col - 4, row = 7, sticky = tk.W, columnspan = 3)\n\nstyle = ttk.Style()\nstyle.configure(\"BW.TLable\", font = (\"Times\", \"10\", \"Bold\"))\nttk.Label(monty2, text = '社会主义核心价值观', style = \"BW.TLabel\").grid(column = 2, row = 7, columnspan = 2, sticky = tk.EW)\n\n#create a container to hold labels\nlabelsFrame = ttk.LabelFrame(monty2, text = '嵌套区域')\nlabelsFrame.grid(column = 0, row = 8, columnspan = 4)\n#place labels into the container element\nttk.Label(labelsFrame, text = '你才25岁,你可以成为任何你想成为的人').grid(column = 0, row = 0)\nttk.Label(labelsFrame, text = '不要在乎一城一池的得失,要执着').grid(column = 0, row = 1, sticky = tk.W)\n\n#add some space around each label\nfor child in labelsFrame.winfo_children():\n child.grid_configure(padx = 8, pady = 4)\n\n#end\n\n#Tab3\ntab3 = tk.Frame(tab3, bg = '#AFEEEE')\ntab3.pack()\nfor i in range(2):\n canvas = 'canvas' + str(col)\n canvas = tk.Canvas(tab3, width = 162, height = 95, highlightthickness = 0, bg = '#FFFF00')\n canvas.grid(row = i, column = i)\n#end\n\n#==============================菜单栏介绍========================\n#Exit GUI cleanly\ndef _quit():\n root.quit()\n root.destroy()\n exit()\n\n#create a menu bar\nmenuBar = Menu(root)\nroot.config(menu = menuBar)\n#add menu items\nfileMenu = Menu(menuBar, tearoff = 0)\nfileMenu.add_command(label = '新建')\nfileMenu.add_separator()\nfileMenu.add_command(label = '退出', command = _quit)\nmenuBar.add_cascade(label = '文件', menu = fileMenu)\n\n#display a message box\ndef _msgBox1():\n messagebox.showinfo('Python Message Info Box', '通知:程序运行正常')\ndef _msgBox2():\n messagebox.showwarning('Python Message Warning Box', '警告:程序出现错误,请检查')\ndef _msgBox3():\n messagebox.showwarning('Python Message Error Box', '错误:程序出现严重错误')\ndef _msgBox4():\n answer = messagebox.askyesno('Python Message Dual Choice Box', '你喜欢这篇文章吗\\n选择是:')\n if answer == True:\n messagebox.showinfo('显示选择结果', '选择了是,谢谢参与')\n else:\n messagebox.showinfo('显示选择结果', '选择了否,谢谢参与')\n\n\nmsgMenu = Menu(menuBar, tearoff = 0)\nmsgMenu.add_command(label = '通知 Box', command = _msgBox1)\nmsgMenu.add_command(label = '警告 Box', command = _msgBox2)\nmsgMenu.add_command(label = '错误 Box', command = _msgBox3)\nmsgMenu.add_separator()\nmsgMenu.add_command(label = '判断对话框', command = _msgBox4)\nmenuBar.add_cascade(label = '消息框', menu = msgMenu)\n\n#end\nnameEntered.focus()\n\n#start GUI\nroot.mainloop()","sub_path":"core_python/tkinter/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":9246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"569783378","text":"from __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport json\n\n\n__all__ = ['DataDecoder', 'DataEncoder']\n\n\ndef cls_from_dtype(dtype):\n \"\"\"Get the class object corresponding to a COMPAS data type specification.\n\n Parameters\n ----------\n dtype : str\n The data type of the COMPAS object in the following format:\n '{}/{}'.format(o.__class__.__module__, o.__class__.__name__).\n\n Returns\n -------\n :class:`compas.base.Base`\n\n Raises\n ------\n ValueError\n If the data type is not in the correct format.\n ImportError\n If the module can't be imported.\n AttributeError\n If the module doesn't contain the specified data type.\n\n \"\"\"\n mod_name, attr_name = dtype.split('/')\n module = __import__(mod_name, fromlist=[attr_name])\n return getattr(module, attr_name)\n\n\nclass DecoderError(Exception):\n pass\n\n\nclass DataEncoder(json.JSONEncoder):\n \"\"\"Data encoder for custom JSON serialisation with support for COMPAS data structures and geometric primitives.\n\n Notes\n -----\n In the context of Remote Procedure Calls,\n\n \"\"\"\n\n def default(self, o):\n if hasattr(o, 'to_data'):\n value = o.to_data()\n return {\n 'dtype': \"{}/{}\".format(\".\".join(o.__class__.__module__.split(\".\")[:-1]), o.__class__.__name__),\n 'value': value\n }\n\n if hasattr(o, '__next__'):\n return list(o)\n\n try:\n import numpy as np\n except ImportError:\n pass\n else:\n if isinstance(o, np.ndarray):\n return o.tolist()\n if isinstance(o, (np.int32, np.int64)):\n return int(o)\n if isinstance(o, (np.float32, np.float64)):\n return float(o)\n\n elif isinstance(o, (np.int_, np.intc, np.intp, np.int8,\n np.int16, np.int32, np.int64, np.uint8,\n np.uint16, np.uint32, np.uint64)):\n return int(o)\n\n elif isinstance(o, (np.float_, np.float16, np.float32, np.float64)):\n return float(o)\n\n elif isinstance(o, np.bool_):\n return bool(o)\n\n elif isinstance(o, np.void):\n return None\n\n return super(DataEncoder, self).default(o)\n\n\nclass DataDecoder(json.JSONDecoder):\n \"\"\"Data decoder for custom JSON serialisation with support for COMPAS data structures and geometric primitives.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super(DataDecoder, self).__init__(object_hook=self.object_hook, *args, **kwargs)\n\n def object_hook(self, o):\n if 'dtype' not in o:\n return o\n\n try:\n cls = cls_from_dtype(o['dtype'])\n\n except ValueError:\n raise DecoderError(\"The data type of the object should be in the following format: '{}/{}'.format(o.__class__.__module__, o.__class__.__name__)\")\n\n except ImportError:\n raise DecoderError(\"The module of the data type can't be found.\")\n\n except AttributeError:\n raise DecoderError(\"The data type can't be found in the specified module.\")\n\n return cls.from_data(o['value'])\n\n\n# ==============================================================================\n# Main\n# ==============================================================================\n\nif __name__ == '__main__':\n pass\n","sub_path":"src/compas/utilities/encoders.py","file_name":"encoders.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"582213651","text":"# Tipos de Dados\n\n# Tipo de dado (nomenclatura do Python)\n\n# Inteiros (int)\n# Números inteiros, sejam positivos ou não.\n\nint1 = 3\nint2 = 42\n\n# Suporta operações como multiplicação e soma.\n\n# Reais (float)\n# Números Reais\n\nfl1 = 3.14\nfl2 = 6.9\n\n# Suporta operações como multiplicação e soma.\n\n\n# Strings (str)\n# Cadeia de caractéres.\n# A ordem importa.\n# Podem ser aspas simples ou duplas.\n# Caractér de escape: \"\\n\"\n\ns1 = \"Olá mundo1.\"\ns2 = 'Oi mundo1, fala comigo.'\n\n# Manuseando strings\n# Podemos acessar elementos da string (caractéres) com os índices.\ns1[0]\n# Retorna 'O'\ns2[-1]\n# Retorna '.'\ns2[2]\n# Retorna ' '\ns2.upper() # Retornar a string toda em maiúscula\ns1.lower() # Retornar a string toda em minúscula\ns1.isascii() # Retorna True se a string for toda códigos ASCII \n\n\n# Boolean (bool)\n# Testes de condições\n\nbool1 = True\nbool2 = False\n\n# Trabalhando com booleans (Algebra booleana)\n\n(True and True)\n# Retorna True\n(True and False)\n# Retorna False\n(True or False)\n# Retorna True\n(False or True)\n# Retorna True\n\n\n# Listas (list)\n# Conjunto mutável de objetos.\n# A ordem importa.\n\nlist1 = [42, int2, \"Olá mundo2.\", bool1]\nlist2 = []\n\nlist1[0] # Retorna o primeiro item da lista\n# Retorna 42\nlist1[3] # Retorna o quarto item da lista\n# Retorna bool1\nlist1[-1] # Retorna último item da lista\n# Retorna bool1\nlist1[-3] # Retorna o antepenúltimo item da lista\n# Retorna int2\n\n# Manuseando listas:\nlist1.append(\"42\") # Adiciona um item ao final da lista\nlist1.pop(-1) # Retorna e remove o último item\nlist1.reverse() # Inverte a lista\nlist1[0] = 44\n# Altera o item list1[0] (42) para 44\n\n# Slicing de lista\n# Recorte de uma lista onde o primeiro índice é intervalo fechado e o último, aberto.\nlist1[0:2] # Igual a list1[:2]\n# Retorna [42, int2]\nlist1[1:]\n# Retorna [int2, \"Olá mundo2.\", bool1]\n\n# Tuplas (tuple)\n# Conjunto imutável de objetos.\n# A ordem importa.\n# Também suporta slicing.\n\nt1 = (4.6, 5.0)\nt2 = ('André', 'Pitas')\n\n# Acessamos o conteúdo das tuplas da mesma maneira que acessamos listas ou strings\nt1[0] \n# Retorna 4.6\n\n\n# Dicionários (dic)\n# Conjunto de elementos identificados por um valor chave.\n\na = dict(one=1, two=2, three=3)\nb = {'one': 1, 'two': 2, 'three': 3}\nc = dict(zip(['one', 'two', 'three'], [1, 2, 3]))\nd = dict([('two', 2), ('one', 1), ('three', 3)])\ne = dict({'three': 3, 'one': 1, 'two': 2})\na == b == c == d == e\n# Retorna True\n\nd1 = {'inerte': \"Algo que não se move por conta própria\", 'dole': \"gay\" }\nd['dole']\n# Retorna 'gay'# Retornar a string toda em maiúscula\n\n# Acessando valores de um dicionário\na['one']\n# Retorna 1","sub_path":"datatypes.py","file_name":"datatypes.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"249754709","text":"#Module 6, Part 5: Practice with dictionaries here\n\n\nmy_phonebook={\n \"Statue of Liberty\":2125555555,\n \"Ghostbusters\":2125551234\n }\nnum = my_phonebook[\"Statue of Liberty\"]\nprint(num)\nmy_phonebook[\"Ghostbusters\"] = 2125559876\nprint(my_phonebook[\"Ghostbusters\"])\n\n###\n#Assign the value of the Statue of Liberty's phone number to the variable, num\n###\n\n###\n#Print the variable, num\n###\n\n###\n#Change the value of the Ghostbusters' phone number to 2125559876\n###\n\n#Here's an empty dictionary\nyour_phonebook={}\nyour_phonebook['hi'] = \"hello\"\nyour_phonebook['bye'] = \"goodbye\"\nyour_phonebook['Sup'] = \"whats up\"\nyour_phonebook['Cya'] = \"Cya later aligator\"\nyour_phonebook['key'] = \"value\"\nprint(your_phonebook.keys())\nfor i in range(5):\n keys = [your_phonebook.keys()]\n print(keys[0])\n\n\n###\n#Add 5 values to it like this\n#your_phonebook['key']=value\n###\n\n###\n#Use the keys() method: your_phonebook.keys()\n#It will produce a sequence of all the keys\n\n#Loop over this sequence with a for loop\n#using syntax like\n\n#for key in sequence_of_keys :\n# #Do stuff\n\n#Use the loop to print to the shell the key and value\n#of every element in the dictionary\n###\n\n","sub_path":"dictionary_practice.py","file_name":"dictionary_practice.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"210400898","text":"\n\n#calss header\nclass _ORBITAL():\n\tdef __init__(self,): \n\t\tself.name = \"ORBITAL\"\n\t\tself.definitions = [u'relating to the orbit (= curved path) of an object in space: ', u'relating to the eye socket (= the bone around the eye)']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_orbital.py","file_name":"_orbital.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"162338176","text":"#\n# -*- coding: utf-8 -*-\n# (C) Copyright: Profound Networks, LLC 2016\n#\n\n\"\"\"Top-level package for pygeons.\"\"\"\n\nimport logging\n\n__author__ = 'Michael Penkov'\n__email__ = 'm@penkov.dev'\n__version__ = '0.9.2'\n\n_LOGGER = logging.getLogger(__name__)\n#\n# Prevent stderr message about \"no handlers found\".\n# It is possible that somebody is using Pygeon without logging.\n# https://docs.python.org/2/howto/logging.html#configuring-logging-for-a-library\n#\n_LOGGER.addHandler(logging.NullHandler())\n","sub_path":"pygeons/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"304426183","text":"import tensorflow as tf\n\n\ndef resize_image_op(image, size, subtract_mean=False, mean=None):\n \"\"\"\n :param image: image to process. 3D tensor: [image_width, image_height, 3]\n :param size: an int. The size of output image.\n :param subtract_mean: if True the mean is subtracted from the image.\n :param mean: the mean to subtract.\n\n :return: modified image\n \"\"\"\n\n image = tf.cast(image, tf.float32)\n\n # convert to float\n image = convert2float(image)\n\n # subtract mean if needed\n if subtract_mean and mean is not None:\n image = image - mean\n\n # resize the image\n image = tf.image.resize(image, [size, size])\n\n return image\n\ndef preprocess_training_op(image, label, size, subtract_mean=False, mean=None):\n \"\"\"\n Pre process training data to fit the net requirements\n\n :param image: image to process. 3D tensor: [image_width, image_height, 3]\n :param label: labels corresponding to image. 3D tensor: [image_width, image_height, 1]\n :param size: an int. The size of output image.\n :param subtract_mean: if True the mean is subtracted from the image.\n :param mean: the mean to subtract.\n :return: modified image and label\n \"\"\"\n\n image = tf.cast(image, tf.float32)\n\n # Convert to float.\n image = convert2float(image)\n\n # subtract mean if needed\n if subtract_mean and mean is not None:\n image = image - mean\n\n # Randomly scale the images and labels.\n image, label = random_image_scaling(image, label)\n\n # Randomly mirror the images and labels.\n image, label = image_mirroring(image, label)\n\n # Randomly crop image to the right size\n image, label = random_crop_and_pad_image_and_labels(image, label, size, size)\n\n return image, label\n\n\ndef preprocess_validation_op(image, label, subtract_mean=False, mean=None):\n \"\"\"\n Pre process validation data to fit the net requirements\n\n :param image: image to process. 3D tensor: [image_width, image_height, 3]\n :param label: labels corresponding to image. 3D tensor: [image_width, image_height, 1]\n :param subtract_mean: if True the mean is subtracted from the image.\n :param mean: the mean to subtract.\n :return: modified image and label\n \"\"\"\n image = tf.cast(image, tf.float32)\n image = convert2float(image)\n\n # subtract mean if needed\n if subtract_mean and mean is not None:\n image = image - mean\n\n return image, label\n\n\ndef convert2float(image):\n \"\"\"\n Transform the input image: convert to float, subtract the mean computed on the training data\n\n :param image: image to convert. 3D tensor: [image_width, image_height, 3]\n :return: modified image\n \"\"\"\n\n image = tf.image.convert_image_dtype(image, dtype=tf.float32)\n\n return image\n\n\ndef random_image_scaling(img, label):\n \"\"\"\n Randomly scales the images between 0.5 to 1.5 times the original size.\n\n :param img: image to scale. 3D tensor: [image_width, image_height, 3]\n :param label: label corresponding to image. 3D tensor: [image_width, image_height, 1]\n :return: modified image and label\n \"\"\"\n\n scale = tf.random_uniform([1], minval=0.5, maxval=1.5, dtype=tf.float32)\n\n h_new = tf.to_int32(tf.multiply(tf.to_float(tf.shape(img)[0]), scale))\n w_new = tf.to_int32(tf.multiply(tf.to_float(tf.shape(img)[1]), scale))\n\n new_shape = tf.squeeze(tf.stack([h_new, w_new]), axis=1)\n\n img = tf.image.resize_images(img, new_shape, method=tf.compat.v2.image.ResizeMethod.BILINEAR)\n\n label = tf.image.resize_images(label, new_shape, method=tf.compat.v2.image.ResizeMethod.NEAREST_NEIGHBOR)\n\n return img, label\n\n\ndef image_mirroring(img, label):\n \"\"\"\n Randomly mirror the image\n\n :param img: image to mirror. 3D tensor: [image_width, image_height, 3]\n :param label: label corresponding to image. 3D tensor: [image_width, image_height, 1]\n :return: modified image and label\n \"\"\"\n\n distort_left_right_random = tf.random_uniform([1], 0, 1.0, dtype=tf.float32)[0]\n mirror = tf.less(tf.stack([1.0, distort_left_right_random, 1.0]), 0.5)\n mirror = tf.boolean_mask([0, 1, 2], mirror)\n img = tf.reverse(img, mirror)\n label = tf.reverse(label, mirror)\n return img, label\n\n\ndef random_crop_and_pad_image_and_labels(image, label, crop_h, crop_w, ignore_label=255):\n \"\"\"\n Randomly scale and crop and pads the input images.\n\n :param image: training image to crop/ pad. 3D tensor: [image_width, image_height, 3]\n :param label: segmentation mask to crop/ pad. 3D tensor: [image_width, image_height, 1]\n :param crop_h: height of cropped segment\n :param crop_w: width of cropped segment\n :param ignore_label: label to ignore during the training\n :return: modified image and label\n \"\"\"\n\n # Pad if needed\n label = tf.cast(label, dtype=tf.float32)\n label = label - ignore_label # Needs to be subtracted and later added due to 0 padding.\n combined = tf.concat(axis=2, values=[image, label])\n image_shape = tf.shape(image)\n combined_pad = tf.image.pad_to_bounding_box(combined, 0, 0, tf.maximum(crop_h, image_shape[0]),\n tf.maximum(crop_w, image_shape[1]))\n\n last_image_dim = tf.shape(image)[-1]\n combined_crop = tf.random_crop(combined_pad, [crop_h, crop_w, 4])\n img_crop = combined_crop[:, :, :last_image_dim]\n label_crop = combined_crop[:, :, last_image_dim:]\n label_crop = label_crop + ignore_label\n label_crop = tf.cast(label_crop, dtype=tf.uint8)\n\n # Set static shape so that tensorflow knows shape at compile time.\n img_crop.set_shape((crop_h, crop_w, 3))\n label_crop.set_shape((crop_h, crop_w, 1))\n return img_crop, label_crop","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":5667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"588659709","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jun 22 10:46:58 2019\r\n\r\nCalculates HQ for sensitive receptors\r\n\r\n@author: Brian\r\n\"\"\"\r\n\r\n\r\nimport os\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom pandas import read_csv\r\nfrom pandas import ExcelWriter\r\nimport exceedances as ex\r\n\r\n#get master list of grids\r\ngrid_file = 'Discrete-Receptors.xls'\r\ngrid_df = pd.read_excel(grid_file, sheet_name='Grid')\r\n\r\n#get receptors with assigned grid locations\r\ndist_file = 'receptor_grids.xlsx'\r\ndist_df = pd.read_excel(dist_file)\r\ndist_df = dist_df.reset_index()\r\ndist_df = dist_df.drop('index', axis=1)\r\n\r\n\r\n#file paths for different runs\r\nfp1 = 'C:\\\\TARS\\AAAActive\\\\Qatar Airshed Study Jul 2017\\\\AQMIS Runs\\\\2017Run\\\\2017_all_MIC_post\\\\'\r\nfp2 = 'C:\\\\TARS\\\\AAAActive\\\\Qatar Airshed Study Jul 2017\\\\AQMIS Runs\\\\3yrCurrent\\\\3yr_current_post\\\\'\r\nfp3 = 'C:\\\\TARS\\\\AAAActive\\\\Qatar Airshed Study Jul 2017\\\\AQMIS Runs\\\\10yr-all-MIC-facilities_post\\\\'\r\n#paths = [fp1, fp2, fp3] # make filepath list\r\npaths = [fp2]\r\n\r\n#make variables of chemicals\r\nnh3 = 'NH3'; hf = '7664393'; h2s = '7783064'; nox = 'NOX'; pm10 = 'PM10-PRI';\r\nso2 = 'SO2'; voc = 'VOC';\r\nchem_type = [nh3, hf, h2s, nox, pm10, so2, voc]\r\nch = len(chem_type)\r\n\r\n#make variables of time averages\r\nhr1 = '1HR'; hr3 = '3HR'; hr24 = '24HR'; hr8760 = '8760HR'\r\n#time_ave = [hr1, hr24, hr8760]\r\ntime_ave = [hr1]\r\ntave = len(time_ave)\r\n\r\nconc_df = pd.DataFrame(grid_df.LOC_ID) # create blank dataframe to use for concatenating\r\n\r\nranklist = [] #initialize list to capture Rank column names\r\n\r\nfor chem_name in range(ch): # select chemical and loop \r\n chem = chem_type[chem_name]\r\n \r\n for i in range(len(paths)): #loop over different runs in different folders\r\n file_path = paths[i]\r\n \r\n # set variable for years of runs\r\n if file_path == fp1:\r\n yr = 1\r\n if file_path == fp2:\r\n yr = 3\r\n if file_path == fp3:\r\n yr = 10\r\n\r\n\r\n os.chdir(file_path + chem) ## set filepath and folder\r\n \r\n for t in range (tave):\r\n \r\n time = time_ave[t] #set averaging period\r\n \r\n #load data file of chemical and time average from run\r\n data_file_name = 'RANK(ALL)_' + chem + '_' + time + '_CONC_C.DAT'\r\n df = read_csv(data_file_name, engine='python', skiprows=4, sep = ' ')\r\n df = df.dropna(axis=1, how='all')\r\n \r\n chem_n = chem + '_' + time + '_' + str(yr) #create name of run\r\n \r\n #prepare input data by changing column name, adding index as column and sorting\r\n #chemical concentration from max to min (descending)\r\n df.columns = ['X_' + chem_n, 'Y_' + chem_n, chem_n, 'Lat_' + chem_n, 'Long_' + chem_n]\r\n df.drop(0, inplace=True) #remove column\r\n df = df.rename_axis('ID').reset_index()\r\n #df.sort_values(by=[chem_n], ascending = False, inplace=True)\r\n \r\n #regulatory threshold for chemical and time\r\n thresh1 = ex.mic_exceedance(chem, time)\r\n \r\n #Extract only chemical concentration from main dataframe\r\n df1 = df[[chem_n]]\r\n df1.columns = [chem_n]\r\n \r\n if thresh1 != 1.:\r\n df1 = df1/thresh1 #calculate Hazard quotient (HQ) = Ave Conc/RfC\r\n else:\r\n break\r\n \r\n conc_df = pd.concat([conc_df, df1], axis=1)\r\n\r\n#find grid rows that have the receptor locations\r\nreceptor_conc = pd.DataFrame() \r\nfor i in range(len(dist_df)):\r\n grid_desc = dist_df.Grid_dist[i]\r\n grid_conc = conc_df.query('LOC_ID == \"{0}\"'.format(grid_desc))\r\n receptor_conc = pd.concat([receptor_conc, grid_conc], axis=0)\r\n receptor_conc = receptor_conc.reset_index()\r\n receptor_conc = receptor_conc.drop('index', axis=1)\r\n\r\n#add column of receptor names \r\nreceptor_conc = pd.concat([dist_df.Receptor_ID, receptor_conc], axis=1)\r\n\r\n\r\n#select only numeric columns and convert to matrix\r\nCa_df = receptor_conc.select_dtypes(['number'])\r\nCa_names = list(Ca_df) #save column names\r\nCDI = np.round(np.asmatrix(Ca_df.values),3)\r\n\r\n\r\nCDI_df = pd.DataFrame(CDI)\r\nCDI_df.columns = Ca_names\r\nCDI_df['HQ'] = CDI_df.sum(axis=1) #sums individual column HQ for aggregated HQ\r\n\r\nCDI_df = pd.concat([dist_df.Receptor_ID, CDI_df], axis=1)\r\n\r\n# save to Excel\r\nCDI_df.to_excel(r'C:\\TARS\\AAAActive\\Qatar Airshed Study Jul 2017\\AQMIS Runs\\QRA_receptor_results.xlsx')\r\n ","sub_path":"receptors-qra.py","file_name":"receptors-qra.py","file_ext":"py","file_size_in_byte":4495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"519239226","text":"import os\nimport rasterio\nimport numpy as np\nimport pandas as pd\nfrom scipy import signal\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\n\n#identify working directory, lulc tiff, and table of lulc and species values\nwd = r'E:\\ArcGIS\\Pollinator HQT\\test'\nin_path = r'E:\\ArcGIS\\Pollinator HQT\\scratch\\LULC_test.tif'\ntable = r\"C:/Users/Erik/Downloads/Pollinator HQT - Data Tables.xlsx\"\n\n#list nesting substrates and seasons to be evaluated; must match table columns\nnest_types = ['ground', 'wood', 'stem', 'cavity']\nseasons = ['f1', 'f2', 'f3']\n\n#define cell size of input tiff\ncell_size = 30\n\n#the decay_cut value is the quantile at which the foraging distance-decay\n#curve is truncated in the caluclation\ndecay_cut = .99\n\n#define the output data type for saving rasters\ndtype = rasterio.float64\n\n##MOVE DOWN AFTER MAIN IS DEFINED\n\ndef kerncalc(beta, cell_size, decay_cut):\n radius = -(beta/cell_size) * np.log(1-decay_cut)\n matrix_rows = int(round(radius) * 2 + 1)\n matrix_columns = int(round(radius) * 2 + 1)\n kernel = np.zeros((matrix_rows, matrix_columns))\n center_row = (matrix_rows - 1) / 2\n center_column = (matrix_columns - 1) / 2\n for r in range(matrix_rows):\n for c in range(matrix_columns):\n kernel[r,c] = np.sqrt((r - center_row)**2 + (c - center_column)**2)\n reachable = kernel < radius\n kernel = np.exp(-kernel/(beta/cell_size))\n kernel = kernel/sum(sum(kernel)) * reachable\n print (\"kernel dim is \" + str(matrix_rows) + \"x\" + str(matrix_columns)\n + \" \" + str(cell_size) + \"m pixels; \" + \"radius = \" + str(round(radius,2))\n + \" pixels\") \n return kernel \n\ndef foragecalc(tiff, kernel):\n c = signal.convolve(tiff, kernel, mode = 'same', method = 'fft') \n return c\n\n \n\n#read in data tables for lulc and species, convert to dictionary\nspecies = pd.read_excel(table, \"species\")\nlulc = pd.read_excel(table, \"lulc\")\nspeciesDict = species.to_dict() #key is index, starting at 0\nlulcDict = lulc.set_index('lulc').to_dict() #key is lulc code\n\n#read in raster and save as 'array', save type and profile for use later \nwith rasterio.open(in_path) as src:\n src_types = {i: dtype for i, dtype in zip(src.indexes, src.dtypes)}\n src_profile = src.profile\n src_profile.update(dtype = dtype)\n# height = src.shape[0]\n# width = src.shape[1]\n# count = 1\n# dtype = src_types[1]\n# crs = src.crs\n array = src.read(1).astype(dtype)\n\n#calculate site-scale nesting suitability\nfor nest in nest_types:\n nest_score = np.vectorize(lulcDict[nest].get)(array)\n with rasterio.open(os.path.join(wd, \"lulc_\" + nest + \".tif\"), 'w', \n **src_profile) as out:\n out.write(nest_score.astype(dtype), 1)\n \n#calculate site-scale floral resources\nfor k in seasons:\n forage_score = np.vectorize(lulcDict[k].get)(array)\n with rasterio.open(os.path.join(wd, \"lulc_\" + k + \".tif\"), 'w',\n **src_profile) as out:\n out.write(forage_score.astype(dtype), 1)\n \n#calculate pollinator-specific nesting and forageing suitability for p \n#pollinators\nfor p in range(len(speciesDict['species'])):\n p_name = speciesDict['species'][p]\n print(p_name)\n #calculate nesting suitability\n #set up a list of arrays to store the nesting scores for n nesting \n #substrates\n nest_arrays = []\n \n #iterate through the nesting types, getting the suitability score from \n #the dictionary, opening the .tif where the nest scores are stored,\n #reading that into an array, and multiplying each value by the suitability\n #score using an anonymous 'lambda' function. \n for nest in nest_types:\n nest_suit = speciesDict[nest][p]\n with rasterio.open(os.path.join(wd, \"lulc_\" + nest + \".tif\")) as src:\n array = src.read(1)\n nest_score = np.vectorize(lambda x: x * nest_suit)(array)\n nest_arrays.append(nest_score)\n \n #select the maximum value for each overlapping cell and save output\n #in a unique file for each species\n max_nest_score = np.maximum.reduce(nest_arrays)\n \n #show the nest score\n print('visualizing nest score')\n plt.imshow(max_nest_score)\n plt.show()\n \n with rasterio.open(os.path.join(wd, p_name + \"_nest.tif\"),\n 'w', **src_profile) as out:\n out.write(max_nest_score.astype(dtype), 1) \n \n #calculate seasonal site-scale forage for p pollinators\n #(see #calculate nesting suitability)\n forage_arrays=[]\n for k in seasons:\n season_suit = speciesDict[k][p]/100\n with rasterio.open(os.path.join(wd, \"lulc_\" + k + \".tif\")) as src:\n array = src.read(1)\n forage_score = season_suit * array\n forage_arrays.append(forage_score)\n weighted_forage_score = np.add.reduce(forage_arrays)\n with rasterio.open(os.path.join(wd, p_name + \"_wforage.tif\"), \n 'w', **src_profile) as out:\n out.write(weighted_forage_score.astype(dtype), 1)\n \n #calculate foraging suitability\n #calculate kernel based on foraging distance\n alpha = speciesDict['alpha'][p]\n kernel = kerncalc(alpha, cell_size, decay_cut)\n \n #Plot the kernel\n fig = plt.figure()\n ax = fig.gca(projection = '3d')\n X = np.arange(0,kernel.shape[0])\n Y = np.arange(0,kernel.shape[1])\n X,Y = np.meshgrid(X, Y)\n Z = kernel\n ax.plot_surface(X,Y,Z, cmap = cm.bwr, linewidth = 0, \n antialiased = False)\n plt.show()\n \n #calculate foraging availability using the kernel\n forage_avail = foragecalc(weighted_forage_score, kernel)\n \n #plot output\n print(\"visualizing forage availability\")\n plt.imshow(forage_avail)\n plt.show()\n \n \n #save output\n with rasterio.open(os.path.join(wd, p_name + \"_forageAvail.tif\"), \n 'w', **src_profile) as out:\n out.write(forage_avail.astype(dtype), 1)\n \n #calculate overall pollinator suitability for p pollinators \n #multiply max_nest_score by weighted_forage_score\n p_suitability = max_nest_score/100 * forage_avail/100\n \n #save output\n with rasterio.open(os.path.join(wd, p_name + \"_suitability.tif\"), \n 'w', **src_profile) as out:\n out.write(p_suitability.astype(dtype), 1)\n \n print('visualizing suitability')\n plt.imshow(p_suitability)\n plt.show()\n print(\"---------------------------------------------------------\")\n","sub_path":"scripts/PollinatorHQT_03.py","file_name":"PollinatorHQT_03.py","file_ext":"py","file_size_in_byte":6488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"406981445","text":"### Imports and Initializations\nfrom numpy import place\nimport numpy as np\nimport pandas as pd\nfrom pandas.core.frame import DataFrame\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport boto3\nimport dash\nimport json\nfrom urllib.request import urlopen\nimport dash_html_components as html\nimport dash_core_components as dcc\nfrom dash.dependencies import Input, Output\n\nfrom flask_caching import Cache\n\nimport warnings\nwarnings.filterwarnings('ignore')\napp = dash.Dash(__name__)\ncache = Cache(app.server, config={\n 'CACHE_TYPE': 'filesystem',\n 'CACHE_DIR': 'cache-directory'\n})\nserver = app.server\nTIMEOUT = 60\ndef load_counties():\n with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:\n counties = json.load(response)\n return counties\n\n@cache.memoize(timeout=TIMEOUT)\ndef load_data():\n client = boto3.client('s3')\n \n\n ### Data: Use old ipynb from ecl\n county_geo = pd.read_csv('tl_2017_us_county.csv')\n county_geo = county_geo[['GEOID']]\n county_geo_org = county_geo.sort_values(by='GEOID')\n county_geo_org['GEOID'] = county_geo_org['GEOID'].astype('str')\n\n county_geo_org = county_geo_org.drop([1248, 1460, 81])\n\n\n path = \"s3://ecodatalab/data/\"\n ten = pd.read_csv( path + 'counties5year2010clean.csv'); ten.insert(0, 'year', 2010)\n eleven = pd.read_csv(path + 'counties5year2011clean.csv'); eleven.insert(0, 'year', 2011)\n twelve = pd.read_csv(path + 'counties5year2012clean.csv'); twelve.insert(0, 'year', 2012)\n thirteen = pd.read_csv(path + 'counties5year2013clean.csv'); thirteen.insert(0, 'year', 2013)\n fourteen = pd.read_csv(path + 'counties5year2014clean.csv'); fourteen.insert(0, 'year', 2014)\n fifteen = pd.read_csv(path + 'counties5year2015clean.csv'); fifteen.insert(0, 'year', 2015)\n sixteen = pd.read_csv(path + 'counties5year2016clean.csv'); sixteen.insert(0, 'year', 2016)\n seventeen = pd.read_csv(path + 'counties5year2017clean.csv'); seventeen.insert(0, 'year', 2017)\n frames = [ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen]\n # newdf = pd.read_csv(path + 'carbon_data_county.csv')\n\n\n\n newdf = pd.concat(frames)\n\n newdf = newdf.rename(columns={\"year\": \"YEAR\", \"Geo_NAME\":\"County Name\", \"DEGREE\":\"DEGREE\", \"MEDINCOME\":\"MEDINCOME\", \"AVGINCOME\":\"AVGINCOME\", \"OWN\":\"OWN\", \"SIZE\":\"SIZE\", \"ROOMS\":\"ROOMS\", \"VEHICLES\":\"VEHICLES\", \"Geo_FIPS\":\"GEOID\"})\n newdf['GEOID'] = newdf['GEOID'].astype(str)\n\n finaldf = county_geo_org.merge(newdf, on=['GEOID'])\n\n finaldf['GEOID'] = finaldf['GEOID'].replace(\"46102\", \"46113\")\n\n finaldf['GEOID'] = finaldf['GEOID'].replace(\"2158\", \"2270\")\n return finaldf\n\napp.layout = html.Div([\n\n html.H1(\"EcoDataLab Maps\", style={'text-align': 'center', 'margin-bottom': 10}),\n\n dcc.Slider(\n id='my_slider',\n min=2010,\n max=2017,\n step=1,\n value=2014,\n marks={\n 2010: '2010',\n 2011: '2011',\n 2012: '2012',\n 2013: '2013',\n 2014: '2014',\n 2015: '2015',\n 2016: '2016',\n 2017: '2017'\n },\n included=False\n ),\n\n dcc.Dropdown(\n id='dropdown',\n options=[\n {'label': 'Degree', 'value': 'DEGREE'},\n # {'label': 'Average Income', 'value': 'AVGINCOME'},\n # {'label': 'Median Income', 'value': 'MEDINCOME'},\n {'label': 'Rooms per Household', 'value': 'ROOMS'},\n {'label': 'Home Ownership', 'value': 'OWN'},\n {'label': 'Vehicle Ownership', 'value': 'VEHICLES'}\n ],\n value='DEGREE',\n placeholder=\"Select a variable to display on the map\"\n ),\n\n html.Div(id='output_container', children=[]),\n html.Div(id='output_container_two', children=[]),\n html.Br(),\n\n dcc.Graph(id='map', figure={}, style={'height': '100vh'})\n\n])\n\n\n### Callback\n@app.callback(\n [Output(component_id='output_container', component_property='children'),\n Output(component_id='output_container_two', component_property='children'),\n Output(component_id='map', component_property='figure')],\n [Input(component_id='my_slider', component_property='value'),\n Input(component_id='dropdown', component_property='value')]\n)\n\ndef map_value(my_slider, dropdown):\n container = \"You are currently viewing the map for : {}\".format(my_slider)\n container_two = \"You are currently mapping : {}\".format(dropdown)\n year = my_slider\n variable = dropdown\n finaldf = load_data()\n counties = load_counties()\n currdf = finaldf[finaldf['YEAR'] == year]\n # print(currdf[variable])\n currdf['GEOID'] = currdf['GEOID'].str.zfill(5)\n min_value = finaldf[variable].min()\n max_value = finaldf[variable].max()\n fig = px.choropleth(\n data_frame=currdf,\n geojson=counties,\n locations=currdf[\"GEOID\"],\n scope=\"usa\",\n color=variable,\n hover_data=['County Name', 'YEAR', variable],\n color_continuous_scale=\"Viridis\",\n labels={str(variable): variable},\n range_color = [min_value, max_value]\n )\n fig.update_layout(geo=dict(bgcolor= 'rgba(189, 222, 240, 1)', lakecolor='#BDDEF0'))\n fig.update_traces(marker_line_width=0)\n fig.update_geos(\n visible=False, resolution=110, scope=\"usa\"\n ) \n return container, container_two, fig\n\n\n### Run\nif __name__ == '__main__':\n app.run_server(debug=True)","sub_path":"app2.py","file_name":"app2.py","file_ext":"py","file_size_in_byte":5423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"499317661","text":"from teacher import PiggyParent\nimport sys\nimport time\n\nclass Piggy(PiggyParent):\n\n '''\n *************\n SYSTEM SETUP\n *************\n '''\n\n def __init__(self, addr=8, detect=True):\n PiggyParent.__init__(self) # run the parent constructor\n\n ''' \n MAGIC NUMBERS <-- where we hard-code our settings\n '''\n self.LEFT_DEFAULT = 100\n self.RIGHT_DEFAULT = 100\n self.exit_heading = 0\n self.SAFE_DIST = 300\n self.MIDPOINT = 1350 # what servo command (1000-2000) is straight forward for your bot?\n self.load_defaults()\n\n\n def load_defaults(self):\n \"\"\"Implements the magic numbers defined in constructor\"\"\"\n self.set_motor_limits(self.MOTOR_LEFT, self.LEFT_DEFAULT)\n self.set_motor_limits(self.MOTOR_RIGHT, self.RIGHT_DEFAULT)\n self.set_servo(self.SERVO_1, self.MIDPOINT)\n \n\n def menu(self):\n \"\"\"Displays menu dictionary, takes key-input and calls method\"\"\"\n ## This is a DICTIONARY, it's a list with custom index values. Python is cool.\n # Please feel free to change the menu and add options.\n print(\"\\n *** MENU ***\") \n menu = {\"n\": (\"Navigate\", self.nav),\n \"d\": (\"Dance\", self.dance),\n \"o\": (\"Obstacle count\", self.obstacle_count),\n \"h\": (\"Hold Position\", self.hold_position),\n \"v\": (\"Veer\", self.slither),\n \"c\": (\"Calibrate\", self.calibrate),\n \"q\": (\"Quit\", self.quit)\n }\n # loop and print the menu...\n for key in sorted(menu.keys()):\n print(key + \":\" + menu[key][0])\n # store the user's answer\n ans = str.lower(input(\"Your selection: \"))\n # activate the item selected\n menu.get(ans, [None, self.quit])[1]()\n\n '''\n ****************\n STUDENT PROJECTS\n ****************\n '''\n\n def dance(self):\n #highered - ordered\n # check ot see it's safe\n if not self.safe_to_dance():\n print(\"Not cool. Not going to dance\")\n return #return closes down the method\n else:\n print(\"It's safe to dance\")\n for x in range(1):\n self.dab()\n self.floss()\n self.whip()\n self.sprinkler()\n self.spin()\n self.shake()\n\n def safe_to_dance(self):\n \"\"\"does a 360 distance check and returns true if safe\"\"\"\n for x in range(4):\n for ang in range(1000, 2001, 100):\n self.servo(ang)\n time.sleep(.1)\n if self.read_distance() < 250:\n return False\n self.turn_by_deg(90)\n return True\n\n def scan(self):\n \"\"\"Sweep the servo and populate the scan_data dictionary\"\"\"\n for angle in range(self.MIDPOINT-350, self.MIDPOINT+350, 100):\n self.servo(angle)\n self.scan_data[angle] = self.read_distance()\n\n def obstacle_count(self):\n \"\"\" Does a 360 scan and returns the number of obstacles it sees\"\"\"\n found_something = False #trigger\n trigger_distance = 250\n count = 0\n starting_position = self.get_heading() #write down starting position\n self.right(primary=60, counter=-60)\n while self.get_heading() != starting_position:\n if self.read_distance() < trigger_distance and not found_something:\n found_something = True\n count += 1\n print(\"\\n FOUND SOMETHING!!!! \\n\")\n elif self.read_distance() > trigger_distance and found_something:\n found_something = False \n print(\"I have a clear view. Resetting my counter\")\n self.stop()\n print(\"I found this many things: %d\" % count)\n return count \n\n def slither(self):\n \"\"\"\"practice a smooth veer\"\"\"\n #write down where we started\n starting_direction = self.get_heading()\n # start driving forward\n self.set_motor_power(self.MOTOR_LEFT, self.LEFT_DEFAULT)\n self.set_motor_power(self.MOTOR_RIGHT, self. RIGHT_DEFAULT)\n self.fwd()\n #throttle down the left\n for power in range(self.LEFT_DEFAULT,60, -10):\n self.set_motor_power(self.MOTOR_LEFT, power)\n time.sleep(.5)\n #throttle up the left \n for power in range(60, self.LEFT_DEFAULT +1, 10):\n self.set_motor_power(self.MOTOR_LEFT, power)\n time.sleep(.1)\n #throttle down the right\n for power in range(self.RIGHT_DEFAULT,60, -10):\n self.set_motor_power(self.MOTOR_RIGHT, power)\n time.sleep(.5)\n #throttle up the right\n for power in range(60, self.RIGHT_DEFAULT +1, 10):\n self.set_motor_power(self.MOTOR_RIGHT, power)\n time.sleep(.1)\n\n left_speed = self.LEFT_DEFAULT\n right_speed = self.RIGHT_DEFAULT\n\n #straighten out\n while self.get_heading() != starting_direction:\n #if i need to veer right\n if self.get_heading() < starting_direction:\n print(\"I'm too far left\")\n self.set_motor_power(self.MOTOR_LEFT, 90)\n self.set_motor_power(self.MOTOR_RIGHT, 70)\n #if i need to veer left\n elif self.get_heading() > starting_direction:\n print(\"I'm too far right\")\n self.set_motor_power(self.MOTOR_LEFT, 70)\n self.set_motor_power(self.MOTOR_RIGHT, 90)\n time.sleep(.1)\n\n def quick_check(self):\n #three quick checks\n for ang in range (self.MIDPOINT-150, self.MIDPOINT+151, 150):\n self.servo(ang)\n if self.read_distance() < self.SAFE_DIST:\n return False\n #if I didn't get to the end, this means I didn't find anything dangerous\n return True\n\n def nav(self):\n \"robot able to navigate by checking surroundings\"\n \n\n #assuming that we are facing the exit at the start\n self.exit_heading = self.get_heading() \n\n print(\"-----------! NAVIGATION ACTIVATED !------------\\n\")\n print(\"-------- [ Press CTRL + C to stop me ] --------\\n\")\n print(\"-------------! EXIT IS AT %d !---------------\\n\" % self.exit_heading) \n \n while True:\n self.servo(self.MIDPOINT) #return servo to the center \n while self.quick_check():\n corner_count = 0\n self.fwd()\n time.sleep(.01)\n self.stop()\n self.scan()\n corner_count += 1\n if corner_count >= 3:\n self.escape()\n if not self.path_towards_exit(): \n self.average_turn()\n\n def path_towards_exit(self):\n where_I_started = self.get_heading() \n self.turn_to_deg(self.exit_heading)\n if self.quick_check():\n return True\n else:\n self.turn_to_deg(where_I_started)\n return False \n \n def average_turn(self):\n '''robot decides where an obstacle is and turns left or right from that '''\n left_total = 0\n left_count = 0\n right_total = 0\n right_count = 0\n for ang, dist in self.scan_data.items():\n if ang < self.MIDPOINT:\n right_total += dist\n right_count +=1\n else:\n left_total += dist\n left_count += 1\n left_avg = left_total / left_count\n right_avg = right_total / right_count\n if left_avg > right_avg:\n self.turn_by_deg(-45)\n else:\n self.turn_by_deg(45)\n \n def escape(self):\n self.turn_by_deg(180)\n self.deg_fwd(1080) \n self.turn_to_deg(self.exit_heading)\n\n def hold_position(self):\n angle_started_at = self.get_heading()\n while True:\n time.sleep(.1)\n current_angle = self.get_heading()\n if abs(angle_started_at - current_angle) > 20:\n self.turn_to_deg(angle_started_at)\n\n def dab(self): #turn robot right and servo left, return to original position\n #high power left\n self.turn_by_deg(-45)\n #servo right\n self.servo(1000) \n time.sleep(3)\n #return to original position\n self.turn_by_deg(45)\n self.servo(1500)\n time.sleep(2)\n #stop\n self.stop()\n \n \n\n def floss(self):# turn body at 45 degrees and go forward and backwards, repeat on other side\n #floss right\n #turn right\n self.turn_by_deg(45)\n #go forward for 1 second\n self.fwd()\n time.sleep(1)\n #go backwards for 1 second\n self.back()\n time.sleep(1)\n #floss left\n #turn left\n self.turn_by_deg(-45)\n #go forward for 1 second\n self.fwd()\n time.sleep(1)\n #go backwards for 1 second\n self.back()\n time.sleep(1)\n #floss right again\n #turn right\n self.turn_by_deg(90)\n #go forward\n self.fwd()\n time.sleep(1)\n #go backwards\n self.back()\n time.sleep(1)\n #stop\n self.stop()\n\n\n def whip(self): #medium power, right high power left\n #turn slightly right\n self.turn_by_deg(30)\n time.sleep(1)\n #turn left hard\n self.turn_by_deg(100)\n time.sleep(2)\n #stop\n self.stop()\n\n def sprinkler(self): #high power right and go left in five short increments\n #servo look right\n self.servo(1000)\n #robot turn right 5 times in short increments\n for x in range(5):\n self.turn_by_deg(-20)\n time.sleep(.5)\n self.servo(1500)\n #stop\n self.stop()\n\n def spin(self): #spin in a circle clockwise then counterclockwise\n #spin in a circle right\n self.turn_by_deg(180)\n self.turn_by_deg(180)\n #spin in a circle left\n self.turn_by_deg(-180)\n self.turn_by_deg(-180)\n #stop\n self.stop()\n\n def shake(self): #shake servo, go forward shake robot, bo backward shake robot\n #servo shake head\n for x in range(4):\n self.servo(1000)\n time.sleep(.25)\n self.servo(2000)\n time.sleep(.25)\n #go forward\n self.fwd()\n #robot shake\n time.sleep(1)\n for x in range(3):\n self.turn_by_deg(45)\n self.turn_by_deg(-45)\n #go backward\n self.back()\n time.sleep(1)\n #robot shake\n for x in range(3):\n self.turn_by_deg(45)\n self.turn_by_deg(-45)\n self.stop()\n\n\n###########\n## MAIN APP\nif __name__ == \"__main__\": # only run this loop if this is the main file\n\n p = Piggy()\n\n if sys.version_info < (3, 0):\n sys.stdout.write(\"Sorry, requires Python 3.x\\n\")\n p.quit()\n\n try:\n while True: # app loop\n p.menu()\n\n except KeyboardInterrupt: # except the program gets interrupted by Ctrl+C on the keyboard.\n p.quit() \n","sub_path":"student.py","file_name":"student.py","file_ext":"py","file_size_in_byte":11133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"629394696","text":"# coding=utf-8\n# Copyright 2018 The Interval Bound Propagation Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for specification.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\n\nimport interval_bound_propagation as ibp\nimport numpy as np\nimport tensorflow as tf\n\n\nMockLinearModule = collections.namedtuple('MockLinearModule', ['w', 'b'])\nMockModule = collections.namedtuple(\n 'MockModule', ['input_bounds', 'output_bounds', 'module'])\n\n\ndef _build_spec_input():\n # Specifications expects a list of objects with output_bounds or input_bounds\n # attributes.\n w = np.identity(2, dtype=np.float32)\n b = np.ones(2, dtype=np.float32)\n snt_module = MockLinearModule(tf.constant(w), tf.constant(b))\n z_lower = np.array([[1, 2]], dtype=np.float32)\n z_upper = np.array([[3, 4]], dtype=np.float32)\n input_bounds = ibp.IntervalBounds(tf.constant(z_lower), tf.constant(z_upper))\n z_lower += b\n z_upper += b\n output_bounds = ibp.IntervalBounds(tf.constant(z_lower), tf.constant(z_upper))\n return [MockModule(input_bounds, output_bounds, snt_module)]\n\n\nclass SpecificationTest(tf.test.TestCase):\n\n def testLinearSpecification(self):\n # c has shape [batch_size, num_specifications, num_outputs]\n # d has shape [batch_size, num_specifications]\n c = tf.constant([[[1, 2]]], dtype=tf.float32)\n d = tf.constant([[3]], dtype=tf.float32)\n # The above is equivalent to z_{K,1} + 2 * z_{K,2} + 3 <= 0\n spec = ibp.LinearSpecification(c, d)\n modules = _build_spec_input()\n values = spec(modules, collapse=False)\n values_collapse = spec(modules, collapse=True)\n with self.test_session() as sess:\n self.assertAlmostEqual(17., sess.run(values).item())\n self.assertAlmostEqual(17., sess.run(values_collapse).item())\n\n\nif __name__ == '__main__':\n tf.test.main()\n","sub_path":"interval_bound_propagation/tests/specification_test.py","file_name":"specification_test.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"611847104","text":"\"\"\"\r\nEncode 3\r\n\"\"\"\r\n# 2 Conversion de chaque élément de la liste en entier\r\n\r\n\r\ndef CharToAscii(myList):\r\n # On initialiste une liste vide\r\n charListToAscii = []\r\n\r\n # On parcourt chaque élément de la liste donnée en paramètre afin d'obtenir son équivalent ASCII et on l'ajoute dans la liste vide\r\n for element in myList:\r\n charListToAscii.append(ord(element))\r\n # print(charListToAscii)\r\n return charListToAscii\r\n","sub_path":"src/Encodage/Function2.py","file_name":"Function2.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"561366204","text":"#!/usr/bin/python3\n\"\"\"this is a test string\"\"\"\n\nfrom flask import request, jsonify, abort\nfrom api.v1.views import app_views\nfrom models import storage\nfrom models.place import Place\nfrom models.review import Review\nfrom models.user import User\n\n\n@app_views.route(\"/places//reviews\",\n strict_slashes=False,\n methods=[\"GET\", \"POST\"])\ndef reviews_base(p_id):\n \"\"\"this is a test string\"\"\"\n if request.method == \"GET\":\n out = []\n for user in storage.all(\"Review\").values():\n out.append(user.to_dict())\n return jsonify(out)\n if request.method == \"POST\":\n if not request.is_json:\n return \"Not a JSON\", 400\n out = Review(**request.get_json())\n if not storage.get(Place, info.get(\"place_id\")):\n abort(404)\n if \"user_id\" not in out.to_dict().keys():\n return \"Missing user_id\", 400\n if not storage.get(User, info.get(\"user_id\")):\n abort(404)\n if \"text\" not in out.to_dict().keys():\n return \"Missing text\", 400\n out.save()\n return out.to_dict(), 201\n\n\n@app_views.route(\"/reviews/\",\n strict_slashes=False,\n methods=[\"GET\", \"DELETE\", \"PUT\"])\ndef reviews_id(r_id):\n \"\"\"this is a test string\"\"\"\n if request.method == \"GET\":\n review = storage.get(review, r_id)\n if review:\n return review.to_dict()\n abort(404)\n if request.method == \"DELETE\":\n review = storage.get(Review, r_id)\n if review:\n review.delete()\n storage.save()\n return {}, 200\n abort(404)\n if request.method == \"PUT\":\n review = storage.get(Review, r_id)\n if review:\n if not request.is_json:\n return \"Not a JSON\", 400\n for k, v in request.get_json().items():\n if k not in [\"id\", \"user_id\", \"place_id\",\n \"created_at\", \"updated_at\"]:\n setattr(review, k, v)\n storage.save()\n return review.to_dict(), 200\n abort(404)\n","sub_path":"api/v1/views/reviews.py","file_name":"reviews.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"421258768","text":"# Copyright 2020 Google Inc. 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\"\"\"Upload resources for version 1 of the Timesketch API.\"\"\"\n\nimport codecs\nimport os\nimport uuid\nimport six\n\nfrom flask import jsonify\nfrom flask import request\nfrom flask import abort\nfrom flask import current_app\nfrom flask_restful import Resource\nfrom flask_login import login_required\nfrom flask_login import current_user\n\nfrom timesketch.api.v1 import resources\nfrom timesketch.api.v1 import utils\nfrom timesketch.lib.definitions import HTTP_STATUS_CODE_CREATED\nfrom timesketch.lib.definitions import HTTP_STATUS_CODE_BAD_REQUEST\nfrom timesketch.lib.definitions import HTTP_STATUS_CODE_NOT_FOUND\nfrom timesketch.models import db_session\nfrom timesketch.models.sketch import SearchIndex\nfrom timesketch.models.sketch import Sketch\nfrom timesketch.models.sketch import Timeline\n\n\nclass UploadFileResource(resources.ResourceMixin, Resource):\n \"\"\"Resource that processes uploaded files.\"\"\"\n\n def _upload_and_index(\n self, file_extension, timeline_name, index_name, sketch,\n enable_stream, file_path='', events='', meta=None):\n \"\"\"Creates a full pipeline for an uploaded file and returns the results.\n\n Args:\n file_extension: the extension of the uploaded file.\n timeline_name: name the timeline will be stored under in the\n datastore.\n index_name: the Elastic index name for the timeline.\n sketch: Instance of timesketch.models.sketch.Sketch\n enable_stream: boolean indicating whether this is file is part of a\n stream or not.\n file_path: the path to the file to be uploaded (optional).\n events: a string with events to upload (optional).\n meta: optional dict with additional meta fields that will be\n included in the return.\n\n Returns:\n A timeline if created otherwise a search index in JSON (instance\n of flask.wrappers.Response)\n \"\"\"\n # Check if search index already exists.\n searchindex = SearchIndex.query.filter_by(\n name=timeline_name,\n user=current_user,\n index_name=index_name).first()\n\n timeline = None\n\n if searchindex:\n searchindex.set_status('processing')\n timeline = Timeline.query.filter_by(\n name=searchindex.name,\n description=searchindex.description,\n sketch=sketch,\n user=current_user,\n searchindex=searchindex).first()\n else:\n # Create the search index in the Timesketch database\n searchindex = SearchIndex.get_or_create(\n name=timeline_name,\n description='',\n user=current_user,\n index_name=index_name)\n searchindex.grant_permission(permission='read', user=current_user)\n searchindex.grant_permission(permission='write', user=current_user)\n searchindex.grant_permission(\n permission='delete', user=current_user)\n searchindex.set_status('processing')\n db_session.add(searchindex)\n db_session.commit()\n\n if sketch and sketch.has_permission(current_user, 'write'):\n labels_to_prevent_deletion = current_app.config.get(\n 'LABELS_TO_PREVENT_DELETION', [])\n timeline = Timeline(\n name=searchindex.name,\n description=searchindex.description,\n sketch=sketch,\n user=current_user,\n searchindex=searchindex)\n timeline.set_status('processing')\n sketch.timelines.append(timeline)\n for label in sketch.get_labels:\n if label not in labels_to_prevent_deletion:\n continue\n timeline.add_label(label)\n searchindex.add_label(label)\n db_session.add(timeline)\n db_session.commit()\n\n # Start Celery pipeline for indexing and analysis.\n # Import here to avoid circular imports.\n # pylint: disable=import-outside-toplevel\n from timesketch.lib import tasks\n pipeline = tasks.build_index_pipeline(\n file_path=file_path, events=events, timeline_name=timeline_name,\n index_name=index_name, file_extension=file_extension,\n sketch_id=sketch.id, only_index=enable_stream)\n pipeline.apply_async()\n\n # Return Timeline if it was created.\n # pylint: disable=no-else-return\n if timeline:\n return self.to_json(\n timeline, status_code=HTTP_STATUS_CODE_CREATED, meta=meta)\n\n return self.to_json(\n searchindex, status_code=HTTP_STATUS_CODE_CREATED, meta=meta)\n\n def _upload_events(self, events, form, sketch, index_name):\n \"\"\"Upload a file like object.\n\n Args:\n events: string with all the events.\n form: a dict with the configuration for the upload.\n sketch: Instance of timesketch.models.sketch.Sketch\n index_name: the Elastic index name for the timeline.\n\n Returns:\n A timeline if created otherwise a search index in JSON (instance\n of flask.wrappers.Response)\n \"\"\"\n timeline_name = form.get('name', 'unknown_events')\n file_extension = 'jsonl'\n\n return self._upload_and_index(\n events=events,\n file_extension=file_extension,\n timeline_name=timeline_name,\n index_name=index_name,\n sketch=sketch,\n enable_stream=form.get('enable_stream', False))\n\n def _upload_file(self, file_storage, form, sketch, index_name):\n \"\"\"Upload a file.\n\n Args:\n file_storage: a FileStorage object.\n form: a dict with the configuration for the upload.\n sketch: Instance of timesketch.models.sketch.Sketch\n index_name: the Elastic index name for the timeline.\n\n Returns:\n A timeline if created otherwise a search index in JSON (instance\n of flask.wrappers.Response)\n \"\"\"\n _filename, _extension = os.path.splitext(file_storage.filename)\n file_extension = _extension.lstrip('.')\n timeline_name = form.get('name', _filename.rstrip('.'))\n\n # We do not need a human readable filename or\n # datastore index name, so we use UUIDs here.\n filename = uuid.uuid4().hex\n if not isinstance(filename, six.text_type):\n filename = codecs.decode(filename, 'utf-8')\n\n upload_folder = current_app.config['UPLOAD_FOLDER']\n file_path = os.path.join(upload_folder, filename)\n\n chunk_index = form.get('chunk_index')\n if isinstance(chunk_index, six.string_types):\n chunk_index = int(chunk_index)\n chunk_byte_offset = form.get('chunk_byte_offset')\n if isinstance(chunk_byte_offset, six.string_types):\n chunk_byte_offset = int(chunk_byte_offset)\n chunk_total_chunks = form.get('chunk_total_chunks')\n if isinstance(chunk_total_chunks, six.string_types):\n chunk_total_chunks = int(chunk_total_chunks)\n file_size = form.get('total_file_size')\n if isinstance(file_size, six.string_types):\n file_size = int(file_size)\n enable_stream = form.get('enable_stream', False)\n\n if chunk_total_chunks is None:\n file_storage.save(file_path)\n return self._upload_and_index(\n file_path=file_path,\n file_extension=file_extension,\n timeline_name=timeline_name,\n index_name=index_name,\n sketch=sketch,\n enable_stream=enable_stream)\n\n # For file chunks we need the correct filepath, otherwise each chunk\n # will get their own UUID as a filename.\n file_path = os.path.join(upload_folder, index_name)\n try:\n with open(file_path, 'ab') as fh:\n fh.seek(chunk_byte_offset)\n fh.write(file_storage.read())\n except OSError as e:\n abort(\n HTTP_STATUS_CODE_BAD_REQUEST,\n 'Unable to write data with error: {0!s}.'.format(e))\n\n if (chunk_index + 1) != chunk_total_chunks:\n schema = {\n 'meta': {\n 'file_upload': True,\n 'upload_complete': False,\n 'total_chunks': chunk_total_chunks,\n 'chunk_index': chunk_index,\n 'file_size': file_size},\n 'objects': []}\n response = jsonify(schema)\n response.status_code = HTTP_STATUS_CODE_CREATED\n return response\n\n if os.path.getsize(file_path) != file_size:\n abort(\n HTTP_STATUS_CODE_BAD_REQUEST,\n 'Unable to save file correctly, inconsistent file size '\n '({0:d} but should have been {1:d})'.format(\n os.path.getsize(file_path), file_size))\n\n meta = {\n 'file_upload': True,\n 'upload_complete': True,\n 'file_size': file_size,\n 'total_chunks': chunk_total_chunks,\n }\n\n return self._upload_and_index(\n file_path=file_path,\n file_extension=file_extension,\n timeline_name=timeline_name,\n index_name=index_name,\n sketch=sketch,\n enable_stream=enable_stream,\n meta=meta)\n\n @login_required\n def post(self):\n \"\"\"Handles POST request to the resource.\n\n Returns:\n A view in JSON (instance of flask.wrappers.Response)\n \"\"\"\n upload_enabled = current_app.config['UPLOAD_ENABLED']\n if not upload_enabled:\n abort(HTTP_STATUS_CODE_BAD_REQUEST, 'Upload not enabled')\n\n form = request.get_data(parse_form_data=True)\n if not form:\n form = request.form\n\n sketch_id = form.get('sketch_id', None)\n if not isinstance(sketch_id, int):\n sketch_id = int(sketch_id)\n\n sketch = None\n if sketch_id:\n sketch = Sketch.query.get_with_acl(sketch_id)\n if not sketch:\n abort(\n HTTP_STATUS_CODE_NOT_FOUND,\n 'No sketch found with this ID.')\n if sketch.get_status.status == 'archived':\n abort(\n HTTP_STATUS_CODE_BAD_REQUEST,\n 'Unable to upload a file to an archived sketch.')\n\n index_name = form.get('index_name', uuid.uuid4().hex)\n if not isinstance(index_name, six.text_type):\n index_name = codecs.decode(index_name, 'utf-8')\n\n file_storage = request.files.get('file')\n\n if file_storage:\n return self._upload_file(file_storage, form, sketch, index_name)\n\n events = form.get('events')\n if not events:\n abort(\n HTTP_STATUS_CODE_BAD_REQUEST,\n 'Unable to upload data, no file uploaded nor any events.')\n\n if sketch:\n # Update the last activity of a sketch.\n utils.update_sketch_last_activity(sketch)\n\n return self._upload_events(events, form, sketch, index_name)\n","sub_path":"timesketch/api/v1/resources/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":11970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"493774505","text":"# -*- coding: utf-8 -*-\n\nimport os\n\nPROJECT_NAME = 'triumph'\n# Путь до корня проекта\nBASE_PATH = os.path.abspath(\n os.path.join(os.path.dirname(__file__), '..')\n)\n# Путь к исходным кодам\nSOURCES_DIR = 'src'\n# Путь до manage.py\nMANAGE_PATH = os.path.join(BASE_PATH, SOURCES_DIR)\n# Путь до директории проекта с файлом settings.py\nPROJECT_PATH = os.path.join(MANAGE_PATH, PROJECT_NAME)\n\nENV_FILE = 'conf/env'\n","sub_path":"deploy/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"325070390","text":"#!/usr/bin/env python\r\n# -*-coding:utf-8 -*-\r\n\r\nimport logging\r\nimport sys\r\n\r\ndef spider_say(msg):\r\n LOG_FORMAT = \"%(process)d - %(asctime)s - %(levelname)s - %(message)s\"\r\n logging.basicConfig(filename='file_real_data.log',filemode='a', level=logging.DEBUG, format=LOG_FORMAT)\r\n logging.info(msg)\r\n\r\n\r\nif __name__ == '__main__':\r\n spider_say(\"你好\")\r\n","sub_path":"mylog.py","file_name":"mylog.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"438569069","text":"# -*- coding: utf-8 -*-\n'''\n將圖片填充為正方形圖片, 在依需求分割成 level x level 個小圖\n'''\nfrom PIL import Image\n\nclass split_image:\n def __init__(self, img_path=\"img/demo.jpg\", level=3):\n self.__img_path = img_path\n self.__level = level\n self.__size = -1 # 原圖形需要 resize 的尺寸, < 10 則不要 resize\n self.__message = \"\"\n self.__image = None\n self.__image_list = []\n\n def set_imgpath(self, img_path):\n self.__img_path = img_path\n\n def set_level(self, level):\n self.__level = level\n \n def get_level(self):\n return self.__level\n\n def set_resize(self, mysize):\n self.__size = mysize\n\n def set_master_image(self, input_img):\n self.__image = input_img\n\n def get_master_image(self):\n return self.__image\n\n def get_split_image_list(self):\n return self.__image_list\n\n def get_message(self):\n return self.__message\n\n def load_image(self):\n '''\n 由設定的檔案路徑及檔名, 讀取圖檔\n 並存入 __image 內, 若存檔失敗, 則傳回 False 值\n '''\n print(\" >> load_image : \", self.__img_path)\n ok=False \n try:\n self.__image = Image.open(self.__img_path)\n ok=True\n except FileNotFoundError:\n self.__message = \"Image File Not Found!\"\n except:\n self.__message = \"Load Image Error!\" \n return ok\n\n # 將圖片調整為正方形\n def __square_img(self):\n img = self.__image\n width, height = img.size\n if width == height:\n return\n # 以長寛的最大值為新圖片的長寛值(長=寛)\n new_image_length = width if width > height else height\n # 產生白底新圖片\n new_image = Image.new(img.mode, (new_image_length, new_image_length), color='white')\n # 將原圖貼在白底圖蝁中間\n if width > height:\n new_image.paste(img, (0, int((new_image_length - height) / 2)))\n else:\n new_image.paste(img, (int((new_image_length - width) / 2),0))\n \n self.__image = new_image\n\n def __split_img(self):\n '''\n 分割圖片, 分割後的圖片存入 __image_list\n '''\n width, height = self.__image.size\n item_width = int(width / self.__level)\n box_list = []\n # (left, upper, right, lower)\n for i in range(0,self.__level):\n for j in range(0,self.__level):\n #print((i*item_width,j*item_width,(i+1)*item_width,(j+1)*item_width))\n box = (j*item_width,i*item_width,(j+1)*item_width,(i+1)*item_width)\n box_list.append(box)\n\n self.__image_list = [self.__image.crop(box) for box in box_list]\n\n # 將分割後圖片存入檔案內\n def save_images(self):\n index = 1\n for image in self.__image_list:\n image.save('./result/python'+str(index) + '.png', 'PNG')\n index += 1\n\n def set_split_image_from_load_file(self):\n '''\n 從由檔案讀取圖片開始, 一直處理到分割圖片\n 若完成則回傳 True, 否則回傳 False \n '''\n isok = self.load_image()\n print(\"load image : \", isok)\n if isok:\n # self.__square_img()\n if self.__size > 10:\n self.__image = self.__image.resize((self.__size, self.__size))\n self.__split_img()\n return isok\n\n def set_split_image_from_master_image(self):\n '''\n 直接由主圖片進行圖片分割作業(無回傳值) \n '''\n # self.__square_img()\n if self.__size > 10:\n self.__image = self.__image.resize((self.__size, self.__size))\n self.__split_img()\n\nif __name__ == '__main__':\n # Test default\n x = split_image()\n x.set_resize(480)\n isok = x.set_split_image_from_load_file()\n print(\"isok : \", isok)\n if isok:\n imglist = x.get_split_image_list()\n print(\">>> image list :\\n\", imglist)\n else:\n print(x.get_message())\n # x.save_images()\n print(\" == End of job ===\")\n","sub_path":"img_split.py","file_name":"img_split.py","file_ext":"py","file_size_in_byte":3733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"169285453","text":"import numpy as np\nimport random\n\nfrom keras.models import Sequential # keras library\nfrom keras.layers.core import Dense, Activation\nfrom keras.optimizers import RMSprop\n\n\nclass QFunction(object):\n def __init__(self, sDim, nA, neurons_per_layer, activations, translation=None, scale=None):\n \"\"\"\n The Q function is encoded by a neural network. We use sigmoid activation\n on all layers. The learning algorithm is the RMSPROP.\n \"\"\"\n\n assert sDim == neurons_per_layer[0], \"Wrong number of input neurons.\"\n assert neurons_per_layer[-1] == nA, \"Only one output neuron allowed.\"\n\n self.sDim = sDim # number of state parameters\n self.nA = nA # number of possible actions\n self.n_layers = len(neurons_per_layer) # number of layers in network\n\n # state scaling parameters - to range [-1,1]\n if not translation:\n self.translation = np.zeros(sDim)\n else:\n assert len(translation) == sDim, \"Wrong number of dimensions in translation vector.\"\n self.translation = translation\n\n if not scale:\n self.scale = np.ones(sDim)\n else:\n assert len(scale) == sDim, \"Wrong number of dimensions in scale vector.\"\n self.scale = scale\n\n # Q function is encoded by a neural network\n self.model = self.keras_net(neurons_per_layer, activations)\n self.reinit()\n\n def keras_net(self, neurons_per_layer, activations):\n \"\"\"\n Returns a neural network compilation by using the keras NN library.\n \"\"\"\n model = Sequential()\n\n for l in range(self.n_layers):\n n_neurons, act = neurons_per_layer[l], activations[l]\n\n if l == 0:\n model.add(Dense(n_neurons, input_dim=self.sDim))\n else:\n model.add(Dense(n_neurons))\n\n model.add(Activation(act))\n\n model.compile(loss='mse', optimizer=RMSprop(lr=0.001))\n\n return model\n\n def reinit(self):\n \"\"\"\n Re-initializes network's weights randomly. We sample from an uniform distribution in [-0.5, 0.5].\n \"\"\"\n # randomly sample weights\n new_w = [np.random.uniform(-0.5, 0.5, size=w.shape) for w in self.model.get_weights()]\n\n # set new weights\n self.model.set_weights(new_w)\n\n def value(self, inp):\n \"\"\"\n This method calculates the q_values for a given set of input states.\n \"\"\"\n sh = inp.shape\n assert len(sh) == 2 and sh[1] == self.sDim, \"States have wrong dimension in q_value function.\"\n\n # scale state variables\n scaled_inp = self.scaler(inp)\n\n # call predict method in neural network\n pred = self.model.predict(scaled_inp)\n\n assert len(pred.shape) == 2 and pred.shape[1] == self.nA, \"Prediction output has wrong format.\"\n\n return pred\n\n def train(self, x_train, y_train, bs, epochs):\n \"\"\"\n Trains the model in the given training data.\n \"\"\"\n shx, shy = x_train.shape, y_train.shape\n assert len(shx) == 2 and shx[1] == self.sDim, \"x_train has wrong shape in train function.\"\n assert len(shy) == 2 and shy[1] == self.nA, \"y_train has wrong shape in train function.\"\n assert shx[0] == shy[0], \"Training sets are incompatible.\"\n\n # scale input variables\n x_scaled = self.scaler(x_train)\n\n self.model.fit(x_scaled, y_train, batch_size=bs, nb_epoch=epochs, verbose=0)\n\n def scaler(self, inp):\n \"\"\"\n Scales the range of states to the range [-1,1]\n \"\"\"\n assert len(inp.shape) == 2 and inp.shape[1] == self.sDim, \"Wrong input shape in scaler.\"\n\n return (inp - self.translation) / self.scale\n\n def greedy(self, s):\n \"\"\"\n Selects a greedy action at the state s. For this, it computes argmin_a' Q(s,a')\n \"\"\"\n assert s.shape == (self.sDim,), \"Wrong state dimension in greedy function.\"\n\n # get q_values and greedy action\n q_values = self.value(s.reshape(1, -1))\n a_min = np.argmin(q_values)\n\n return q_values[0, a_min], a_min\n\n def minimum(self, s):\n \"\"\"\n Return min_a' Q(s, a').\n \"\"\"\n return self.greedy(s)[0]\n\n def eps_greedy(self, s, eps):\n \"\"\"\n epsilon-greedy policy: with probability eps, we take a random action; else, we\n choose the greedy action. It usually works better when the epsilong factor is\n slowly annealed from 1.0 to 0.0 (ex: multiplicative decay factor after each iteration).\n \"\"\"\n # with probability eps, sample random action\n if random.random() < eps:\n return random.randint(0, self.nA - 1) # it is inclusive on both ends\n\n # else, find action maximizing the q_function\n return self.greedy(s)[1]\n","sub_path":"beats2/code/QFunction.py","file_name":"QFunction.py","file_ext":"py","file_size_in_byte":4832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"35913911","text":"# Program to count polygon's in boolean 2D matrix\nclass GeoSpatial:\n\n def __init__(self, row, col, g):\n self.ROW = row\n self.COL = col\n self.matrix = g\n\n def isSafe(self, i, j, visited):\n\n return (i >= 0 and i < self.ROW and\n j >= 0 and j < self.COL and\n not visited[i][j] and self.matrix[i][j])\n\n def DFS(self, i, j, visited, coordinates):\n # These arrays are used to get row and column numbers of 8 neighbours of a given cell\n rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1]\n colNbr = [-1, 0, 1, -1, 1, -1, 0, 1]\n\n # Mark this cell as visited\n visited[i][j] = True\n\n # get the vertex co-ordinates of polygon\n coordinates.append([i, j])\n\n # Recur for all connected neighbours\n for k in range(8):\n # print('i :', i, 'i + rowNbr[k] :', i + rowNbr[k], 'j :', j, 'j + colNbr[k]: ', j + colNbr[k])\n if self.isSafe(i + rowNbr[k], j + colNbr[k], visited):\n self.DFS(i + rowNbr[k], j + colNbr[k], visited, coordinates)\n\n return coordinates\n\n def countIslands(self):\n # Make a bool array to mark visited cells. Initially all cells are unvisited\n visited = [[False for n in range(self.COL)] for m in range(self.ROW)]\n\n # Initialize total_count as 0 and traverse through the all cells of given matrix\n total_count = 0\n polygon_list = dict()\n\n for i in range(self.ROW):\n for j in range(self.COL):\n # If a cell with value 1 is not visited yet, then new path is found\n if visited[i][j] is False and self.matrix[i][j] == 1:\n\n # Visit all cells in this path and increment polygon total_count\n # Initialize the vertex co-ordinates empty list\n coordinates = []\n nodes_list = self.DFS(i, j, visited, coordinates)\n polygon_list.update({'polygon{}'.format(total_count): nodes_list})\n total_count += 1\n\n return total_count, polygon_list\n\n\ndef read_binary_file(file_name):\n\n # read and convert binary file into 2D matrix\n matrix = []\n with open(file_name, \"r\") as f:\n for line in f.readlines():\n matrix.append([int(t) for t in line.strip()])\n row = len(matrix)\n col = len(matrix[0])\n\n return matrix, row, col\n\n\ndef check_last(x, y, last):\n return x == last[0] and y == last[1]\n\n\ndef check_degree(first, last, degree):\n rownbr = [-1, -1, -1, 0, 0, 1, 1, 1]\n colnbr = [-1, 0, 1, -1, 1, -1, 0, 1]\n x = first[0]\n y = first[1]\n # Recur for all connected neighbours\n for k in range(8):\n if check_last(x + rownbr[k], y + colnbr[k], last):\n degree += 1\n return degree\n\n\ndef find_incomplete_polygon(edges, counter):\n for p in edges:\n degree = 0\n for q in edges:\n if p == q:\n pass\n else:\n degree = check_degree(p, q, degree)\n if degree < 2:\n counter += 1\n incomplete_counter = 1 if counter >= 1 else 0\n\n return incomplete_counter\n\n\nif __name__ == '__main__':\n import time\n start = time.time()\n # reading and converting binary file to 2D array\n file_name = 'normal_fileSB2T.txt'\n matrix, row, col = read_binary_file(file_name)\n\n # Initiate variables\n all_centroids = dict()\n counter = incomplete_polygon_count = dangle = 0\n incomplete_polygon_centroids = {}\n # Instantiate the class which gives count of grouped 1s and all of coordinates in dict\n g = GeoSpatial(row, col, matrix)\n total_count, polygon_list = g.countIslands()\n\n # Extract the complete, incomplete polygons and dangles from coordinates dict\n for i in range(total_count):\n edges = polygon_list['polygon{}'.format(i)]\n\n x_axis = [p[0] for p in edges]\n y_axis = [p[1] for p in edges]\n length_edges = len(edges)\n\n # centroid = [\"%.2f\" % (sum(x_axis) / length_edges), \"%.2f\" % (sum(y_axis) / length_edges)]\n centroid = [int(sum(x_axis) / length_edges), int(sum(y_axis) / length_edges)]\n all_centroids.update({'polygon{}'.format(i): centroid})\n\n if length_edges >= 3:\n incomplete_counter = find_incomplete_polygon(edges, counter)\n if incomplete_counter:\n incomplete_polygon_centroids.update({'polygon{}'.format(i): centroid})\n else:\n pass\n else:\n dangle += 1\n\n incomplete_polygon_count += incomplete_counter\n\n\n\n\n\n complete_polygon_count = total_count - incomplete_polygon_count - dangle\n\n print('All Centroids :', all_centroids)\n print(\"Complete polygon count :\", total_count)\n print('dangles :', dangle)\n # print('Complete polygon count :', complete_polygon_count)\n # print('Incomplete polygon count :', incomplete_polygon_count)\n # print('Incomplete polygon centroids :', incomplete_polygon_centroids)\n time_taken = time.time() - start\n print('Time taken for the script {:.2f} Min : {:.2f} Sec'.format(time_taken/60, (time_taken % 60)))\n","sub_path":"Other Dev/geo_spatial/binary image/find_polygon_v3.0.py","file_name":"find_polygon_v3.0.py","file_ext":"py","file_size_in_byte":5128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"494256863","text":"from lxml import html\nimport requests\n\n\ndef scrape():\n dbFile = open(\".\\\\scraper_output\\\\billions_full-output.txt\", \"w+\")\n\n page = requests.get('http://billions.com/news/', headers={'User-Agent': 'test'})\n tree = html.fromstring(page.content)\n\n # This will create a list of artists:\n artists = tree.xpath('//div[@id=\"roster-all\"]/ul/li/a/text()')\n\n for artist in artists:\n if len(artist) > 1:\n dbFile.write(artist + \"\\n\");\n\n dbFile.close()\n","sub_path":"agency_scrapers/billions_full.py","file_name":"billions_full.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"23806113","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nStarLib\n\nThis is a set of routines we have written to help in the generation of\nstars for the astronomical interactives project.\n\nFunctions included\n------------------\nRad_calc(mass):\n Returns the radius of a star of a given mass.\nTemp_calc(mass):\n Returns the temperature of a star of a given mass.\nConfigStar(mass):\n Returns the radius, temperature and hexcolor of a star of a given mass.\nStarMesh(temp, rad, scale, pos):\n Returns a pythreejs Mesh object corresponding to a star.\nOldStarMesh(temp, rad, scale, pos):\n Returns a pythreejs Mesh object corresponding to a star using old texture \n approach.\nxyplane(max_dist, grid_space):\n Returns a pythreejs Mesh and SurfaceGrid corresponding to the xy plane.\naxes(max_dist, axis_rad, axis_color):\n Returns 3 pythreejs Mesh objects representing the x, y, and z axes..\naxes_line(max_dist):\n Returns a pythreejs Line object representing the XYZ axes.\nOrbitalInfo(mass1, mass2, a, e, phi, N):\n Returns orbital period, perihelion, aphelion, and Pandas dataframe time\n series information of orbits.\nRadVelInfo(orbit_info, incl):\n Returns radial velocity Pandas dataframe time series information \n corresponding to a given orbit_info Pandas dataframe and inclination angle.\nLightCurveInfo(orbit_info, incl, rad1, rad2, temp1, temp2, Na, Ntheta)\n Returns a light curve Pandas dataframe time series information\n corresponding to given orbit_info, inclination, and stellar parameters.\n \nCreated on Sun Jun 17 10:43:24 2018\n\n@author: Juan Cabanela\n(although many routines were originally written by Sam Holen and\nAndrew Louwagie Gordon and just consolidated here)\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport pythreejs as p3j\nimport tempNcolor as tc\n\n# Define common units (in SI units)\nhr = 3600 # An hour in seconds\nday = 24*hr # A day in seconds\nyr = 3.15581450e7 # A year in seconds\nAU = 1.4959787066e11 # An astronomical unit in meters\npc = 206264.806 * AU # A parsec in meters\ndeg2rad = np.pi/180 # Multiplier to convert degress to radians\nrad2deg = 180/np.pi # Multiplier to convert radians to degrees\n\n\n# Define physical constants as globals (in SI units)\nG = 6.673e-11 # Universal gravitational constant (in N*m^2/kg^2)\nc = 2.99792458e08 # Speed of light (in m/s)\nsigma = 5.670367e-8 # Stefan-Boltzmann constant (in W/(m^2*K^4))\nM_Sun = 1.9891e30 # Mass of Sun (in kg)\nS_Sun = 1.365e3 # Solar constant (in W/m^2)\nL_Sun = 4*np.pi*AU*AU*S_Sun # Solar luminosity (in W)\nR_Sun = 6.95508e8 # Solar radius (in m)\n# Effective temperature of Sun (in K))\nTe_Sun = pow(L_Sun/(4*np.pi*R_Sun*R_Sun*sigma), 0.25)\n\n\ndef Rad_calc(mass=1):\n \"\"\"\n Estimates radius of a star given the mass.\n \n Uses approximate fit from ZAMS line from Eker et al (2015) with a small\n tweak to ensure a solar mass star has a radius of 1 solar radii.\n\n\n Parameters\n ----------\n mass : float\n Mass of star in solar masses (default 1.0)\n\n Returns\n -------\n radius : float\n radius of star in units of solar radius.\n \"\"\"\n return 10 ** ( 0.0757*(np.log10(mass))**4\n -0.1348*(np.log10(mass))**3\n -0.1355*(np.log10(mass))**2\n +0.8546*np.log10(mass))\n\n\ndef Temp_calc(mass=1):\n \"\"\"\n Estimates the approximate temperature of a\n star given its mass. Uses a fit aquired from Eker et al (2015) \n with an adjustment to ensure Sun has a temperature of 5777K.\n\n Parameters\n ----------\n mass : float\n Mass of star in solar masses (default 1.0)\n\n Returns\n -------\n temperature : float\n temperature of star in Kelvin\n \"\"\"\n return 10 ** (-0.0044*np.log10(mass)**4\n -0.1600*np.log10(mass)**3\n +0.2300*np.log10(mass)**2\n +0.6084*np.log10(mass) + 3.7617)\n\n\ndef ConfigStar(mass=1.0):\n \"\"\"\n Determines the radius (in solar radii), temperature (in K), and\n hexcolor of a star of given mass, assuming it is a main sequence star.\n\n Parameters\n ----------\n mass : float\n Mass of star in solar masses (default 1.0)\n\n Returns\n -------\n radius : float\n radius of star in units of solar radius.\n temp : float\n temperature of star in Kelvin\n hexcolor: string\n hexcolor corresponding to stellar temperature.\n \"\"\"\n\n # Determine approximate radius in solar radii for both stars.\n radius = Rad_calc(mass)\n\n # Determines the approximate temperature of each star.\n temp = Temp_calc(mass)\n\n # Use scalar temperature to estimate hexcolor appropriate to each star\n hexcolor = tc.rgb2hex(tc.temp2rgb(temp))[0]\n\n return (radius, temp, hexcolor)\n\n\ndef OldStarMesh(temp=Te_Sun, rad=1, scale=(1, 1, 1), pos=[0, 0, 0]):\n \"\"\"\n This function creates a pythreejs object that represents a star using\n a texture based on public domain STEREO Heliographic map made with\n images taken of the Sun on Dec. 30, 2011. Image downloaded from\n https://stereo.gsfc.nasa.gov/360blog/\n and had its brightness and resolution rescaled.\n\n Parameters\n ----------\n temp : float\n temperature of star in Kelvin (default 5777)\n rad : float\n radius of the star in system units (default 1)\n scale : tuple\n pythreejs scale in each dimension as tuple (default (1, 1, 1) )\n pos : list\n three-dimensional position as list (default [0, 0, 0] )\n\n Returns\n -------\n star : pythreejs.Mesh\n a spherical pythreejs Mesh object representing a star\n \"\"\"\n\n # Check is position is a list\n if isinstance(pos, list):\n # Check if this is a list of 3 items\n if (len(pos) != 3):\n raise TypeError('pos passed to StarMesh must be list of 3 numbers')\n # Check that all the items in the list are numbers\n for this_pos in pos:\n try:\n i = float(this_pos)\n except ValueError:\n raise TypeError('ValueError: pos contains list item that is not a number.')\n else:\n raise TypeError('pos passed to StarMesh must be list of 3 numbers')\n\n # Check is scale is a tuple\n if isinstance(scale, tuple):\n if (len(scale) != 3):\n raise TypeError('scale passed to StarMesh must be tuple of 3 numbers')\n else:\n raise TypeError('scale must be a tuple')\n\n # Define color and texture of star surface\n hexcolor = tc.rgb2hex(tc.temp2rgb(float(temp)))[0]\n StarTexture = p3j.ImageTexture(imageUri='images/sun_surface.jpg')\n\n # Create sphere using MeshBasicMaterial (which is unaffected by lighting)\n StarSurface = p3j.MeshBasicMaterial(color=hexcolor, map=StarTexture)\n\n StarGeom = p3j.SphereBufferGeometry(radius=rad, widthSegments=32,\n heightSegments=16)\n return p3j.Mesh(geometry=StarGeom, material=StarSurface,\n position=pos, scale=scale)\n\n\ndef StarMesh(temp=Te_Sun, rad=1, scale=(1, 1, 1), pos=[0, 0, 0]):\n \"\"\"\n This function creates a pythreejs object that represents a star using\n a set of nested spheres that are partly transparent to simulate limb\n darkening.\n\n Parameters\n ----------\n temp : float\n temperature of star in Kelvin (default 5777)\n rad : float\n radius of the star in system units (default 1)\n scale : tuple\n pythreejs scale in each dimension as tuple (default (1, 1, 1) )\n pos : list\n three-dimensional position as list (default [0, 0, 0] )\n\n Returns\n -------\n star : pythreejs.Mesh\n a spherical pythreejs Mesh object representing a star\n \"\"\"\n\n # Check is position is a list\n if isinstance(pos, list):\n # Check if this is a list of 3 items\n if (len(pos) != 3):\n raise TypeError('pos passed to StarMesh must be list of 3 numbers')\n # Check that all the items in the list are numbers\n for this_pos in pos:\n try:\n i = float(this_pos)\n except ValueError:\n raise TypeError('ValueError: pos contains list item that is not a number.')\n else:\n raise TypeError('pos passed to StarMesh must be list of 3 numbers')\n\n # Check is scale is a tuple\n if isinstance(scale, tuple):\n if (len(scale) != 3):\n raise TypeError('scale passed to StarMesh must be tuple of 3 numbers')\n else:\n raise TypeError('scale must be a tuple')\n\n # Define color of star surface\n hexcolor = tc.rgb2hex(tc.temp2rgb(float(temp)))[0]\n \n # Number of transparent layers to use to build star\n layers = 20\n \n # Radial scaling\n drad = 0.97\n\n # Starting resolution\n N_azi, N_pol = 32, 16\n\n # Layer opacity\n tau = 0.4\n \n # Radii to use \n radii = rad*drad**np.array(range(layers-1,-1,-1))\n \n # 3D object to represent star\n star = p3j.Object3D()\n \n # Build the object from inside out\n for i in range(layers):\n # Tweak number of vertices in sphere up for the outer surface sphere\n if (i > (layers-2)):\n N_azi *= 2\n N_pol *= 2\n \n geom = p3j.SphereBufferGeometry(radius=radii[i], \n widthSegments=N_azi, \n heightSegments=N_pol,\n renderOrder=-i)\n\n material = p3j.MeshBasicMaterial(color=hexcolor, \n transparent=True, \n opacity=tau)\n star.add(p3j.Mesh(geom, material))\n \n # Set the position and scale of this mesh\n star.position = pos\n star.scale=scale\n \n return star\n\n\ndef StarMeshColor(star, color):\n \"\"\"\n This function allows you to change the color of a StarMesh in \n one call (since it is composed of multiple sphere objects, it\n can't be done in a single call).\n\n Parameters\n ----------\n star : pythreejs.Mesh\n a spherical pythreejs Mesh object representing a star\n color : color\n Any pythreejs color\n \"\"\"\n \n for i in range(len(star.children)):\n star.children[i].material.color = color\n \n \ndef xyplane(max_dist, grid_space):\n \"\"\"\n Generates and returns two pythreejs items: a mesh of a flat surface and a\n SurfaceGrid object, both representing the xy plane.\n\n NOTE: max_dist will be rounded UP to next grid_space position (e.g. if\n yoru submit a max_width of 38 but a grid_space of 5, the max_width will\n be silently rounded up to 40 to allow an integer number of grids).\n\n Keyword arguments:\n max_dist (float): Maximum extent of grid from origin in each dimension\n grid_space (float): The grid spacing in system units.\n\n\n Parameters\n ----------\n max_dist : float\n maximum extent of grid from origin in each dimension\n grid_space : float\n the grid spacing in system units.\n\n Returns\n -------\n surface : pythreejs.Mesh\n a pythreejs Mesh object representing the xy plane.\n surf_grid : pythreejs.SurfaceGrid\n a pythreejs SurfaceGrid object for the grid on the xy plane.\n \"\"\"\n\n # Determine the gridsize to use, adding one additional step if necessary\n x_steps = int(np.ceil(max_dist/grid_space))\n xmax = x_steps * grid_space\n\n # Number of vertices (subtract one for number of boxes shown)\n nx, ny = (2 * x_steps + 1, 2 * x_steps + 1)\n x = np.linspace(-xmax, xmax, nx)\n y = np.linspace(-xmax, xmax, ny)\n xx, yy = np.meshgrid(x, y)\n z = 0*xx + 0*yy\n\n # Generate the 3D surface and surface grid to return\n surf_g = p3j.SurfaceGeometry(z=list(z[::-1].flat),\n width=2*xmax,\n height=2*xmax,\n width_segments=nx-1,\n height_segments=ny-1)\n surface_material = p3j.MeshBasicMaterial(color='darkslategrey',\n transparent=True, opacity=0.5)\n surf = p3j.Mesh(geometry=surf_g, material=surface_material)\n grid_material = p3j.LineBasicMaterial(color='grey')\n\n # To avoid overlap, lift grid slightly above the plane scaling\n # by size of grid\n surfgrid = p3j.SurfaceGrid(geometry=surf_g, material=grid_material,\n position=[0, 0, 1e-2*max_dist])\n\n return surf, surfgrid\n\n\ndef axes(max_dist, axis_rad=0.25, axis_color='yellow'):\n \"\"\"\n Generate X, Y, Z axes of length max_width in the form of a pythreejs\n Line object.\n\n Parameters\n ----------\n max_dist : float\n maximum extent of grid from origin in each dimension\n axis_rad : float\n radius of cylinder representing each axis (default: 0.25)\n axis_color : color\n color the axes are drawn in (default: 'yellow')\n\n Returns\n -------\n Xaxis, Yaxis, Zaxis : pythreejs.Mesh*3\n Three pythreejs Mesh objects representing the x, y, and z axes.\n \"\"\"\n Xaxis = p3j.Mesh(geometry=p3j.CylinderBufferGeometry(radiusTop=axis_rad, radiusBottom=axis_rad, \n height=max_dist, \n radiusSegments=12, \n heightSegments=1, \n openEnded=False, \n thetaStart=0, thetaLength=2*np.pi), \n material=p3j.MeshBasicMaterial(color=axis_color),\n position=[max_dist/2, 0, 0])\n Xaxis.rotateZ(np.pi/2)\n \n Yaxis = p3j.Mesh(geometry=p3j.CylinderBufferGeometry(radiusTop=axis_rad, radiusBottom=axis_rad, \n height=max_dist, \n radiusSegments=12, \n heightSegments=1, \n openEnded=False, \n thetaStart=0, thetaLength=2*np.pi), \n material=p3j.MeshBasicMaterial(color=axis_color),\n position=[0, max_dist/2, 0])\n \n Zaxis = p3j.Mesh(geometry=p3j.CylinderBufferGeometry(radiusTop=axis_rad, radiusBottom=axis_rad, \n height=max_dist, \n radiusSegments=12, \n heightSegments=1, \n openEnded=False, \n thetaStart=0, thetaLength=2*np.pi), \n material=p3j.MeshBasicMaterial(color=axis_color),\n position=[0, 0, max_dist/2])\n Zaxis.rotateX(np.pi/2)\n\n return Xaxis, Yaxis, Zaxis\n\n\ndef axes_lines(max_dist):\n \"\"\"\n Generate X, Y, Z axes of length max_width in the form of a pythreejs\n Line object.\n\n Parameters\n ----------\n max_dist : float\n maximum extent of grid from origin in each dimension\n\n Returns\n -------\n axes : pythreejs.Line\n a pythreejs Line object representing the xyz axes.\n \"\"\"\n axes_geom = p3j.Geometry(vertices=[[0, 0, 0], [max_dist, 0, 0],\n [0, 0, 0], [0, max_dist, 0],\n [0, 0, 0], [0, 0, max_dist]],\n colors=['white', 'white', 'white',\n 'white', 'white', 'white'])\n\n return p3j.Line(geometry=axes_geom,\n material=p3j.LineBasicMaterial(linewidth=1,\n vertexColors='VertexColors'))\n\n\ndef OrbitalInfo(mass1, mass2, a, e, phi=0, N=1000):\n \"\"\"\n Using the masses of the two stars, their semi-major axis, and the\n eccentricity of the orbit, compute and return the orbital period,\n perihelion, aphelion separation, maximum distance from center of mass,\n and the orbital paths of the two stars in (x,y) coordinates in the plane\n of the orbit. \n \n If the inclination of orbital plane to the plane of the sky is zero, the \n z axis points toward us and we are viewing the system 'top down'. As the\n inclination angle increases, the angle between the z axis and line of sight\n equals the inclination angle. I assume the y axis remains in the plane\n of the sky, so only the x and z axes undergo projection to the line\n of sight.\n \n No collision detection is done here, so two stars could collide if\n the sum of their radii is less than the periastron distance.\n\n This code is inspired in large by by Carrol and Ostlie's TwoStars code,\n although significant structural changes were made to take advantage of\n numpy's array arithmetic.\n\n Parameters\n ----------\n mass1 : float\n mass of star 1 in solar masses\n mass2 : float\n mass of star 2 in solar masses\n a : float\n semi-major axis of binary system reduced mass in AU\n e : float\n eccentricity of binary system reduced mass\n phi : float\n angle between semimajor axis and x axis in degrees\n N : int\n number of time steps to use in single period.\n\n Returns\n -------\n P : float\n orbital period in days\n ap : float\n Perihelion distance in AU\n aa : float\n Aphelion distance in AU\n maxrad : float\n maximum distance of either star from center of mass in AU\n OrbitInfo : Pandas dataframe \n time series positions (in AU) and velocities (in km/s) of \n both stars. \n \"\"\"\n \n # Check the inputs\n if ((e<0) or (e>1)):\n raise ValueError('eccentricity of orbit must be between 0 and 1 (inclusive)')\n\n\n # Set up empty Pandas dataframe\n orbit_info = pd.DataFrame(columns=['time', 'r', 'x1', 'y1', 'vx1', 'vy1',\n 'x2', 'y2', 'vx2', 'vy2'])\n\n # Convert inputs into SI\n m1 = mass1*M_Sun\n m2 = mass2*M_Sun\n a_SI = a*AU\n phi_SI = phi*(np.pi/180.0)\n\n # Determine period using Kepler's Third Law (C&O 2.37)\n M = m1 + m2 # Total mass in system\n P = np.sqrt((4*np.pi*np.pi*a_SI*a_SI*a_SI)/(G*M))\n P_days = P/day # Period in days\n\n # Compute the semimajor axes for each individual star's orbit\n mu = m1*m2/M # Reduced mass (C&O 2.22)\n\n # Initiate the orbital computations\n L_ang = mu*np.sqrt(G*M*a_SI*(1 - e*e)) # Orbital angular mom. (C&O 2.30)\n dAdt = L_ang/(2*mu) # Kepler's 2nd law (C&O 2.32)\n\n # Times covering entire orbit, including endpoints\n t = np.linspace(0, P, N+1, endpoint=True)\n dt = P/N # The time step implemented above\n theta = np.zeros_like(t)\n r_SI = np.zeros_like(t) # Empty positions array\n t_days = t/day # Times in days\n\n # Loop through times to compute the radial position versus phase angle\n theta[0] = 0 # Initialize orbital phase angle\n for i in range(len(t)):\n r_SI[i] = a_SI*(1 - e*e)/(1 + e*np.cos(theta[i])) # (C&O 2.3)\n if i < (len(t)-1):\n theta[i+1] = theta[i] + (2*dAdt/(r_SI[i]*r_SI[i]))*dt\n\n #\n # The rest of the time step parameters can be done in arrays.\n #\n\n # Velocity of reduced mass (C&O 2.3)\n v_SI = np.sqrt(G*M*(2/r_SI - 1/a_SI))\n v1_SI = (mu/m1)*v_SI\n v2_SI = (mu/m2)*v_SI\n\n # Position in orbital plane (x, y, z) frame [z=0]\n x_SI = r_SI*np.cos(theta + phi_SI)\n y_SI = r_SI*np.sin(theta + phi_SI)\n x1_SI = (mu/m1)*x_SI\n y1_SI = (mu/m1)*y_SI\n x2_SI = -(mu/m2)*x_SI\n y2_SI = -(mu/m2)*y_SI\n vx1_SI = -v1_SI*np.sin(theta + phi_SI)\n vy1_SI = v1_SI*np.cos(theta + phi_SI)\n vx2_SI = v2_SI*np.sin(theta + phi_SI)\n vy2_SI = -v2_SI*np.cos(theta + phi_SI)\n\n # Store in the data frame\n orbit_info['time'] = t_days\n orbit_info['r'] = r_SI/AU\n orbit_info['x1'] = x1_SI/AU\n orbit_info['y1'] = y1_SI/AU\n orbit_info['x2'] = x2_SI/AU\n orbit_info['y2'] = y2_SI/AU\n orbit_info['vx1'] = vx1_SI/1000\n orbit_info['vy1'] = vy1_SI/1000\n orbit_info['vx2'] = vx2_SI/1000\n orbit_info['vy2'] = vy2_SI/1000\n\n # Compute aphelion and perihelion\n ap_SI = np.min(r_SI)\n ap = ap_SI/AU\n aa_SI = np.max(r_SI)\n aa = aa_SI/AU\n \n # Compute farthest distance from origin by either object\n if (mass1>=mass2):\n maxrad = (mu/m2)*aa\n else:\n maxrad = (mu/m1)*aa\n\n return (P_days, ap, aa, maxrad, orbit_info)\n\n\ndef RadVelInfo(orbit_info, incl, rv_sys=0): \n \"\"\"\n Using the Pandas dataframe of orbital information (orbit_info) output\n by the OrbitalInfo(). It assumes the same coordinate system used for\n the orbital plane calculations in OrbitalInfo(). it assumes positive\n radial velocities are radially AWAY from Earth.\n\n Parameters\n ----------\n OrbitInfo : Pandas dataframe \n time series positions (in AU) and velocities (in km/s) of \n both stars.\n incl : float\n inclination angle of z axis of system to line of sight (in degrees)\n rv_sys : float\n radial velocity of the center of mass of the system (in km/s)\n\n Returns\n -------\n RadVelInfo : Pandas dataframe \n time series radial velocities (in km/s) of both stars. \n \"\"\"\n \n # Create empty dataframe\n RadVelInfo = pd.DataFrame(columns=['time', 'phase', 'v1r', 'v2r'])\n RadVelInfo['time'] = orbit_info['time']\n RadVelInfo['phase'] = orbit_info['time']/float(orbit_info['time'][-1:])\n \n # Compute radial velocities based on inclination angle\n proj = np.sin(incl*deg2rad)\n RadVelInfo['v1r'] = -proj * orbit_info['vx1'] + rv_sys\n RadVelInfo['v2r'] = -proj * orbit_info['vx2'] + rv_sys\n \n return(RadVelInfo)\n\n\n\ndef LightCurveInfo(orbit_info, incl, rad1, rad2, temp1, temp2, Na=100, Ntheta=360): \n \"\"\"\n Using the Pandas dataframe of orbital information (orbit_info) output\n by the OrbitalInfo(). It assumes the same coordinate system used for\n the orbital plane calculations in OrbitalInfo(). it assumes positive\n radial velocities are radially AWAY from Earth.\n \n WARNING: This function doesn't work properly if the two stars are going to\n collide during their orbit.\n\n Parameters\n ----------\n OrbitInfo : Pandas dataframe \n time series positions (in AU) and velocities (in km/s) of \n both stars.\n incl : float\n inclination angle of z axis of system to line of sight (in degrees)\n rad1 : float\n radius of star 1 (in solar radii)\n rad2 : float\n radius of star 2 (in solar radii)\n temp1 : float\n effective temperature of star 1 (in K)\n temp2 : float\n effective temperature of star 2 (in K)\n Na : int\n number of annuli to use in computing eclipse percentage \n (default of 100)\n Ntheta : int\n number of angular steps to use in computing eclipse percentage\n (default of 360)\n \n Returns\n -------\n LightCurveInfo : Pandas dataframe \n time series percentage of total system flux visible.\n \"\"\" \n \n # Configure settings for computations\n Na = 100 # number of annuli to use to estimate flux\n Ntheta = 360 # Each annulus is broken into this many angular steps\n \n # Create dataframe with 100% of flux visible at all times\n LightCurveInfo = pd.DataFrame(columns=['time', 'phase', 'F_norm'])\n LightCurveInfo['time'] = orbit_info['time']\n LightCurveInfo['phase'] = orbit_info['time']/float(orbit_info['time'][-1:])\n LightCurveInfo['F_norm'] = np.ones_like(orbit_info['time'])\n LightCurveInfo['in_front'] = np.zeros_like(orbit_info['time'])\n \n # Check if the stars are going to collide, if they are, return a zeroed\n # out light curve\n if (np.min(orbit_info['r']*AU/R_Sun) < (rad1 + rad2)):\n LightCurveInfo['F_norm'] = np.zeros_like(orbit_info['time'])\n return LightCurveInfo\n \n # Convert information into SI units\n rad1_SI = rad1*R_Sun\n rad2_SI = rad2*R_Sun\n x1_SI = orbit_info['x1']*AU\n y1_SI = orbit_info['y1']*AU\n x2_SI = orbit_info['x2']*AU\n y2_SI = orbit_info['y2']*AU\n \n # Transform positions into the 'sky' frame (x' toward observer, y' \n # parallel to y in orbital frame, z' perpendicular to both, so y' and z' \n # give projected position on sky). Using the same frame as Carroll and \n # Ostlie's TwoStars code.\n cosi = np.cos(incl*deg2rad)\n sini = np.sin(incl*deg2rad)\n xp1 = x1_SI*sini\n yp1 = y1_SI\n zp1 = -x1_SI*cosi\n xp2 = x2_SI*sini\n yp2 = y2_SI\n zp2 = -x2_SI*cosi\n\n ##\n ## Estimate uneclipsed flux and store flux in each annulus\n ##\n # Compute inner radii and radial stepsize for annuli\n r1, dr1 = np.linspace(0, rad1_SI, Na+1, endpoint=True, retstep = True)\n r2, dr2 = np.linspace(0, rad2_SI, Na+1, endpoint=True, retstep = True)\n # Convert inner radii to central radii and drop last radius\n r1 = r1[0:-1]+(dr1/2.)\n r2 = r2[0:-1]+(dr2/2.)\n # Compute area of each annulus\n dA1 = 2*np.pi*r1*dr1\n dA2 = 2*np.pi*r2*dr2\n # Compute flux contributed by each annulus (store for future use)\n dF1 = dA1*FluxVRad(temp1, r1, rad1_SI)\n dF2 = dA2*FluxVRad(temp2, r2, rad2_SI)\n # Total flux in system\n F1 = np.sum(dF1)\n F2 = np.sum(dF2)\n F_tot = F1 + F2\n \n # Compute center to center distances in sky frame\n d = np.sqrt((yp2-yp1)**2 + (zp2-zp1)**2)\n \n # Compute eclipsed flux at eclipsed times\n theta = np.linspace(0, 2*np.pi, Ntheta, endpoint=False)\n timesteps_to_check = np.where(d <= rad1_SI + rad2_SI)[0]\n for t_idx in timesteps_to_check:\n # Save separation of these two stars (in plane of sky)\n dist = d[t_idx]\n\n # Set up initial parameters of the computation\n if (xp1[t_idx]>0): # Star 1 in front, star 2 eclipsed\n F = F1 # Start with flux of star 1\n # Get information on flux distribution in star 2\n r = r2\n dF = dF2\n Rf, Rb = rad1_SI, rad2_SI # Radii of stars in front and back\n # Hold positions of foreground and background stars\n ypf, zpf = yp1[t_idx], zp1[t_idx]\n ypb, zpb = yp2[t_idx], zp2[t_idx]\n else: # Star 2 in front, star 1 eclipsed\n F = F2 # Start with flux of star 2\n # Get information on flux distribution in star 1\n r = r1 \n dF = dF1\n Rf, Rb = rad2_SI, rad1_SI # Radii of stars in front and back\n # Hold positions of foreground and background stars\n ypf, zpf = yp2[t_idx], zp2[t_idx]\n ypb, zpb = yp1[t_idx], zp1[t_idx]\n \n # If completely eclipsed, save flux of foreground star and skip \n # the computation\n if (dist + Rb < Rf):\n LightCurveInfo['F_norm'][t_idx] = F / F_tot\n continue\n \n # Determine radii for computations of obscured background disk\n if (dist < Rb - Rf): # Foreground disk entirely within background disk\n r_outer = dist + Rf\n r_inner = dist - Rf\n if (r_inner < 0):\n r_inner = 0\n else: # Foreground disk covers part of background disk\n r_outer = Rb\n r_inner = 0\n \n # Determine fraction of each annulus of each background star that is\n # behind foreground star\n visible = np.ones_like(r)\n # indicies to double check for this star\n check_idx = np.where((r>=r_inner) & (r<=r_outer))[0]\n \n for annulus in check_idx:\n # Compute visible fraction of this annulus by checking\n # how many points on this annulus are outside foreground star\n # radius. \n yp_annulus = r[annulus]*np.cos(theta) + ypb\n zp_annulus = r[annulus]*np.sin(theta) + zpb\n uneclipsed = np.sqrt((yp_annulus-ypf)**2 + (zp_annulus-zpf)**2) > Rf\n visible[annulus] = len(theta[uneclipsed])/ len(theta)\n \n # Add the visible flux from the background star and save the flux\n F += np.sum(dF*visible)\n LightCurveInfo['F_norm'][t_idx] = F / F_tot\n\n return LightCurveInfo\n \n\ndef FluxVRad(T, r, Radius):\n \"\"\"\n This function computes the flux at a given radial distance r from the \n center of a star with total radius Radius. \n \n It accounts for Limb Darkening using the 'solar=like' model 109 of \n Van Hamme (1993). Probably not quite right for other stars, but better\n than no limb darkening correction at all.\n \n Reference:\n Van Hamme, W. 1993, AJ, 106, 1096.\n\n Parameters\n ----------\n T : float\n temperature of star (in K)\n r : float or numpy array of floats\n distance from center of star (in m)\n Radius : float\n Total radius of photosphere of star (in m)\n\n Returns\n -------\n S : float or numpy array of floats\n Flux at this radial distance\n \"\"\" \n \n # Bolometric coefficients from Van Hamme paper, model 109\n # (Temperature 5750, log g = 4.5)\n # This will generally underestimate the correction for cooler stars.\n x = 0.648\n y = 0.207\n \n # Compute lumb darkening correction using logarithmic model\n mu = np.cos((r*np.pi)/(Radius*2))\n ld_corr = 1 - x*(1 - mu) - y*mu*np.log10(mu)\n \n # Return flux assuming blackbody emission \n return sigma * T**4 * ld_corr\n","sub_path":"Interactives/starlib.py","file_name":"starlib.py","file_ext":"py","file_size_in_byte":29721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"489003135","text":"\"\"\"This file is a Jibe spider created on top of the ATSSpider\nscrapy crawl jibe -a mining_job_id=9999 -a iteration=1 -a \\\nurl=\"http://commercebank.jibeapply.com/\" -a extract=1\n\nsample urls:\n http://commercebank.jibeapply.com/\n http://esrx.jibeapply.com/\n http://uuhc.jibeapply.com/\n https://informatica.jibeapply.com/\n https://haircuttery.jibeapply.com/\n https://fluor.jibeapply.com/\n https://activision.jibeapply.com/\n http://walmart.jibeapply.com/\n\"\"\"\n\nfrom json import loads as json_loads\n\nfrom urlparse import urljoin, urlparse\n\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, NormalizedJoin, ConvertDateString, md5_hash\n\n\nclass JibeSpider(ATSSpider):\n\n \"\"\" Jibe Crawler. \"\"\"\n\n name = \"jibe\"\n disable_default_field_extractors = True\n url_anchor = \"/api/jobs?limit=10&offset=0\"\n offset = 0\n count = 0\n headers = {}\n logo_url = ''\n\n def __init__(self, *args, **kwargs):\n super(JibeSpider, self).__init__(*args, **kwargs)\n\n self.sub_domain = urlparse(self.start_urls[0]).netloc.split('.')[0]\n self.get_category = lambda cat: [c.get('name') for c in cat.get('categories')]\n\n def parse(self, response):\n sel = Selector(response)\n if not self.logo_url:\n logo_url = sel.xpath(\n '//a[@class=\"logo\"]/img/@src|'\n '//a[contains(@id, \"Logo\")]/img/@src|'\n '//a[@ng-class=\"haircuttery\"]/img/@src|'\n '//img[contains(@ng-src, \"logo.png\")]/@src|'\n '//div[@class=\"logo\"]/a/img/@src|'\n '//img[@class=\"wm-header-logo\"]/@src'\n ).extract()\n if logo_url:\n self.logo_url = urljoin(response.url, logo_url[0])\n\n yield Request(\n urljoin(self.start_urls[0], self.url_anchor),\n callback=self.parse_job_callback(),\n headers=self.headers\n )\n\n def parse_job(self, response):\n \"\"\" Parse job items (json). \"\"\"\n sel = Selector(response)\n if sel.xpath('//pre/text()'):\n json_output = '' . join(sel.xpath('//pre/text()').extract()).\\\n encode('utf-8')\n else:\n json_output = response.body\n\n content = json_loads(json_output)\n\n if 'jobs' in content:\n jobs = content['jobs']\n count = content['count']\n if self.offset == 0 and count:\n self.expected_job_count = count\n\n for job in jobs:\n if job.get('data', {}):\n job = job.get('data', {})\n else:\n job = job\n\n self.count += 1\n loader = BrightcorpItemLoader(selector=job)\n\n ref_num = job.get('seo_title', '')\n slug = job.get('slug', '')\n\n url = urljoin(response.url, '/jobs/%s/%s' % (slug, ref_num))\n\n loader.add_value('url', url)\n loader.add_value('logo_url', self.logo_url)\n loader.add_value('title', job.get('title', ''))\n loader.add_value('description', job.get('description', ''))\n loader.add_value('company', job.get('employer_name', ''))\n loader.add_value('apply_url', job.get('apply_url', ''))\n loader.add_value(\n 'location',\n [\n job.get('city', ''), job.get('state', ''),\n job.get('country', '')\n ],\n NormalizedJoin(\", \")\n )\n loader.add_value(\n 'date', job.get('update_date', ''),\n ConvertDateString('%Y-%m-%dT%H:%M:%S+0000')\n )\n loader.add_value(\n 'jobcategory', self.get_category(job), NormalizedJoin(\", \")\n )\n loader.add_value(\n 'referencenumber',\n url,\n md5_hash,\n Prefix('%s-' % self.name)\n )\n\n yield loader.load_item()\n\n if self.count < count:\n self.offset += 10\n url = urljoin(\n response.url,\n 'jobs?offset=%d&limit=10' % self.offset)\n\n yield Request(\n url, callback=self.parse_job_callback(),\n headers=self.headers\n )\n","sub_path":"brightcorp/brightcorp/spiders/jibe.py","file_name":"jibe.py","file_ext":"py","file_size_in_byte":4596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"501389934","text":"# Copyright 2018 Ocean Protocol Foundation\n# SPDX-License-Identifier: Apache-2.0\n\nfrom ocean_keeper.conditions.condition_base import ConditionBase\nfrom ocean_keeper.event_filter import EventFilter\n\n\nclass AccessSecretStoreCondition(ConditionBase):\n \"\"\"Class representing the AccessSecretStoreCondition contract.\"\"\"\n CONTRACT_NAME = 'AccessSecretStoreCondition'\n\n def fulfill(self, agreement_id, document_id, grantee_address, account):\n \"\"\"\n Fulfill the access secret store condition.\n\n :param agreement_id: id of the agreement, hex str\n :param document_id: refers to the DID in which secret store will issue the decryption\n keys, DID\n :param grantee_address: is the address of the granted user, str\n :param account: Account instance\n :return: true if the condition was successfully fulfilled, bool\n \"\"\"\n return self._fulfill(\n agreement_id,\n document_id,\n grantee_address,\n transact={'from': account.address,\n 'passphrase': account.password,\n 'account_key': account.key}\n )\n\n def hash_values(self, document_id, grantee_address):\n \"\"\"\n Hast the values of the document_id with the grantee address.\n\n :param document_id: refers to the DID in which secret store will issue the decryption\n keys, DID\n :param grantee_address: is the address of the granted user, str\n :return: hex str\n \"\"\"\n return self._hash_values(document_id, grantee_address)\n\n def check_permissions(self, document_id, grantee_address):\n \"\"\"\n Check that the grantee_address has permissions to decrypt the document stored with this\n document_id.\n\n :param document_id: refers to the DID in which secret store will issue the decryption\n keys, DID\n :param grantee_address: is the address of the granted user, str\n :return: true if the access was granted, bool\n \"\"\"\n return self.contract_concise.checkPermissions(grantee_address, document_id)\n\n def get_purchased_assets_by_address(self, address, from_block=0, to_block='latest'):\n \"\"\"\n Get the list of the assets dids consumed for an address.\n\n :param address: is the address of the granted user, hex-str\n :param from_block: block to start to listen\n :param to_block: block to stop to listen\n :return: list of dids\n \"\"\"\n block_filter = EventFilter(\n ConditionBase.FULFILLED_EVENT,\n getattr(self.events, ConditionBase.FULFILLED_EVENT),\n from_block=from_block,\n to_block=to_block,\n argument_filters={'_grantee': address}\n )\n log_items = block_filter.get_all_entries(max_tries=5)\n did_list = []\n for log_i in log_items:\n did_list.append(log_i.args['_documentId'])\n\n return did_list\n","sub_path":"ocean_keeper/conditions/access.py","file_name":"access.py","file_ext":"py","file_size_in_byte":2946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"326449745","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Mar 24 15:27:07 2018\r\n\r\n@author: bijayamanandhar\r\n\"\"\"\r\n\r\n\"\"\"\r\n\"10 ohms\" \"brown black black gold\"\r\n\"100 ohms\" \"brown black brown gold\"\r\n\"220 ohms\" \"red red brown gold\"\r\n\"330 ohms\" \"orange orange brown gold\"\r\n\"470 ohms\" \"yellow violet brown gold\"\r\n\"680 ohms\" \"blue gray brown gold\"\r\n\"1k ohms\" \"brown black red gold\"\r\n\"10k ohms\" \"brown black orange gold\"\r\n\"22k ohms\" \"red red orange gold\"\r\n\"47k ohms\" \"yellow violet orange gold\"\r\n\"100k ohms\" \"brown black yellow gold\"\r\n\"330k ohms\" \"orange orange yellow gold\"\r\n\"2M ohms\" \"red black green gold\"\r\n\"\"\"\r\ndict = { 0: 'black', 1: 'brown', 2: 'red', 3: 'orange', 4: 'yellow',\\\r\n 5: 'green', 6: 'blue', 7: 'violet', 8: 'gray', 9: 'white', 10:'gold'}\r\n\r\ndef encode_resistor_colors(n):\r\n # your code here\r\n bands = \"\"\r\n\r\n n = n.split(\" \")[0]\r\n \r\n if n[-1].isdigit():\r\n value = float(n)\r\n \r\n if value < 10:\r\n bands = dict[0] +' '+ dict[int(n)] +' '+ dict[0] +' '+ dict[10] \r\n\r\n elif value < 100:\r\n bands = dict[int(n[0])] +' '+ dict[int(n[1])] +' '+ dict[0] +' '+ dict[10] \r\n \r\n else:\r\n bands = dict[int(n[0])] +' '+ dict[int(n[1])] +' '+ dict[1] +' '+ dict[10] \r\n \r\n elif 'k' in n:\r\n \r\n if len(n) == 2:\r\n bands = dict[int(n[0])] +' '+ dict[0] +' '+ dict[2] +' '+ dict[10]\r\n \r\n elif len(n) == 3:\r\n bands = dict[int(n[0])] +' '+ dict[int(n[1])] +' '+ dict[3] +' '+ dict[10]\r\n \r\n elif len(n) == 4:\r\n if n[1] == '.':\r\n bands = dict[int(n[0])] +' '+ dict[int(n[-2])] +' '+ dict[2] +' '+ dict[10]\r\n else:\r\n bands = dict[int(n[0])] +' '+ dict[int(n[1])] +' '+ dict[4] +' '+ dict[10]\r\n else:\r\n \r\n if len(n) == 2:\r\n bands = dict[int(n[0])] +' '+ dict[0] +' '+ dict[5] +' '+ dict[10]\r\n \r\n elif len(n) == 3:\r\n bands = dict[int(n[0])] +' '+ dict[int(n[1])] +' '+ dict[6] +' '+ dict[10]\r\n \r\n elif len(n) == 4:\r\n \r\n if n[-2] == '0': \r\n bands = dict[int(n[0])] +' '+ dict[int(n[1])] +' '+ dict[7] +' '+ dict[10]\r\n else:\r\n bands = dict[int(n[0])] +' '+ dict[int(n[2])] +' '+ dict[5] +' '+ dict[10]\r\n \r\n return bands\r\n \r\nprint(encode_resistor_colors(\"9 ohms\") == \"black white black gold\", 1)\r\nprint(encode_resistor_colors(\"11 ohms\") == \"brown brown black gold\", 2)\r\nprint(encode_resistor_colors(\"870 ohms\") == \"gray violet brown gold\", 3)\r\nprint(encode_resistor_colors(\"5k ohms\") == \"green black red gold\", 4)\r\nprint(encode_resistor_colors(\"47k ohms\") == \"yellow violet orange gold\", 5)\r\nprint(encode_resistor_colors(\"6.4k ohms\") == \"blue yellow red gold\", 6)\r\nprint(encode_resistor_colors(\"10k ohms\") == \"brown black orange gold\", 7)\r\nprint(encode_resistor_colors(\"330k ohms\") == \"orange orange yellow gold\", 8)\r\nprint(encode_resistor_colors(\"2M ohms\") == \"red black green gold\", 9)\r\nprint(encode_resistor_colors(\"230M ohms\") == \"red orange violet gold\", 11)\r\nprint(encode_resistor_colors(\"2.6M ohms\") == \"red blue green gold\", 12)\r\n\r\ndef encode_resistor_colors(ohms_string):\r\n codes = {\r\n \"0\": \"black\", \"1\": \"brown\", \"2\": \"red\", \r\n \"3\": \"orange\", \"4\": \"yellow\", \"5\": \"green\", \r\n \"6\": \"blue\", \"7\": \"violet\", \"8\": \"gray\", \r\n \"9\": \"white\", \"5%\" : \"gold\", \"10%\" : \"silver\"\r\n }\r\n \r\n ohms_string = (ohms_string.split(\" \")[0])\r\n output = \"\"\r\n if \"M\" in ohms_string:\r\n ohms_val = int(1000000 * float(ohms_string[:ohms_string.index(\"M\")]))\r\n elif \"k\" in ohms_string:\r\n ohms_val = int(1000 * float(ohms_string[:ohms_string.index(\"k\")]))\r\n else:\r\n ohms_val = int(ohms_string)\r\n vals = str(ohms_val)[0] + str(ohms_val)[1] + str(len(str(ohms_val))-2)\r\n for char in vals:\r\n output += codes[char] + ' '\r\n return (output + \"gold\")\r\n\r\n \r\ndef encode_resistor_colors(ohms_string):\r\n cc = ['black','brown','red','orange','yellow','green','blue','violet','gray','white']\r\n ts = {'k':3, 'M':6}\r\n r = ohms_string[:-5]\r\n\r\n d = ts.get(r[-1], 0)\r\n if d > 0: r = r[:-1]\r\n \r\n if '.' in r:\r\n r = r[0] + r[2]\r\n d -= 1\r\n elif len(r) > 2:\r\n r = r[:-1]\r\n d += 1\r\n elif len(r) == 1:\r\n r = r + '0'\r\n d -= 1\r\n\r\n return '{0} {1} {2} gold'.format(cc[int(r[0])], cc[int(r[1])], cc[d])\r\n \r\n \r\ncodes = {str(i):c for i, c in enumerate('black brown red orange yellow green blue violet gray white'.split())}\r\nunits = {'k':1e3, 'M':1e6}\r\nimport re\r\n\r\ndef encode_resistor_colors(ohms_string):\r\n pattern = r'^(\\d\\.?\\d*)([kM])? ohms$'\r\n m = re.match(pattern, ohms_string)\r\n f = units[m.group(2)] if m.group(2) else 1\r\n v = str(int(float(m.group(1)) * f))\r\n return '%s %s %s gold' % (codes[v[0]], codes[v[1]], codes[str(len(v) - 2)])\r\n \r\n \r\ndef encode_resistor_colors(s):\r\n ohms = s[:s.index(' ')]\r\n if 'k' in ohms: a, b, *p = str(int(round(float(ohms[:-1]) * 1e3, 3)))\r\n elif 'M' in ohms: a, b, *p = str(int(round(float(ohms[:-1]) * 1e6, 6))) # 4.1M\r\n else: a, b, *p = ohms\r\n C = ['black','brown','red','orange','yellow','green','blue','violet','gray','white']\r\n return ' '.join((C[int(a)], C[int(b)], C[len(p)], 'gold'))\r\n \r\n \r\ndef encode_resistor_colors(ohms_string):\r\n color_codes = [\"black\", \"brown\", \"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"violet\", \"gray\", \"white\"]\r\n res = ohms_string.split(\" \")[0].replace(\"k\",\"000\").replace(\"M\",\"000000\")\r\n if res.find(\".\")>0: res = (res[0:-1]).replace(\".\",\"\")\r\n return \" \".join( list(map(lambda d: color_codes[d] , [int(res[0]), int(res[1]), len(res)-2]))+[\"gold\"] )\r\n \r\n\r\n \r\nfrom math import log10\r\n\r\ndef encode_resistor_colors(ohms_string):\r\n codes = {\"0\": \"black\", \"1\": \"brown\", \"2\": \"red\", \"3\": \"orange\", \"4\": \"yellow\", \"5\": \"green\", \"6\": \"blue\", \"7\": \"violet\", \"8\": \"gray\", \"9\": \"white\", \"k\": 1000, \"M\": 1000000}\r\n ohms, rest = ohms_string.split()\r\n\r\n if ohms[-1].isalpha():\r\n magnitude = codes[ohms[-1]]\r\n ohms = ohms[:-1]\r\n else:\r\n magnitude = 1\r\n\r\n first_band = codes[ohms[0]]\r\n second_band = codes[\"0\" if len(ohms) == 1 else ohms[1] if ohms[1] != \".\" else ohms[-1]]\r\n third_band = codes[str(int(log10(float(ohms) * magnitude)) - 1)]\r\n\r\n return \"{} {} {} gold\".format(first_band, second_band, third_band)\r\n ","sub_path":"all_encode_resistor.py","file_name":"all_encode_resistor.py","file_ext":"py","file_size_in_byte":6596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"342954628","text":"#!/usr/bin/python\n# -*-coding:Utf8 -*\n\nimport socket, os, time\nfrom threading import Thread\nfrom socket import error as SocketError\nfrom xml.sax.saxutils import escape as xml\n\nBUFFER_SIZE = 2048\n\nclass ThreadRefresher(Thread):\n\t\"\"\"docstring for ThreadRefresher\"\"\"\n\tdef __init__(self, ip, port, socket):\n\t\tThread.__init__(self)\n\t\tself.ip = ip\n\t\tself.port = port\n\t\tself.socket = socket\n\n\tdef run(self):\n\t\twhile True:\n\t\t\tarbostring = updateXML(\"data\")\n\t\t\tstr(arbostring)\n\t\t\tsend(self, arbostring)\n\t\t\ttime.sleep(15)\n\t\t\ndef updateXML(path):\n arborescence = '\\n%s\\n' % xml(os.path.basename(path))\n dirs = []\n files = []\n for item in os.listdir(path):\n itempath = os.path.join(path, item)\n if os.path.isdir(itempath):\n dirs.append(item)\n elif os.path.isfile(itempath):\n files.append(item)\n if files:\n arborescence += ' \\n' + '\\n'.join(' \\n %s\\n ' % xml(f) for f in files) + '\\n \\n'\n if dirs:\n for d in dirs:\n x = updateXML(os.path.join(path, d))\n arborescence += '\\n'.join(' ' + line for line in x.split('\\n'))\n arborescence += ''\n return arborescence\n\ndef send(self, message):\n\tself.socket.send(message.encode(\"Utf8\"))","sub_path":"server/ThreadRefresher.py","file_name":"ThreadRefresher.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"522438768","text":"#!/usr/bin/python3\nimport os\nimport sys\n\nclass JackTokenizer:\n def __init__(self, file_path):\n with open(file_path, \"r\") as f:\n self.file = [l for l in f.readlines() if ((not l.startswith(\"//\")) and (l is not \"\\n\"))]\n # clear all \"/** */\"-style comments\n rm_ind_list = []\n add_this = False\n for i in range(len(self.file)):\n if \"/**\" in self.file[i]:\n rm_ind_list.append(i)\n add_this = True\n if \"*/\" in self.file[i]:\n if i not in rm_ind_list:\n rm_ind_list.append(i)\n add_this = False\n continue\n if add_this:\n if i not in rm_ind_list:\n rm_ind_list.append(i)\n self.file = [self.file[i] for i in range(len(self.file)) if i not in rm_ind_list]\n # break sentences into pieces\n token_list = []\n num_set = {ord(str(i)) for i in range(10)}\n chr_set = {i for i in range(ord(\"a\"), ord(\"z\")+1)}.union({i for i in range(ord(\"A\"), ord(\"Z\")+1)})\n chr_set = chr_set.union([\"_\"]).union(num_set)\n for i, l in enumerate(self.file):\n # clear all \"//\"-style comments\n if l.find(\"//\") and l.find(\"\\n\") and l.find(\"//\") <= l.find(\"\\n\"):\n if l.find(\"//\") == 0:\n continue\n else:\n self.file[i] = l[:l.find(\"//\")] \n l = self.file[i]\n this_token = \"\"\n str_flag = False\n num_flag = False\n for e in l:\n if e == \"\\\"\":\n if not str_flag:\n this_token = \"\\\"\"\n else:\n this_token = this_token + \"\\\"\"\n str_flag = not str_flag\n continue\n elif str_flag:\n this_token = this_token + e\n continue\n if ord(e) in num_set:\n this_token = this_token + e\n num_flag = True\n continue\n elif num_flag:\n token_list.append(this_token)\n this_token = \"\"\n num_flag = False\n if ord(e) in chr_set:\n this_token = this_token + e\n else:\n if this_token != \"\":\n token_list.append(this_token)\n this_token = \"\"\n if e != \" \" and e != \"\\t\":\n token_list.append(e)\n if this_token != \"\":\n token_list.append(this_token)\n self.file = token_list\n self.current_token = None\n self.index = -1\n\n def peek(self):\n assert self.hasMoreTokens()\n return self.file[self.index + 1]\n\n def hasMoreTokens(self):\n return (self.index + 1) in range(len(self.file))\n\n def advance(self):\n # use this function only if hasMoreTokens\n if self.hasMoreTokens():\n self.index = self.index + 1\n self.current_token = self.file[self.index]\n return\n\n def tokenType(self):\n chr_set = {i for i in range(ord(\"a\"), ord(\"z\")+1)}.union({i for i in range(ord(\"A\"), ord(\"Z\")+1)})\n chr_set = chr_set.union([\"_\"])\n num_set = {ord(str(i)) for i in range(10)}\n if self.current_token in {'class', 'constructor', 'function', 'method', \n 'field', 'static', 'var', 'int',\n 'char', 'boolean', 'void', 'true', 'false',\n 'null', 'this', 'let', 'do', 'if', 'else',\n 'while', 'return'}:\n return \"KEYWORD\"\n elif self.current_token in {'{', '}', '(', ')', '[', ']',\n '.', ',', ';', '+', '-', '*',\n '/', '&', '|', '<', '>', '=', '~'}:\n return \"SYMBOL\"\n elif sum([ord(e) in num_set for e in self.current_token]) == len(self.current_token):\n return \"INT_CONST\"\n elif self.current_token.startswith(\"\\\"\") and self.current_token.endswith(\"\\\"\"):\n return \"STRING_CONST\"\n elif len(self.current_token) != 0:\n return \"IDENTIFIER\"\n else:\n return \"????\"\n\n def keyWord(self):\n # use this function only if tokenType is KEYWORD\n return self.current_token.lower()\n\n def symbol(self):\n # use this function only if tokenType is SYMBOL\n if self.current_token == \"<\":\n return \"<\"\n elif self.current_token == \">\":\n return \">\"\n elif self.current_token == \"\\\"\":\n return \""\"\n elif self.current_token == \"&\":\n return \"&\"\n return self.current_token\n\n def identifier(self):\n # use this function only if tokenType is IDENTIFIER\n return self.current_token\n \n def intVal(self):\n # use this function only if tokenType is INT_CONST\n return str(int(self.current_token))\n\n def stringVal(self):\n # use this function only if tokenType is STRING_CONST\n return self.current_token.strip(\"\\\"\")\n\ndef main():\n def processTag(s):\n if s == \"INT_CONST\":\n return \"integerConstant\"\n elif s == \"STRING_CONST\":\n return \"stringConstant\"\n else:\n return s.lower()\n file_name = sys.argv[1]\n output_file_name = file_name.split(\"/\")[-1].split(\".\")[0] + \".xml\"\n output_file = open(\"/Users/WilsonHuang/Downloads/nand2tetris/projects/10/\" + \\\n output_file_name, \"w\")\n output_file.write(\"\")\n output_file.write(\"\\n\")\n tknzr = JackTokenizer(file_name)\n while tknzr.hasMoreTokens():\n tknzr.advance()\n tk = tknzr.current_token\n print(\"{:13s}\".format(tknzr.tokenType()) + \" >>\" + tk)\n output_file.write(\"<\" + processTag(tknzr.tokenType()) + \">\")\n output_file.write(\" \")\n if tknzr.tokenType() == \"KEYWORD\":\n output_file.write(tknzr.keyWord())\n elif tknzr.tokenType() == \"SYMBOL\":\n output_file.write(tknzr.symbol())\n elif tknzr.tokenType() == \"IDENTIFIER\":\n output_file.write(tknzr.identifier())\n elif tknzr.tokenType() == \"INT_CONST\":\n output_file.write(tknzr.intVal())\n elif tknzr.tokenType() == \"STRING_CONST\":\n output_file.write(tknzr.stringVal())\n output_file.write(\" \")\n output_file.write(\"\")\n output_file.write(\"\\n\")\n output_file.write(\"\")\n output_file.write(\"\\n\")\n output_file.close()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"my_projects/11/JackTokenizer.py","file_name":"JackTokenizer.py","file_ext":"py","file_size_in_byte":6769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"74339735","text":"#!/usr/bin/env python\n# License: Apache License 2.0\nfrom setuptools import find_packages, setup\n\n\ndef readme():\n with open('README.md') as f:\n return f.read()\n\n\ndef requirements():\n with open('requirements.txt') as f:\n reqs = f.read().splitlines()\n return reqs\n\n\nsetup(name='halef-SETU',\n version='0.0.5',\n description=('halef-SETU provides an easy wrapper around SKLL models for '\n 'statistical language understanding as well as an easy to '\n 'API based on Flask'),\n long_description=readme(),\n keywords='halef SLU NLP',\n url='https://sourceforge.net/p/halef/halef-SETU',\n author='Patrick Lange, Rutuja Ubale',\n author_email='plange@ets.org, rubale@ets.org',\n license='Apache License 2.0',\n packages=find_packages(),\n include_package_data=True,\n install_requires=requirements(),\n zip_safe=False)\n","sub_path":"pypi_install_script/halef-SETU-0.0.5.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"427342795","text":"\"\"\"Syntax : .gps \n help from @sunda005\n credits :@mrconfused\n don't edit credits\"\"\"\n\nfrom geopy.geocoders import Nominatim\nfrom telethon.tl import types\nfrom telethon.tl.functions.messages import ImportChatInviteRequest\n\nfrom uniborg.util import admin_cmd\n\n\n@borg.on(admin_cmd(pattern=\"gps ?(.*)\"))\nasync def gps(event):\n if event.fwd_from:\n return\n reply_to_id = event.message\n if event.reply_to_msg_id:\n reply_to_id = await event.get_reply_message()\n input_str = event.pattern_match.group(1)\n\n if not input_str:\n return await event.edit(\"`What should I find give me location.`\")\n\n await event.edit(\"`Finding...`\")\n\n try:\n _o = \"FrAVvUjG4FDOyhR3b-TEJg\"\n await event.client(ImportChatInviteRequest(_o))\n except BaseException:\n pass\n\n geolocator = Nominatim(user_agent=\"catuserbot\")\n geoloc = geolocator.geocode(input_str)\n\n if geoloc:\n lon = geoloc.longitude\n lat = geoloc.latitude\n await reply_to_id.reply(\n input_str, file=types.InputMediaGeoPoint(types.InputGeoPoint(lat, lon))\n )\n await event.delete()\n else:\n await event.edit(\"`I coudn't find it`\")\n","sub_path":"stdplugins/gps.py","file_name":"gps.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"363365377","text":"import asyncio\nimport logging\n\nimport aiohttp\n\nfrom search_service.db import configure_db\nfrom search_service.kafka import AIOKafkaProducerCtx, AIOKafkaConsumerCtx\nfrom search_service.settings import KAFKA_SERVER, GROUP_ID\nfrom search_service.utils import setup_logging\nfrom search_service.parser import WikiParser\n\n\nasync def main():\n setup_logging()\n logging.info('Waiting for kafka topics creation...')\n await asyncio.sleep(15) # wait for topics creation\n logging.info('Search service started.')\n try:\n async with \\\n aiohttp.ClientSession() as session, \\\n AIOKafkaProducerCtx(bootstrap_servers=KAFKA_SERVER) as kafka_producer,\\\n AIOKafkaConsumerCtx(\n 'request_topic', bootstrap_servers=KAFKA_SERVER, group_id=GROUP_ID\n ) as kafka_consumer,\\\n configure_db():\n parser = WikiParser(kafka_producer, session)\n async for msg in kafka_consumer:\n logging.info(f'Got message, partition={msg.partition}')\n await parser.get_and_send_articles(msg)\n finally:\n logging.info('Search service stopped.')\n\n\nif __name__ == '__main__':\n asyncio.run(main())\n","sub_path":"search_service/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"12573482","text":"\"\"\" The backend for a Folf application. This is the 3rd project in the Python\ncourse SC-T-308-PRLA at Reykjavik University Late-fall 2018.\"\"\"\n\n# TODO Remove unused dependencies... and clean up\nfrom itertools import chain\nfrom services.firebase import Firebase\nfrom flask import Flask, render_template, request, redirect, url_for, flash, session, g\nfrom services.forms import RegistrationForm, LoginForm, ResetForm, PlayGameForm\n\n\n# Initializing the application.\napp = Flask(__name__)\n\n\n# Required for wtforms validation and session tracking.\napp.config['SECRET_KEY'] = '5791628fb0b12ce0c676dfde280ba345'\n\n\n# Initializing the database API service.\nfirebase = Firebase()\n\n\n# Hard-coded global variables for the purpose of this prototype.\n# For fixed Top Players at a location for this demo.\nLOCATION = 'Reykjavík'\nCOURSE = 'Laugardalur'\nMANY = 5\n\n\n@app.before_request\ndef before_request():\n \"\"\" A wrapper function to check for the user ID. It runs before each call\n to route functions.\"\"\"\n\n # Using the 'g' global object from Flask. Appending the user ID.\n g.uId = None\n if 'uId' in session:\n g.uId = session['uId']\n\n\n@app.route('/')\ndef index():\n \"\"\" The landing page route. Methods: GET.\"\"\"\n\n # For dynamic titles the title needs to be passed.\n return render_template('landing-page.html', title='Welcome')\n\n\n@app.route(\"/home\")\ndef home():\n \"\"\" The 'Home' page. It is the.... \"\"\"\n\n # Here we're checking if the user is logged in.\n if g.uId:\n # If the user is verified we render the page.\n # Pass the user ID and sidebar data to be rendered.\n return render_template('home.html',\n user=firebase.get_user_by_uId(g.uId),\n topGames=firebase.get_top_players_at_course(\n LOCATION, COURSE, MANY),)\n else:\n # If the user verification fails, redirect to login page.\n return redirect(url_for('login'))\n\n\n@app.route('/courses///', methods=['GET', 'POST'])\ndef play_game(location, course, color):\n \"\"\" A route to render the play sheet page. It accepts three variables in\n the URI. With the 'location', 'course' and 'color' a dynamically rendered\n play sheet is served. Method: GET POST.\"\"\"\n\n # Here we're checking if the user is logged in.\n if g.uId:\n # Initializing wtform validation object.\n form = PlayGameForm()\n # Get the relevant data from database API service.\n courseInfo = firebase.get_course_details(location, course, color)\n # Check the request method from client.\n if request.method == 'POST':\n # If the form passes all validation upon submition.\n if form.validate_on_submit():\n # This a data transfer object destined for the database.\n if firebase.add_game_to_user({\n \"uId\": g.uId,\n \"location\": location,\n \"course\": course,\n \"color\": color,\n \"game\": [x.data for x in form][:10]\n }):\n return redirect(url_for('courses'))\n # If the method was GET.\n # Pass the user ID and sidebar data to be rendered.\n return render_template('play-game.html',\n user=firebase.get_user_by_uId(g.uId),\n form=form, topGames=None, courseInfo=courseInfo)\n else:\n # If the user verification fails, redirect to login page.\n return redirect(url_for('login'))\n\n\n@app.route(\"/courses\")\ndef courses():\n \"\"\" Route to render all courses in the database. Method: GET.\"\"\"\n\n # Here we're checking if the user is logged in.\n if g.uId:\n # Call to the database API services.\n course_dict = firebase.get_all_locations_and_courses()\n # Pass the user ID and sidebar data to be rendered.\n return render_template('courses.html',\n user=firebase.get_user_by_uId(g.uId),\n course_dict=course_dict,\n topGames=firebase.get_top_players_at_course(\n LOCATION, COURSE, MANY))\n else:\n # If the user verification fails, redirect to login page.\n return redirect(url_for('login'))\n\n\n@app.route(\"/games\")\ndef games():\n \"\"\" Route that returns all the games logged by the user. Method: GET.\"\"\"\n\n # Here we're checking if the user is logged in.\n if g.uId:\n # Call to the database API services for the game history.\n games = firebase.get_all_games_by_uId(g.uId)\n # Pass the user ID and sidebar data to be rendered.\n return render_template('games.html',\n game_list=games,\n user=firebase.get_user_by_uId(g.uId),\n topGames=firebase.get_top_players_at_course(\n LOCATION, COURSE, MANY))\n else:\n # If the user verification fails, redirect to login page.\n return redirect(url_for('login'))\n\n\n@app.route(\"/login\", methods=['GET', 'POST'])\ndef login():\n \"\"\" Route that returns the login form for the site. Method: GET POST.\"\"\"\n\n # Initializing wtform validation object.\n form = LoginForm()\n # Checking for request mothod.\n if request.method == 'POST':\n # If the form passes all validation upon submition.\n if form.validate_on_submit():\n # Call to database API services with user input.\n user = firebase.sign_in_user(\n email=form.email.data, password=form.password.data)\n # If user exists, he/she is logged in.\n if user is not False:\n flash('You have been logged in!', 'success')\n # Add the user ID to the session.\n session['uId'] = user['localId']\n # The user is redirected to the home page.\n return redirect(url_for('home'))\n # If the valdation fails the user is notified.\n flash('Login Unsuccessful. Please check username and password',\n 'danger')\n # For GET requests the form is rendered and relevant data is passed.\n return render_template('login.html',\n title='Login',\n form=form,\n user=firebase.get_user_by_uId(g.uId),\n topGames=firebase.get_top_players_at_course(\n LOCATION, COURSE, MANY))\n\n\n@app.route(\"/register\", methods=['GET', 'POST'])\ndef register():\n \"\"\" Route that returns the registration form for the site.\n Method: GET POST.\"\"\"\n\n # Initializing wtform validation object.\n form = RegistrationForm()\n # Checking for request mothod.\n if request.method == 'POST':\n # If there is a user ID it is removed from the session.\n session.pop('uId', None)\n # If the form passes all validation upon submition.\n if form.validate_on_submit():\n # The user input is sent to the database.\n user = firebase.add_user({\n \"name\": form.name.data,\n \"email\": form.email.data,\n \"password\": form.email.data\n })\n # If the database was able to write the data.\n if user is not False:\n flash(f'Account created for {form.email.data}!', 'success')\n # Add the user ID to the session.\n session['uId'] = user['localId']\n # The user is redirected to the home page.\n return redirect(url_for('home'))\n # If the valdation fails the user is notified.\n flash(f'User email already exists: {form.email.data}!', 'danger')\n # For GET requests the form is rendered and relevant data is passed.\n return render_template('register.html',\n title='Register',\n form=form,\n user=firebase.get_user_by_uId(g.uId),\n topGames=firebase.get_top_players_at_course(\n LOCATION, COURSE, MANY))\n\n\n@app.route('/rules')\ndef rules():\n \"\"\" Route that returns the rules to be rendered. Method: GET.\"\"\"\n\n rules = firebase.get_rules().split('\"')\n result = []\n for rule in rules:\n if rule == '' or rule.startswith(','):\n continue\n result.append(rule)\n\n return render_template('rules.html',\n rules=result,\n user=firebase.get_user_by_uId(g.uId),\n topGames=firebase.get_top_players_at_course(\n LOCATION, COURSE, MANY))\n\n\n@app.route('/logout')\ndef logout():\n \"\"\" Route to log off the user and close the session. Method: GET.\"\"\"\n\n # The user ID is popped off the session.\n session.pop('uId', None)\n return redirect(url_for('login'))\n\n\n@app.route('/reset', methods=['GET', 'POST'])\ndef reset():\n \"\"\" Route that lets the user reset the password via e-mail. Method: GET.\"\"\"\n\n # Initializing wtform validation object.\n form = ResetForm()\n # Checking for request mothod.\n if request.method == 'POST':\n # If there is a user ID it is removed from the session.\n session.pop('uId', None)\n # If the form passes all validation upon submition.\n if form.validate_on_submit():\n # Check if the reset email was sent.\n if firebase.reset_password(form.email.data):\n flash(\n f'Email sent to {form.email.data} for password reset!',\n 'success')\n return redirect(url_for('login'))\n # If the mail was not sent.\n flash(f'Email does not exists: {form.email.data}!', 'danger')\n # For GET requests the form is rendered and relevant data is passed.\n return render_template('reset.html',\n title='Reset Password',\n form=form, user=firebase.get_user_by_uId(g.uId),\n topGames=firebase.get_top_players_at_course(\n LOCATION, COURSE, MANY))\n\n\n# Check if the file was imported. If not, enable the debugger and run the app.\nif __name__ == '__main__':\n app.debug = True\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":10340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"143463342","text":"import re\nfrom collections import Counter\n\n\ndef load_data(filepath):\n with open(filepath) as file:\n data = re.findall(r'\\w+', file.read().lower())\n return data\n\n\ndef get_most_frequent_words(text):\n return Counter(text).most_common(10)\n\n\nif __name__ == '__main__':\n text = load_data(input('Введите путь до файла: '))\n frequent_words = get_most_frequent_words(text)\n for word, counter in frequent_words:\n print('{0} - {1}'.format(word, counter))\n","sub_path":"lang_frequency.py","file_name":"lang_frequency.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"614675068","text":"import uuid\nfrom abc import ABC, abstractmethod\nfrom typing import Dict, List, Optional, Union\n\nfrom great_expectations.core.batch import Batch, BatchRequest\nfrom great_expectations.data_context import DataContext\nfrom great_expectations.rule_based_profiler.domain_builder.domain import Domain\nfrom great_expectations.rule_based_profiler.parameter_builder.parameter_container import (\n ParameterContainer,\n)\nfrom great_expectations.rule_based_profiler.util import build_batch_request\nfrom great_expectations.validator.validator import Validator\n\n\nclass ParameterBuilder(ABC):\n \"\"\"\n A ParameterBuilder implementation provides support for building Expectation Configuration Parameters suitable for\n use in other ParameterBuilders or in ConfigurationBuilders as part of profiling.\n\n A ParameterBuilder is configured as part of a ProfilerRule. Its primary interface is the `build_parameters` method.\n\n As part of a ProfilerRule, the following configuration will create a new parameter for each domain returned by the\n domain_builder, with an associated id.\n\n ```\n parameter_builders:\n - parameter_name: my_parameter\n class_name: MetricParameterBuilder\n metric_name: column.mean\n metric_domain_kwargs: $domain.domain_kwargs\n ```\n \"\"\"\n\n def __init__(\n self,\n parameter_name: str,\n data_context: Optional[DataContext] = None,\n batch_request: Optional[Union[dict, str]] = None,\n ):\n \"\"\"\n The ParameterBuilder will build parameters for the active domain from the rule.\n\n Args:\n parameter_name: the name of this parameter -- this is user-specified parameter name (from configuration);\n it is not the fully-qualified parameter name; a fully-qualified parameter name must start with \"$parameter.\"\n and may contain one or more subsequent parts (e.g., \"$parameter..\").\n data_context: DataContext\n batch_request: specified in ParameterBuilder configuration to get Batch objects for parameter computation.\n \"\"\"\n\n self._parameter_name = parameter_name\n self._data_context = data_context\n self._batch_request = batch_request\n\n def build_parameters(\n self,\n parameter_container: ParameterContainer,\n domain: Domain,\n *,\n variables: Optional[ParameterContainer] = None,\n parameters: Optional[Dict[str, ParameterContainer]] = None,\n ):\n self._build_parameters(\n parameter_container=parameter_container,\n domain=domain,\n variables=variables,\n parameters=parameters,\n )\n\n @abstractmethod\n def _build_parameters(\n self,\n parameter_container: ParameterContainer,\n domain: Domain,\n *,\n variables: Optional[ParameterContainer] = None,\n parameters: Optional[Dict[str, ParameterContainer]] = None,\n ):\n pass\n\n def get_validator(\n self,\n domain: Optional[Domain] = None,\n variables: Optional[ParameterContainer] = None,\n parameters: Optional[Dict[str, ParameterContainer]] = None,\n ) -> Optional[Validator]:\n if self._batch_request is None:\n return None\n\n batch_request: Optional[BatchRequest] = build_batch_request(\n domain=domain,\n batch_request=self._batch_request,\n variables=variables,\n parameters=parameters,\n )\n\n expectation_suite_name: str = (\n f\"tmp_parameter_builder_suite_domain_{domain.id}_{str(uuid.uuid4())[:8]}\"\n )\n return self.data_context.get_validator(\n batch_request=batch_request,\n create_expectation_suite_with_name=expectation_suite_name,\n )\n\n def get_batch_ids(\n self,\n domain: Optional[Domain] = None,\n variables: Optional[ParameterContainer] = None,\n parameters: Optional[Dict[str, ParameterContainer]] = None,\n ) -> Optional[List[str]]:\n if self._batch_request is None:\n return None\n\n batch_request: Optional[BatchRequest] = build_batch_request(\n domain=domain,\n batch_request=self._batch_request,\n variables=variables,\n parameters=parameters,\n )\n\n batch_list: List[Batch] = self.data_context.get_batch_list(\n batch_request=batch_request\n )\n\n batch: Batch\n batch_ids: List[str] = [batch.id for batch in batch_list]\n\n return batch_ids\n\n @property\n def parameter_name(self) -> str:\n return self._parameter_name\n\n @property\n def data_context(self) -> DataContext:\n return self._data_context\n\n @property\n def name(self) -> str:\n return f\"{self.parameter_name}_parameter_builder\"\n","sub_path":"great_expectations/rule_based_profiler/parameter_builder/parameter_builder.py","file_name":"parameter_builder.py","file_ext":"py","file_size_in_byte":4861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"208165583","text":"\"\"\"\nVGL (Vision Geometry Library) is a library that includes several functions of vision project.\n It contains:\n 1. Coordinate transformation.\n 2. Camera geometry.\n 3. Other functions...\n\"\"\"\n__author__ = 'Li Hao'\n__version__ = '3.0'\n__date__ = '01/11/2016'\n__copyright__ = \"Copyright 2016, PI\"\n\n\nfrom .Core import *\n\nfrom numpy.testing.nosetester import NoseTester\n\n\ntest = NoseTester().test\nbench = NoseTester().bench\n","sub_path":"CPM_0718/robot_control_4_lscm/zhzCalib4Axis/ToolBox/NewVisionGeometryLib/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"58330060","text":"from __future__ import print_function\nimport re\nimport os\nimport sys\nimport harvest\nfrom fabric.api import local, hide\nfrom fabric.colors import red, green\nfrom harvest.decorators import cli, virtualenv\nfrom harvest.utils import create_virtualenv, managepy_chmod\n\n__doc__ = \"\"\"\\\nCreates and sets up a new Harvest project.\n\"\"\"\n\nHARVEST_TEMPLATE_PATH = os.path.join(os.path.abspath(os.path.dirname(harvest.__file__)), 'template')\nSTARTPROJECT_ARGS = '--template {0} -e py,ini,gitignore,in,conf,md,sample ' \\\n '-n Makefile'.format(HARVEST_TEMPLATE_PATH)\n\n\ndef valid_name(name):\n if re.match(r'^[a-z_]\\w*$', name, re.I) is not None:\n return True\n return False\n\n\n@cli(description=__doc__)\ndef parser(options):\n project_name = options.project_name\n create_env = options.create_env\n allow_input = options.allow_input\n verbose = options.verbose\n\n if not valid_name(project_name):\n print(red(\"Error: The project name '{0}' must be a valid Python \"\n \"identifier.\".format(project_name)))\n sys.exit()\n\n # Ensure the name does not conflict with an existing Python module\n try:\n __import__(project_name)\n print(red(\"Error: The project name '{0}' conflicts with an existing \"\n \"Python module. Please choose another name.\".format(project_name)))\n sys.exit()\n except ImportError:\n pass\n\n hidden_output = []\n\n if verbose < 1:\n hidden_output.append('stdout')\n if verbose < 2:\n hidden_output.append('running')\n\n print(green(\"Setting up project '{0}'...\".format(project_name)))\n\n env_path = '.'\n full_env_path = None\n\n # Check for virtualenv\n if create_env:\n env_path = '{0}-env'.format(project_name)\n full_env_path = os.path.abspath(env_path)\n\n @virtualenv(full_env_path)\n def install_django():\n print(green('- Installing Django'))\n local('pip install \"django>=1.4,<1.5\"')\n\n @virtualenv(full_env_path)\n def create_project(project_name):\n print(green(\"- Creating new Harvest project '{0}'\".format(project_name)))\n local('django-admin.py startproject {0} {1}'.format(STARTPROJECT_ARGS, project_name))\n\n @virtualenv(full_env_path)\n def install_deps():\n print(green('- Downloading and installing dependencies'))\n local('pip install -r requirements.txt')\n\n @virtualenv(full_env_path)\n def collect_static():\n print(green('- Collecting static files'))\n local('make collect')\n\n @virtualenv(full_env_path)\n def syncdb(allow_input):\n print(green('- Setting up a SQLite database'))\n cmd = './bin/manage.py syncdb --migrate'\n if not allow_input:\n cmd += ' --noinput'\n local(cmd)\n\n with hide(*hidden_output):\n if create_env:\n create_virtualenv(env_path)\n\n install_django()\n\n create_project(project_name)\n\n # Change into project directory for next set of commands..\n os.chdir(project_name)\n\n # Ensure manage.py is executable..\n managepy_chmod()\n\n with hide('running'):\n install_deps()\n\n with hide(*hidden_output):\n collect_static()\n\n hidden_output = ['running']\n if not allow_input:\n hidden_output.append('stdout')\n\n # Refrain from blocking stdout due to the prompts..\n with hide(*hidden_output):\n syncdb(allow_input)\n\n print(green('\\nComplete! Copy and paste the following in your shell:\\n'))\n\n if create_env:\n print(green('cd {0}/{1}\\nsource ../bin/activate'.format(env_path, project_name)))\n else:\n print(green('cd {0}'.format(project_name)))\n\n print(green('./bin/manage.py runserver'))\n print(green('\\nOpen up a web browser and go to: http://localhost:8000\\n'))\n\n\nparser.add_argument('project_name', help='Name of the Harvest project. This '\n 'must be a valid Python identifier.')\nparser.add_argument('-v', '--verbose', action='count',\n help='Print stdout output during installation process.')\nparser.add_argument('--no-env', action='store_false', dest='create_env',\n help='Prevents creating a virtualenv and sets up the project in the '\n 'current directory.')\nparser.add_argument('--no-input', action='store_false', dest='allow_input',\n help='Prevents interactive prompts during setup.')\n","sub_path":"harvest/commands/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":4297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"328004771","text":"import ast\n# products_category = {'clothing': {\n# 'T-shirt': [('white', 300), ('black', 400), ('velvet', 500)],\n# 'Shoe': [('black', 5000), ('blue', 3000), ('brown', 4000)]},\n# 'Confectionery':{'chocolates':300, 'biscuits':100, 'lollipop':10},\n# 'Food':{'beans':100,'fish':200, 'rice': 200, 'garri':300, 'meat':400}\n# }\n# products_category = ''''{'clothing': {'T-shirt': 300, 'Shoe': 5000},\n# 'Confectionery':{'chocolates':300, 'biscuits':100, 'lollipop':10},\n# 'Food':{'beans':100,'fish':200, 'rice': 200, 'garri':300, 'meat':400}}'''\n\n\nproducts_file = open('products.txt', 'r')\nproducts_category = ast.literal_eval(products_file.read())\n# product_category = ast.literal_eval(product_category)\nproducts_file.close()\n\n\nun_categorized_products = {}\n\ncart = []\n\ndef display_stock():\n\n print('CATEGORY'.center(15), 'SUB-CATEGORY'.center(13), 'PRICE'.center(10))\n\n for key in products_category:\n\n for item in products_category[key]:\n\n un_categorized_products[item] = products_category[key][item]\n price = products_category[key][item]\n print(key.center(15), item.center(13), f'₦{str(price)}'.center(10))\n\n\ndef add_Item(consumer,_object):\n\n if consumer == 'consumer':\n\n cart.append(_object)\n\n elif consumer == \"admin\":\n\n products_category[_object[0]][_object[1]] = _object[2]\n print(products_category)\n\ndef remove_Item(consumer, item):\n\n if consumer == 'consumer':\n\n if item in cart:\n\n cart.remove(item)\n\n elif consumer == 'admin':\n\n del un_categorized_products[item]\n\ndef bill(item):\n\n bill = 0\n \n for item in cart:\n\n for key in item:\n\n cost = item[key]\n bill += cost\n\n return bill\n \n\nwhile True:\n\n print('welcome to the shopping store')\n prompt = input('please what do you want to do : ')\n\n if prompt == 'add':\n\n display_stock()\n prompt = input('what do you want to add? ')\n\n add_Item(\"consumer\",{prompt:un_categorized_products[prompt]})\n print(f'you now have {cart} in your cart')\n \n continue\n elif prompt == 'bill':\n\n print('Your total bill is', '₦',bill(cart))\n\n elif prompt == 'remove':\n\n print(f'you have {cart}')\n\n delete = input('what you you want to delete? ')\n remove_Item('consumer', {delete:un_categorized_products[delete]})\n print(cart)\n\n elif prompt == 'admin':\n\n while prompt == 'admin':\n\n prompt = input('do you want to add or remove? ')\n\n if prompt == 'add':\n\n key = input('what is the product category? ')\n item_name = input('what do you want to add? ')\n item_price = int(input('how much is the item? '))\n\n add_Item('admin', [key,item_name, item_price])\n open('products.txt', 'w').write(str(products_category))\n\n\n\n prompt = input('are you finished? y/n')\n\n if prompt == 'y':\n\n continue\n\n \n\n # print(f'you have {crt} in your cart and your total bill is ₦{bill}')\n \n# _object = [{'beans':300}, {'fish':400}]\n# delt = {'beans':300}\n# for i in _object:\n# for key in i:\n# print(i[key])\n\n# if delt in _object:\n\n# _object.remove(delt)\n# print(_object)\n\n# cart = dict(_object)\n\n# print(cart)\n \n\n\n \n\n \n\n\n # consumer_response = input('what do you want to add : ')\n # add_Item('consumer', consumer_response,0)\n \n # print(cart)","sub_path":"shopping_app_file.py","file_name":"shopping_app_file.py","file_ext":"py","file_size_in_byte":3611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"581639629","text":"# -*- coding: utf-8 -*-\nfrom os import path\n\n\nclass SassPathResolver:\n def __init__(self, str_path, current_dir, roots, lang, settings, proj_settings):\n self.str_path = str_path\n self.current_dir = current_dir\n self.valid_extensions = settings.get('valid_extensions', {})[lang]\n proj_aliases = proj_settings.get('aliases', {}).get(lang, {})\n self.aliases = settings.get('aliases', {}).get(lang, {})\n self.aliases.update(proj_aliases)\n matching_roots = [root for root in roots if self.current_dir.startswith(root)]\n self.current_root = matching_roots[0] if matching_roots else self.current_dir\n self.lookup_paths = proj_settings.get('lookup_paths', {}).get(lang, []) + settings.get('lookup_paths', {}).get(lang, [])\n\n def resolve(self):\n result = self.resolve_relative_to_dir(self.str_path, self.current_dir)\n if result:\n return result\n\n for alias, alias_source in self.aliases.items():\n result = self.resolve_from_alias(alias, alias_source)\n if result:\n return result\n\n result = self.resolve_in_lookup_paths(self.str_path)\n if result:\n return result\n\n return ''\n\n def resolve_from_alias(self, alias, alias_source):\n path_parts = path.normpath(self.str_path).split(path.sep)\n\n if path_parts[0] == alias:\n path_parts[0] = alias_source\n\n return self.resolve_relative_to_dir(path.join(*path_parts), self.current_root)\n\n def resolve_relative_to_dir(self, target, directory):\n combined = path.realpath(path.join(directory, target))\n return self.resolve_as_file(combined)\n\n def resolve_in_lookup_paths(self, target):\n for lookup_path in self.lookup_paths:\n result = self.resolve_relative_to_dir(target, path.join(self.current_root, lookup_path))\n if result:\n return result\n\n def resolve_as_file(self, path_name):\n if path.isfile(path_name):\n return path_name\n # matching ../variables/palette to ../variables/palette.scss\n for ext in self.valid_extensions:\n file_path = path_name + '.' + ext\n if path.isfile(file_path):\n return file_path\n\n # matching ../variables/palette to ../variables/_palette.scss\n pathname, filename = path.split(path_name)\n combined = path.join(pathname, '_' + filename)\n for ext in self.valid_extensions:\n file_path = combined + '.' + ext\n if path.isfile(file_path):\n return file_path\n","sub_path":"hyper_click/sass_path_resolver.py","file_name":"sass_path_resolver.py","file_ext":"py","file_size_in_byte":2611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"540617348","text":"import keras\nfrom keras import layers\nfrom keras import models\n\ndef _make_divisible(v, divisor, min_value=None):\n if min_value is None:\n min_value = divisor\n new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)\n # Make sure that round down does not go down by more than 10%.\n if new_v < 0.9 * v:\n new_v += divisor\n return new_v\n\ndef _conv_block(inputs, strides, filters, kernel=3):\n \"\"\"\n Adds an initial convolution layer (with batch normalization and relu6).\n \"\"\"\n x = layers.Conv2D(filters, kernel, padding='same', use_bias=False, strides=strides, name='Conv1')(inputs)\n x = layers.BatchNormalization(epsilon=1e-3, momentum=0.999, name='Conv1_bn')(x)\n \n print(x.name, inputs.shape, x.shape)\n \n return layers.ReLU(6., name='Conv1_relu')(x)\n\ndef _sep_conv_block(inputs, filters, alpha, pointwise_conv_filters, depth_multiplier=1, strides=(1, 1)):\n \"\"\"\n Adds a separable convolution block.\n A separable convolution block consists of a depthwise conv,\n and a pointwise convolution.\n \"\"\"\n pointwise_conv_filters = int(pointwise_conv_filters * alpha)\n x = layers.DepthwiseConv2D((3, 3),\n padding='same',\n depth_multiplier=depth_multiplier,\n strides=strides,\n use_bias=False,\n name='Dw_conv_sep')(inputs)\n x = layers.Conv2D(pointwise_conv_filters, (1, 1), padding='valid', use_bias=False, \n strides=strides, name='Conv_sep')(x)\n x = layers.BatchNormalization(epsilon=1e-3, momentum=0.999, name='Conv_sep_bn')(x)\n \n print(x.name, inputs.shape, x.shape)\n \n return layers.ReLU(6., name='Conv_sep_relu')(x)\n \ndef _inverted_res_block(inputs, kernel, expansion, alpha, filters, block_id, stride=1):\n in_channels = inputs._keras_shape[-1]\n pointwise_conv_filters = int(filters * alpha)\n pointwise_filters = _make_divisible(pointwise_conv_filters, 8)\n x = inputs\n prefix = 'block_{}_'.format(block_id)\n \n if block_id:\n x = layers.Conv2D(expansion * in_channels,\n kernel_size=1,\n padding='same',\n use_bias=False,\n activation=None,\n name=prefix + 'expand')(x)\n x = layers.BatchNormalization(epsilon=1e-3,\n momentum=0.999,\n name=prefix + 'expand_bn')(x)\n x = layers.ReLU(6., name=prefix + 'expand_relu')(x)\n else:\n prefix = 'expanded_conv_'\n\n x = layers.DepthwiseConv2D(kernel_size=kernel,\n strides=stride,\n activation=None,\n use_bias=False,\n padding='same',\n name=prefix + 'depthwise')(x)\n x = layers.BatchNormalization(epsilon=1e-3,\n momentum=0.999,\n name=prefix + 'depthwise_bn')(x)\n\n x = layers.ReLU(6., name=prefix + 'depthwise_relu')(x)\n\n x = layers.Conv2D(pointwise_filters,\n kernel_size=1,\n padding='same',\n use_bias=False,\n activation=None,\n name=prefix + 'project')(x)\n x = layers.BatchNormalization(\n epsilon=1e-3, momentum=0.999, name=prefix + 'project_bn')(x)\n\n print(x.name, inputs.shape, x.shape)\n \n if in_channels == pointwise_filters and stride == 1:\n print(\"Adding %s\" % x.name)\n return layers.Add(name=prefix + 'add')([inputs, x])\n return x\n \ndef MnasNet(input_shape=None, alpha=1.0, depth_multiplier=1, pooling=None, nb_classes=10):\n img_input = layers.Input(shape=input_shape)\n \n first_block_filters = _make_divisible(32 * alpha, 8)\n x = _conv_block(img_input, strides=2, filters=first_block_filters)\n\n x = _sep_conv_block(x, filters=16, alpha=alpha, \n pointwise_conv_filters=16, depth_multiplier=depth_multiplier)\n \n x = _inverted_res_block(x, kernel=3, expansion=3, stride=2, alpha=alpha, filters=24, block_id=1)\n x = _inverted_res_block(x, kernel=3, expansion=3, stride=1, alpha=alpha, filters=24, block_id=2)\n x = _inverted_res_block(x, kernel=3, expansion=3, stride=1, alpha=alpha, filters=24, block_id=3)\n \n x = _inverted_res_block(x, kernel=5, expansion=3, stride=2, alpha=alpha, filters=40, block_id=4)\n x = _inverted_res_block(x, kernel=5, expansion=3, stride=1, alpha=alpha, filters=40, block_id=5)\n x = _inverted_res_block(x, kernel=5, expansion=3, stride=1, alpha=alpha, filters=40, block_id=6)\n \n x = _inverted_res_block(x, kernel=5, expansion=6, stride=2, alpha=alpha, filters=80, block_id=7)\n x = _inverted_res_block(x, kernel=5, expansion=6, stride=1, alpha=alpha, filters=80, block_id=8)\n x = _inverted_res_block(x, kernel=5, expansion=6, stride=1, alpha=alpha, filters=80, block_id=9)\n\n x = _inverted_res_block(x, kernel=3, expansion=6, stride=1, alpha=alpha, filters=96, block_id=10)\n x = _inverted_res_block(x, kernel=3, expansion=6, stride=1, alpha=alpha, filters=96, block_id=11)\n \n x = _inverted_res_block(x, kernel=5, expansion=6, stride=2, alpha=alpha, filters=192, block_id=12)\n x = _inverted_res_block(x, kernel=5, expansion=6, stride=1, alpha=alpha, filters=192, block_id=13)\n x = _inverted_res_block(x, kernel=5, expansion=6, stride=1, alpha=alpha, filters=192, block_id=14)\n x = _inverted_res_block(x, kernel=5, expansion=6, stride=1, alpha=alpha, filters=192, block_id=15)\n \n x = _inverted_res_block(x, kernel=3, expansion=6, stride=1, alpha=alpha, filters=320, block_id=16)\n \n if pooling == 'avg':\n x = layers.GlobalAveragePooling2D()(x)\n else:\n x = layers.GlobalMaxPooling2D()(x)\n \n x = layers.Dense(nb_classes, activation='softmax', use_bias=True, name='proba')(x)\n \n inputs = img_input\n \n model = models.Model(inputs, x, name='mnasnet')\n return model\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"434130274","text":"def is_abundant(n: int) -> bool:\n \"\"\"\n >>> is_abundant(12)\n True\n \"\"\"\n divisors = [x for x in range(1, n//2 + 1) if n % x == 0]\n return sum(divisors) > n\n\n# abundant_list = [x for x in range(1, 28124) if is_abundant(x)]\nfile = open(\"abundant_nums23.txt\", \"r\") # file of [x for x in range(1, 28124) if is_abundant(x)]\nabundant_list = eval(file.read())\n\n\nlst = []\nfor x in abundant_list:\n for y in abundant_list:\n if x + y > 28123:\n break\n lst.append(x+y)\n print(x)\nlst = set(lst)\nnums = [x for x in range(1, 28124)]\nnums = set(nums)\nnums = nums - lst\nprint(sum(nums))\n","sub_path":"ProjEuler/ex23.py","file_name":"ex23.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"644632067","text":"#!/usr/bin/env python2.7\n# -*- coding:UTF-8 -*-2\nu\"\"\"sorcery.__init__.py\n\nCopyright(c)2019 Yukio Kuro\nThis software is released under BSD license.\n\n魔術パッケージ。\n\"\"\"\nimport data as __data\nget = __data.get\nget_all = __data.get_all\n\n\ndef init():\n u\"\"\"パッケージ初期化。\n \"\"\"\n import config as __config\n __config.init()\n","sub_path":"Source/armament/sorcery/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"224591790","text":"# -*- coding:utf-8 -*-\nfrom selenium import webdriver \nimport os \nimport time\nabspath = os.path.abspath(r\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe\") \ndriver = webdriver.Chrome(abspath) \n\ndriver.get('http://www.yopmail.com/zh/email-generator.php')\ntime.sleep(1)\nemail = driver.find_element_by_id(\"login\")\nemail = email.get_attribute('value')\nprint(email)\n\n#打开邮箱页面后,我发现,邮箱的内容是以iframe的形式展现的,所以,这地方要处理一下:\n# driver.switch_to_frame(driver.find_element_by_id('ifmail'))\ntry:\n html = driver.find_element_by_id('login')\nexcept Exception as e:\n input('遇到机器识别的问题,切换到浏览器点击一下,验证完敲一下回车')\n html = driver.find_element_by_id('login')\nhtml = html.text\nprint(html)\n# active_url = html.split('account:')[1].strip()\ndriver.delete_all_cookies()\ntime.sleep(1)","sub_path":"seleniumTest.py","file_name":"seleniumTest.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"560183936","text":"#!venv/bin/python\n\nimport hashlib\nimport base64\nimport time\nfrom os import unlink, path, getenv, listdir, mkdir, urandom\nfrom shutil import rmtree\nfrom threading import Thread\nfrom random import randint\nfrom sys import stderr, exit\n\nfrom flask import (\n Flask,\n render_template,\n jsonify,\n request,\n redirect,\n send_from_directory,\n)\nfrom flask_dropzone import Dropzone\nfrom argparse import ArgumentParser\nfrom werkzeug.utils import secure_filename\n\napp = Flask(__name__)\napp.config[\"SECRET_KEY\"] = \"You should change this value!\"\n# app.jinja_env.trim_blocks = True\n# app.jinja_env.lstrip_blocks = True\n\napp.config[\"PREFERRED_URL_SCHEME\"] = \"https\"\napp.config[\"DROPZONE_SERVE_LOCAL\"] = True\napp.config[\"DROPZONE_MAX_FILE_SIZE\"] = 128\napp.config[\"DROPZONE_UPLOAD_MULTIPLE\"] = True\napp.config[\"DROPZONE_PARALLEL_UPLOADS\"] = 10\n\napp.config[\"DROPZONE_ALLOWED_FILE_CUSTOM\"] = True\napp.config[\"DROPZONE_ALLOWED_FILE_TYPE\"] = \"\"\n\napp.config[\n \"DROPZONE_DEFAULT_MESSAGE\"\n] = \"Ziehe die Dateien hier hin, um sie hochzuladen oder klicken Sie zur Auswahl.\"\n\ndropzone = Dropzone(app)\n\nbasedir = getenv(\"FILER_BASEDIR\", \"./Daten\")\npublicdir = getenv(\"FILER_PUBLICDIR\", \"Public\")\ndocumentsdir = getenv(\"FILER_DOCUMENTSDIR\", \"Dokumente\")\nclientsdir = getenv(\"FILER_CLIENTSSDIR\", \"Mandanten\")\n\nfilettl = int(getenv(\"FILER_FILETTL\", 10))\n\n#### ADMIN FACING DIRECTORY LISTS ####\n####\n####\n@app.route(\"/admin\", methods=[\"GET\"])\ndef admin():\n url_root = request.url_root.replace(\"http://\", \"https://\", 1)\n users = listdir(path.join(basedir, clientsdir))\n return render_template(\n \"admin.html\",\n users=users,\n tree=make_tree(basedir, publicdir, False),\n url_root=url_root,\n documentsdir=documentsdir,\n )\n\n\n@app.route(\"/admin/\" + documentsdir + \"/\", methods=[\"GET\"])\ndef admin_dokumente(user):\n return render_template(\n \"mandant.html\",\n admin=\"admin/\",\n user=user,\n tree=make_tree(basedir, path.join(documentsdir, user)),\n documentsdir=documentsdir,\n )\n\n\n@app.route(\"/admin/del-user/\", methods=[\"POST\"])\ndef admin_deluser(user):\n method = request.form.get(\"_method\", \"POST\")\n if method == \"DELETE\":\n rmtree(path.join(basedir, documentsdir, secure_filename(user)))\n unlink(path.join(basedir, clientsdir, secure_filename(user)))\n return redirect(\"/admin\")\n\n\n@app.route(\"/admin/new-user\", methods=[\"POST\"])\ndef admin_newuser():\n password = request.form.get(\"password\", \"\")\n user = request.form.get(\"user\", \"\")\n if not password or not user:\n return \"Username or password missing\", 400\n directory = secure_filename(user)\n\n salt = urandom(4)\n sha = hashlib.sha1(password.encode(\"utf-8\"))\n sha.update(salt)\n\n digest_salt_b64 = base64.b64encode(sha.digest() + salt)\n tagged_digest_salt = \"{{SSHA}}{}\".format(digest_salt_b64.decode(\"ascii\"))\n\n try:\n if not path.exists(path.join(basedir, documentsdir, directory)):\n mkdir(path.join(basedir, documentsdir, directory))\n with open(\n path.join(basedir, clientsdir, directory), \"w+\", encoding=\"utf-8\"\n ) as htpasswd:\n htpasswd.write(\"{}:{}\\n\".format(user, tagged_digest_salt))\n except OSError as error:\n return \"Couldn't create user scope\", 500\n return redirect(\"/admin\")\n\n\n#### USER FACING DIRECTORY LIST ####\n####\n####\n@app.route(\"/\" + documentsdir + \"/\", methods=[\"GET\"])\ndef mandant(user):\n return render_template(\n \"mandant.html\",\n admin=\"\",\n user=user,\n tree=make_tree(basedir, path.join(documentsdir, user)),\n documentsdir=documentsdir,\n )\n\n\n#### UPLOAD FILE ROUTES ####\n####\n####\n@app.route(\"/\" + documentsdir + \"/\", methods=[\"POST\"])\n@app.route(\"/admin/\" + documentsdir + \"/\", methods=[\"POST\"])\ndef upload_mandant(user):\n for key, f in request.files.items():\n if key.startswith(\"file\"):\n username = secure_filename(user)\n filename = secure_filename(f.filename)\n f.save(path.join(basedir, documentsdir, username, filename))\n return \"upload template\"\n\n\n@app.route(\"/admin\", methods=[\"POST\"])\ndef upload_admin():\n for key, f in request.files.items():\n if key.startswith(\"file\"):\n filename = secure_filename(f.filename)\n f.save(path.join(basedir, publicdir, filename))\n return \"upload template\"\n\n\n#### DELETE FILE ROUTES ####\n####\n####\n@app.route(\"/\" + documentsdir + \"//\", methods=[\"POST\"])\ndef delete_file_mandant(user, filename):\n method = request.form.get(\"_method\", \"POST\")\n if method == \"DELETE\":\n unlink(\n path.join(\n basedir, documentsdir, secure_filename(user), secure_filename(filename)\n )\n )\n return redirect(\"/\" + documentsdir + \"/\" + user)\n\n\n@app.route(\"/admin/\" + documentsdir + \"//\", methods=[\"POST\"])\ndef delete_file_mandant_admin(user, filename):\n method = request.form.get(\"_method\", \"POST\")\n if method == \"DELETE\":\n unlink(\n path.join(\n basedir, documentsdir, secure_filename(user), secure_filename(filename)\n )\n )\n return redirect(\"/admin/\" + documentsdir + \"/\" + user)\n\n\n@app.route(\"/admin/\" + publicdir + \"/\", methods=[\"POST\"])\ndef delete_file_admin(filename):\n method = request.form.get(\"_method\", \"POST\")\n if method == \"DELETE\":\n unlink(path.join(basedir, publicdir, secure_filename(filename)))\n return redirect(\"/admin\")\n\n\n#### SERVE FILES RULES ####\n####\n####\n@app.route(\"/admin/\" + documentsdir + \"//\", methods=[\"GET\"])\n@app.route(\"/\" + documentsdir + \"//\", methods=[\"GET\"])\ndef custom_static(user, filename):\n return send_from_directory(\n path.join(basedir, documentsdir), path.join(user, filename)\n )\n\n\n@app.route(\"/\" + publicdir + \"/\")\ndef custom_static_public(filename):\n return send_from_directory(path.join(basedir, publicdir), filename)\n\n\ndef make_tree(rel, pathname, clean_expired = True):\n tree = dict(name=pathname, download=path.basename(pathname), children=[])\n try:\n lst = listdir(path.join(rel, pathname))\n except OSError:\n pass # ignore errors\n else:\n for name in lst:\n fn = path.join(pathname, name)\n if path.isdir(path.join(rel, fn)):\n tree[\"children\"].append(make_tree(rel, fn, clean_expired))\n else:\n ttl = filettl - int(\n (time.time() - path.getmtime(path.join(rel, fn))) / (24 * 3600)\n )\n if clean_expired and ttl < 0:\n unlink(path.join(rel, fn))\n else:\n tree[\"children\"].append(dict(name=fn, download=name, ttl=ttl))\n return tree\n\n\n# Start a cleaner thread that will trigger make_tree's side effect of\n# wiping old files\ndef cleaner_thread():\n while True:\n make_tree(basedir, documentsdir)\n # sleep for 6h plus jitter\n time.sleep(21600 + randint(1, 1800))\n\n\nthread = Thread(target=cleaner_thread, args=())\nthread.daemon = True\nthread.start()\n\n# Ensure all working directories are there\ntry:\n for datadir in (\n basedir,\n path.join(basedir, documentsdir),\n path.join(basedir, clientsdir),\n path.join(basedir, publicdir),\n ):\n if not path.exists(datadir):\n mkdir(datadir)\nexcept:\n stderr.write(\"Error: Basedir not accessible\\n\")\n exit(1)\n\nif __name__ == \"__main__\":\n parser = ArgumentParser(description=\"Filer\")\n parser.add_argument(\n \"-H\",\n \"--host\",\n help=\"Hostname of the Flask app \" + \"[default %s]\" % \"127.0.0.1\",\n default=\"127.0.0.1\",\n )\n parser.add_argument(\n \"-P\",\n \"--port\",\n help=\"Port for the Flask app \" + \"[default %s]\" % \"5000\",\n default=\"5000\",\n )\n\n args = parser.parse_args()\n\n app.run(host=args.host, port=int(args.port))\n","sub_path":"Filer.py","file_name":"Filer.py","file_ext":"py","file_size_in_byte":8019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"19227588","text":"#Karen Liang 45492235 and Derek Yang 63118832\n\nfrom collections import namedtuple\nimport socket\nimport connectfour\n\n#ask for host and port\n#ask for username\n#connect\n#error if unable to connect and close program\n#run console if connection is succesful\n#red player is user, yellow player is program\n\nhost = 'woodhouse.ics.uci.edu'\nport = 4444\nuser = 'username'\n\n\nConnectFourConnection = namedtuple ('ConnectFourConnection', ['c4socket', 'c4input', 'c4output'])\n\nclass c4error (Exception):\n pass\n\ndef connect () -> ConnectFourConnection:\n host = get_host()\n port = get_port()\n \n connectfour_socket = socket.socket ()\n print ('connecting')\n \n try:\n connectfour_socket.connect ((host, port))\n print ('connected')\n except socket.gaierror:\n print ('Error! Invalid host or port.')\n raise SystemExit\n \n connectfour_input = connectfour_socket.makefile ('r')\n connectfour_output = connectfour_socket.makefile ('w')\n \n return ConnectFourConnection (\n c4socket = connectfour_socket,\n c4input = connectfour_input,\n c4output = connectfour_output)\n\n\ndef get_host ()-> str:\n while True:\n ConnectFourHost= input ('Enter host name: ').strip ()\n if ConnectFourHost == '':\n print ('Error! Incorrect host name')\n else:\n return ConnectFourHost\n \ndef get_port () -> int:\n while True:\n try:\n ConnectFourPort = int (input ('Enter port number: ').strip ())\n\n if (ConnectFourPort < 0) or (ConnectFourPort > 65535):\n print ('Error! Port must be an integer between 0 and 65535.')\n else:\n return ConnectFourPort\n except ValueError:\n print ('Error! Port must be an integer between 0 and 65535.')\n\n\ndef get_user () -> str:\n while True:\n ConnectFourUser= input ('Enter username: ')\n if ' ' in ConnectFourUser:\n print (\"Error! Username can not contain whitespaces.\")\n return ConnectFourUser\n\ndef _read_line (connection: ConnectFourConnection) -> str:\n return connection.c4input.readline () [:-1]\n\n\ndef _write_line(ConnectFourConnection, line: str) -> None:\n ConnectFourConnection.c4output.write(line + '\\r\\n')\n ConnectFourConnection.c4output.flush()\n\n\ndef close (connection: ConnectFourConnection) -> None:\n connection.c4input.close ()\n connection.c4output.close ()\n connection.socket.close ()\n\n\n##def send (connection: ConnectFourConnection, message:str, expected:str) -> None:\n## _write_line (connection, 'Sending' + message)\n## _expect_line (connection, expected + '\\r\\n')\n\n\n\n##def _expect_line (connection: ConnectFourConnection, expected: str)-> None:\n## line = _read_line (connection)\n## if line != expected:\n## raise c4error\n \n\n##def test () -> None:\n## c4connection = connect ()\n## print (_read_line (c4connection))\n## while True:\n## try:\n## (c4connection, 'I32CFSP_HELLO ' + user, 'WELCOME ' + user)\n## except c4error:\n## print ('error')\n","sub_path":"project 2/Others/ConnectFourProtocol.py","file_name":"ConnectFourProtocol.py","file_ext":"py","file_size_in_byte":3073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"592343102","text":"\nfrom airflow import DAG\nfrom datetime import datetime, timedelta\n\nfrom airflow.operators.dummy_operator import DummyOperator\nfrom airflow.operators.email_operator import EmailOperator\nfrom airflow.contrib.operators.ssh_operator import SSHOperator\nfrom airflow.sensors.named_hive_partition_sensor import NamedHivePartitionSensor\n\nfrom dsp_airflow.spark_submit import SSHSparkSubmitOperator\nfrom dsp_airflow.hiveserver2_hive_operator import HiveServer2HiveOperator\n\n\ndefault_args = {\n\t'owner': 'ceasterwood',\n\t'depends_on_past': False,\n\t'start_date': datetime(2019, 10, 1),\n\t'email': ['ceasterwood@groupon.com'],\n\t'email_on_failure': True,\n\t'email_on_retry': True,\n\t'retries': 1,\n}\n\n#############\n# LOCATIONS #\n#############\n\n# Local\nDEACT_DIR = '/home/svc_clv/Consumer-Intelligence/Models/Deact-Model'\n\n# HDFS\n# HDFS_DIR = 'hdfs://cerebro-namenode-vip.snc1/user/grp_gdoop_clv/deact-model/'\nHIVE_DB = 'grp_gdoop_clv_db'\n\n# Spark\nPYTHON_DIR = './ANACONDA/anaconda2_env/bin/python'\nARCHIVES_DIR = 'hdfs:////user/grp_gdoop_admin/anaconda/anaconda2_env.zip#ANACONDA'\nWAREHOUSE_DIR = 'hdfs://cerebro-namenode-vip.snc1/user/grp_gdoop_clv/grp_gdoop_clv_hiveDB.db'\n\nTARGET_DATA_DAYS = 3\n\n\n###################\n# MODEL VARIABLES #\n###################\n\ndef date_add(date_str, days):\n\treturn datetime.strftime(datetime.strptime(date_str, '%Y-%m-%d') + timedelta(days=days), '%Y-%m-%d')\n\n\ntoday = datetime.strftime(datetime.utcnow(), '%Y-%m-%d')\ntrain_date = date_add(today, -366)\nscore_date = date_add(today, -1)\ntrain_pct = 0.10\ncalibrate_pct = 0.10\nvalidate_pct = 0.10\ncalibrate_model = True\nvalidate_model = False\nscore_active_users = True\nmask_prob = True\nmask_days = 3\n\n\n#######\n# DAG #\n#######\n\n# Task Generators\n\ndef verify_partition_task(table_suffix, record_date):\n\ttask = NamedHivePartitionSensor(\n\t\ttask_id='verify_{0}_partition'.format(table_suffix),\n\t\tmetastore_conn_id='svc_push_ds_hive_cerebro_metastore',\n\t\tpartition_names=['{0}.keep_cdf_final_features_{1}/record_date={2}'.format(HIVE_DB, table_suffix, record_date)],\n\t\ttimeout=60*60*6 # Wait 6 hours to see if partition arrives\n\t)\n\treturn task\n\n\ndef add_partition_task(table, date):\n\ttask = HiveServer2HiveOperator(\n\t\ttask_id='add_{0}_partition'.format(table),\n\t\thqls='alter table {0}.ce_keep_deact_{1} add if not exists partition(record_date = \"{2}\")'\n\t\t\t.format(HIVE_DB, table, date),\n\t\thiveserver2_conn_id='hive_cerebro_prod',\n\t\tschema=HIVE_DB,\n\t)\n\treturn task\n\n\ndef drop_partition_task(table, date):\n\ttask = HiveServer2HiveOperator(\n\t\ttask_id='drop_old_{0}_partition'.format(table),\n\t\thqls='alter table {0}.ce_keep_deact_{1} drop if exists partition(record_date <= \"{2}\")'\n\t\t\t.format(HIVE_DB, table, date),\n\t\thiveserver2_conn_id='hive_cerebro_prod',\n\t\tschema=HIVE_DB,\n\t\t)\n\treturn task\n\n\ndef partition_stats_task(table, date):\n\ttask = HiveServer2HiveOperator(\n\t\ttask_id='{0}_partition_stats'.format(table),\n\t\thqls='analyze table {0}.ce_keep_deact_{1} partition(record_date = \"{2}\") compute statistics'\n\t\t\t.format(HIVE_DB, table, date),\n\t\thiveserver2_conn_id='hive_cerebro_prod',\n\t\tschema=HIVE_DB,\n\t\t)\n\treturn task\n\n\ndef ssh_task(task_id, command):\n\ttask = SSHOperator(\n\t\ttask_id=task_id,\n\t\tssh_conn_id='ssh_clv_job_submitter',\n\t\tcommand=command,\n\t)\n\treturn task\n\n\n# DAG\n\nwith DAG(dag_id='deact-model',\n\tschedule_interval='00 09 * * *',\n\tcatchup=False,\n\tmax_active_runs=2,\n\tdefault_args=default_args,\n\tdescription=__doc__,) as dag:\n\n\t################\n\t# TARGET TABLE #\n\t################\n\n\ttarget_data_drop_date = date_add(train_date, -TARGET_DATA_DAYS)\n\tverify_t365d_partition = verify_partition_task('t365d', train_date)\n\n\ttarget_tbl = HiveServer2HiveOperator(\n\t\ttask_id='target_tbl',\n\t\thqls='target.sql',\n\t\thiveserver2_conn_id='hive_cerebro_prod',\n\t\tschema=HIVE_DB,\n\t\thive_conf={\n\t\t\t'mapred.job.queue.name': 'clv',\n\t\t\t'hive.exec.copyfile.maxsize': 7516192768,\n\t\t},\n\t\tparams={'feature_date': train_date, 'today': today}\n\t\t)\n\n\ttarget_partition_stats = partition_stats_task('target', train_date)\n\tdrop_old_target = drop_partition_task('target', target_data_drop_date)\n\n\t####################################################\n\t# TRAIN DEACT MODEL, EVALUATE IT, MAKE PREDICTIONS #\n\t####################################################\n\n\tapp_args = [\n\t\t'--train_date', train_date,\n\t\t'--train_pct', train_pct,\n\t\t]\n\n\tif calibrate_model:\n\t\tapp_args.extend(['--calibrate_model', '--calibrate_pct', calibrate_pct])\n\n\tif validate_model:\n\t\tapp_args.extend(['--validate_model', '--validate_pct', validate_pct])\n\n\tif score_active_users:\n\t\tapp_args.extend(['--score_active_users', '--score_date', score_date])\n\n\tif mask_prob:\n\t\tapp_args.extend(['--mask_prob', '--mask_days', mask_days])\n\n\tdeact_model = SSHSparkSubmitOperator(\n\t\ttask_id='deact_model',\n\t\thdfs_application_file='{0}/run.py'.format(DEACT_DIR), # Python file with Spark job\n\t\tapplication_args=app_args, # Arguments for run.py file\n\t\tqueue='public',\n\t\tspark_config_dict={\n\t\t\t'spark.app.name': 'deact-model',\n\t\t\t'spark.master': 'yarn',\n\t\t\t'spark.submit.deployMode': 'client',\n\t\t\t# 'spark.yarn.queue': 'public',\n\t\t\t'spark.driver.memory': '50g',\n\t\t\t'spark.executor.memory': '50g',\n\t\t\t'spark.executor.instances': 50,\n\t\t\t'spark.yarn.appMasterEnv.PYSPARK_PYTHON': PYTHON_DIR,\n\t\t\t'spark.yarn.dist.archives': ARCHIVES_DIR,\n\t\t\t'spark.sql.warehouse.dir': WAREHOUSE_DIR,\n\t\t\t},\n\t\tssh_conn_id='ssh_clv_job_submitter',\n\t\t)\n\n\tif validate_model:\n\t\tpapermill_command = 'papermill {0} {0} -p today {1} -p train_date {2}'\\\n\t\t\t.format(DEACT_DIR+'/model_evaluation/Deact_Model_Eval.ipynb', today, train_date)\n\n\t\trefresh_jupyter = ssh_task('refresh_jupyter', papermill_command)\n\n\t\tgit_command = '''cd {0} && git pull && git add model_evaluation/ &&\n\t\t\tgit commit -m \"refreshing evaluation results from {1}\" && git push origin master'''\\\n\t\t\t.format(DEACT_DIR, train_date)\n\n\t\tupdate_git = DummyOperator(task_id='update_git')\n\t\t# update_git = ssh_task('update_git', git_command)\n\n\tif score_active_users:\n\t\tverify_scoring_partition = verify_partition_task('scoring', score_date)\n\t\tadd_predictions_partition = add_partition_task('predictions', score_date)\n\t\tadd_totals_partition = add_partition_task('totals', score_date)\n\n\t#################\n\t# SUCCESS EMAIL #\n\t#################\n\n\tif calibrate_model:\n\t\tcalibrate_str = '
  • Calibrated model on {0:0.0%} of the data from {1}
  • '.format(calibrate_pct, train_date)\n\telse:\n\t\tcalibrate_str = '
  • Did not calibrate the model
  • '\n\n\tif mask_prob:\n\t\tmask_str = '
  • Applied probability mask to customers deactivating in the next {0:d} days
  • '.format(mask_days)\n\telse:\n\t\tmask_str = '
  • Did not apply a probability mask
  • '\n\n\tif validate_model:\n\t\tvalidate_str = '''
  • Validated model on {0:0.0%} of the data from {1}
  • \n\t\t\t
  • Saved results of model evaluation to: {2}/model_evaluation/
  • '''\\\n\t\t\t.format(validate_pct, train_date, DEACT_DIR) # ADD LOCATION\n\telse:\n\t\tvalidate_str = '
  • Did not validate the model
  • '\n\n\tif score_active_users:\n\t\tscore_str = '''
  • Scored active users from {0}
  • \n\t\t\t
  • Added partition to {1}.ce_keep_deact_predictions for {0}
  • \n\t\t\t
  • Added partition to {1}.ce_keep_deact_totals for {0}
  • '''.format(score_date, HIVE_DB)\n\telse:\n\t\tscore_str = '
  • Did not score active users
  • '\n\n\tsuccess_email = EmailOperator(\n\t\ttask_id='success_email',\n\t\tto=['ceasterwood@groupon.com'],\n\t\tsubject='Deact Model Success {0}'.format(train_date),\n\t\thtml_content='''

    Workflow Completed Successfully!

    \n\t\t\t

    1. Added partition to {0}.ce_keep_deact_target for {1}
    2. \n\t\t\t
    3. Removed partitions from {0}.ce_keep_deact_target for {2} and earlier
    4. \n\t\t\t
    5. Trained deact model on {3:0.0%} of the data from {1}
    6. \n\t\t\t{4}{5}{6}{7}\n\t\t\t

    '''.format(HIVE_DB, train_date, target_data_drop_date, train_pct,\n\t\t\t\tcalibrate_str, mask_str, validate_str, score_str),\n\t\t)\n\n\t#######################\n\t# ORDER OF OPERATIONS #\n\t#######################\n\n\tverify_t365d_partition >> target_tbl >> [target_partition_stats, drop_old_target]\n\ttarget_partition_stats >> deact_model\n\n\tif validate_model:\n\t\tdeact_model >> refresh_jupyter >> update_git >> success_email\n\tif score_active_users:\n\t\ttarget_tbl >> verify_scoring_partition >> \\\n\t\t\t[deact_model, add_predictions_partition, add_totals_partition] >> success_email\n\tif not validate_model and not score_active_users:\n\t\tdeact_model >> success_email\n","sub_path":"demodel/deact_dag.py","file_name":"deact_dag.py","file_ext":"py","file_size_in_byte":8257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"134239171","text":"from __future__ import print_function\nimport logging\nfrom scrapy.responsetypes import responsetypes\nfrom scrapy.utils.request import request_fingerprint\nfrom scrapy.utils.python import to_bytes\nfrom scrapy.http.headers import Headers\nfrom elasticsearch_dsl import DocType, Date, Integer, Text, connections\nfrom datetime import datetime\nfrom webcrawler_plus.settings import DATA_COLLECTION, DATABASE\nfrom webcrawler_plus.utils.url import get_urn, get_domain\n\nlogger = logging.getLogger(__name__)\n\n\nclass WebLink(DocType):\n url = Text()\n html = Text()\n headers = Text()\n status = Integer()\n created = Date()\n\n class Meta:\n index = DATABASE\n doc_type = DATA_COLLECTION\n\n\nclass ESCacheStorage(object):\n \"\"\"\n should set HTTPCACHE_ES_DATABASE in the settings.py\n\n\n \"\"\"\n COLLECTION_NAME = \"weblinks\"\n\n def __init__(self, settings):\n self.database = settings['HTTPCACHE_ES_DATABASE']\n self.database_host = settings.get('HTTPCACHE_HOST', '127.0.0.1')\n connections.create_connection(hosts=[self.database_host])\n WebLink.init()\n\n self.expiration_secs = settings.getint('HTTPCACHE_EXPIRATION_SECS')\n\n def open_spider(self, spider):\n logger.debug(\"Using elastic cache storage with index name %(database)s\" % {'database': self.database},\n extra={'spider': spider})\n\n def close_spider(self, spider):\n pass\n\n def get_headers(self, obj):\n \"\"\"\n this will convert all the headers_Server, headers_Date\n into \"header\": {\n \"Server\": \"\",\n \"Date\": \"\"\n }\n\n :param obj:\n :return:\n \"\"\"\n headers = {}\n for k, v in obj.items():\n if k.startswith(\"headers_\"):\n headers[k.replace(\"headers_\", \"\")] = v\n\n obj['headers'] = headers\n return obj\n\n def retrieve_response(self, spider, request):\n data = self._read_data(spider, request)\n\n if data is None:\n return # not cached\n else:\n if data['status'] == 200 and data['html'] is None:\n return None\n\n data = self.get_headers(data)\n url = data['url']\n status = data['status']\n headers = Headers(data['headers'])\n body = bytes(data['html'], encoding=\"utf-8\")\n respcls = responsetypes.from_args(headers=headers, url=url)\n response = respcls(url=url, headers=headers, status=status, body=body)\n return response\n\n def _clean_headers(self, obj):\n cleaned_object = {}\n for k, v in obj.items():\n cleaned_object[k.decode('utf-8')] = v[0].decode('utf-8')\n return cleaned_object\n\n def _flatten_headers(self, obj):\n flat_data = {}\n for k, v in obj.items():\n flat_data['headers_{}'.format(k)] = v\n return flat_data\n\n def store_response(self, spider, request, response):\n data = {\n 'status': response.status,\n 'domain': get_domain(response.url),\n 'url': response.url,\n 'html': str(response.body).lstrip(\"b'\").strip(\"'\")\n .replace(\"\\\\n\", \"\")\n .replace(\"\\\\t\", \"\")\n .replace(\"\\\\\\\\\", \"\\\\\"),\n 'created': datetime.now()\n }\n data.update(self._flatten_headers(self._clean_headers(response.headers)))\n WebLink(meta={'id': get_urn(response.url)}, **data).save()\n\n def _read_data(self, spider, request):\n try:\n return WebLink.get(id=get_urn(request.url)).to_dict()\n except Exception as e:\n return None\n\n def _request_key(self, request):\n return to_bytes(request_fingerprint(request))\n","sub_path":"webcrawler_plus/httpcache/elasticsearch.py","file_name":"elasticsearch.py","file_ext":"py","file_size_in_byte":3687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"237763183","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCopyright 2013-2014 Olivier Cortès \n\nThis file is part of the sparks project.\n\nIt provides {python,django}-social-auth pipeline helpers.\n\nAs soon as I used them in 2 projets I manage, I moved them\nto sparks to mutualize the code.\n\n1flow is free software: you can redistribute it and/or modify\nit under the terms of the GNU Affero General Public License as\npublished by the Free Software Foundation, either version 3 of\nthe License, or (at your option) any later version.\n\n1flow is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public\nLicense along with 1flow. If not, see http://www.gnu.org/licenses/\n\"\"\"\n\nimport logging\n\nfrom constance import config\n\nfrom django.shortcuts import redirect\n\nfrom social_auth.backends.facebook import FacebookBackend\nfrom social_auth.backends.twitter import TwitterBackend\nfrom social_auth.backends import google\n\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef get_social_avatar(social_user, user, details, request, response, backend,\n is_new=False, *args, **kwargs):\n \"\"\" Get the user's social avatar and store it in social-auth's DB.\n\n Current implementation handles facebook, Google (oauth2) and Twitter.\n\n \"\"\"\n\n try:\n url = None\n\n if isinstance(backend, FacebookBackend):\n if 'id' in response:\n url = u'http://graph.facebook.com/{}/picture?type=large'.format(\n response['id'])\n\n elif isinstance(backend, google.GoogleOAuth2Backend):\n url = response.get('picture', None)\n\n elif isinstance(backend, TwitterBackend):\n url = response.get('profile_image_url', None)\n\n if url:\n mongo_user = user.mongo\n\n if mongo_user.avatar_url != url:\n mongo_user.avatar_url = url\n mongo_user.save()\n\n LOGGER.info(u'Saved new avatar for user %s from backend %s.',\n user, social_user)\n\n # avatar = urlopen(url)\n # photo = Photo(author=user, is_avatar=True)\n # photo.picture.save(slugify(user.username+\"social\") + '.jpg',\n # ContentFile(avatar.read()))\n # photo.save()\n\n except:\n LOGGER.exception(u'Could not get avatar for user %s from '\n u'backend %s.', user, social_user)\n\n\ndef throttle_new_user_accounts(social_user, user, details, request,\n response, backend, is_new=False,\n *args, **kwargs):\n \"\"\" Deactivate newly created users if registrations are closed.\n\n They are also redirected to the ``social_signup_closed`` page to\n inform them about what's going on.\n\n .. note:: accounts still get created in the database, and we keep them.\n This is intended to be able to contact users if registrations are\n opened again later.\n \"\"\"\n\n if is_new and not config.SOCIAL_REGISTRATION_ENABLED:\n\n user.is_active = False\n user.save()\n\n LOGGER.warning(u'De-activated new user account %s from backend %s on '\n u'the fly because social registrations are currently '\n u'disabled.', user, social_user)\n\n # Wrap the 'official' account view to signify the user we are closed.\n return redirect('social_signup_closed')\n","sub_path":"sparks/django/social_pipeline.py","file_name":"social_pipeline.py","file_ext":"py","file_size_in_byte":3591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"119212852","text":"import sys\nimport os\nimport time\nimport marshal\nimport re\nfrom functools import cmp_to_key\n\nif __name__ == '__main__':\n \n import cmd\n try:\n import readline\n except ImportError:\n pass\n\n class ProfileBrowser(cmd.Cmd):\n def __init__(self, profile=None):\n cmd.Cmd.__init__(self)\n self.prompt = \"% \"\n self.stats = None\n self.stream = sys.stdout\n\n def generic_help(self):\n print(\"Arguments may be:\", file=self.stream)\n print(\"* An integer maximum number of entries to print.\", file=self.stream)\n print(\"* A decimal fractional number between 0 and 1, controlling\", file=self.stream)\n print(\" what fraction of selected entries to print.\", file=self.stream)\n print(\"* A regular expression; only entries with function names\", file=self.stream)\n print(\" that match it are printed.\", file=self.stream)\n\n def do_callees(self, line):\n return self.generic('print_callees', line)\n \n def do_quit(self, line):\n print('xxxxxx')\n return 1\n \n def help_quit(self):\n print(\"Leave the profile brower.\", file=self.stream)\n\n def do_test(self):\n print('test')\n print(\"AALeave the profile brower.\", file=self.stream)\n self.generic_help()\n\n def help_stats(self):\n print(\"Print statistics from the current stat object.\", file=self.stream)\n self.generic_help()\n\n def postcmd(self, stop, line):\n if stop:\n return stop\n return None\n\n\n\n\ninitprofile = None\nbrowser = ProfileBrowser(initprofile)\n\nprint('1')\nbrowser.do_test()\n\nprint('6-------')\n\nprint(\"Welcome to the profile statistics browser.\", file = browser.stream)\nbrowser.cmdloop()\n\nprint(\"Goodbye.\", file = browser.stream)\n\n\n","sub_path":"_4.python/__code/python-master/Lib/pstats.py","file_name":"pstats.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"70012706","text":"#!/usr/bin/env python\n\nimport unittest\nimport sys\nimport os\nimport shutil\nimport itertools\nfrom copy import copy\nimport types\nimport signal\nimport tempfile\n\nfrom config.experiment_config_lib import ControllerConfig\nfrom sts.control_flow import Replayer, MCSFinder, EfficientMCSFinder\nfrom sts.topology import FatTree, MeshTopology\nfrom sts.simulation_state import Simulation, SimulationConfig\nfrom sts.replay_event import Event, InternalEvent, InputEvent\nfrom sts.event_dag import EventDag\nfrom sts.entities import Host, Controller\nimport logging\n\nsys.path.append(os.path.dirname(__file__) + \"/../../..\")\n\nclass MockMCSFinderBase(MCSFinder):\n ''' Overrides self.invariant_check and run_simulation_forward() '''\n def __init__(self, event_dag, mcs):\n super(MockMCSFinderBase, self).__init__(None, None,\n invariant_check_name=\"InvariantChecker.check_liveness\")\n # Hack! Give a fake name in config.invariant_checks.name_to_invariant_checks, but\n # but remove it from our dict directly after. This is to prevent\n # sanity check exceptions from being thrown.\n self.invariant_check = self._invariant_check\n self.dag = event_dag\n self.new_dag = None\n self.mcs = mcs\n self.simulation = None\n\n def log(self, message):\n self._log.info(message)\n\n def _invariant_check(self, _):\n for e in self.mcs:\n if e not in self.new_dag._events_set:\n return []\n return [\"violation\"]\n\n def replay(self, new_dag, hook=None):\n self.new_dag = new_dag\n return self.invariant_check(new_dag)\n\n# Horrible horrible hack. This way lies insanity\nclass MockMCSFinder(MockMCSFinderBase, MCSFinder):\n def __init__(self, event_dag, mcs):\n MockMCSFinderBase.__init__(self, event_dag, mcs)\n self._log = logging.getLogger(\"mock_mcs_finder\")\n\nclass MockEfficientMCSFinder(MockMCSFinderBase, EfficientMCSFinder):\n def __init__(self, event_dag, mcs):\n MockMCSFinderBase.__init__(self, event_dag, mcs)\n self._log = logging.getLogger(\"mock_efficient_mcs_finder\")\n\nclass MockInputEvent(InputEvent):\n def __init__(self, fingerprint=None, **kws):\n super(MockInputEvent, self).__init__(**kws)\n self.fingerprint = fingerprint\n\n def proceed(self, simulation):\n return True\n\nmcs_results_path = \"/tmp/mcs_results\"\n\nclass MCSFinderTest(unittest.TestCase):\n def test_basic(self):\n self.basic(MockMCSFinder)\n\n def test_basic_efficient(self):\n self.basic(MockEfficientMCSFinder)\n\n def basic(self, mcs_finder_type):\n trace = [ MockInputEvent(fingerprint=(\"class\",f)) for f in range(1,7) ]\n dag = EventDag(trace)\n mcs = [trace[0]]\n mcs_finder = mcs_finder_type(dag, mcs)\n try:\n os.makedirs(mcs_results_path)\n mcs_finder.init_results(mcs_results_path)\n mcs_finder.simulate()\n finally:\n shutil.rmtree(mcs_results_path)\n self.assertEqual(mcs, mcs_finder.dag.input_events)\n\n def test_straddle(self):\n self.straddle(MockMCSFinder)\n\n def test_straddle_efficient(self):\n self.straddle(MockEfficientMCSFinder)\n\n def straddle(self, mcs_finder_type):\n trace = [ MockInputEvent(fingerprint=(\"class\",f)) for f in range(1,7) ]\n dag = EventDag(trace)\n mcs = [trace[0],trace[5]]\n mcs_finder = mcs_finder_type(dag, mcs)\n try:\n os.makedirs(mcs_results_path)\n mcs_finder.init_results(mcs_results_path)\n mcs_finder.simulate()\n finally:\n shutil.rmtree(mcs_results_path)\n self.assertEqual(mcs, mcs_finder.dag.input_events)\n\n def test_all(self):\n self.all(MockMCSFinder)\n\n def test_all_efficient(self):\n self.all(MockEfficientMCSFinder)\n\n def all(self, mcs_finder_type):\n trace = [ MockInputEvent(fingerprint=(\"class\",f)) for f in range(1,7) ]\n dag = EventDag(trace)\n mcs = trace\n mcs_finder = mcs_finder_type(dag, mcs)\n try:\n os.makedirs(mcs_results_path)\n mcs_finder.init_results(mcs_results_path)\n mcs_finder.simulate()\n finally:\n shutil.rmtree(mcs_results_path)\n self.assertEqual(mcs, mcs_finder.dag.input_events)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/unit/sts/mcs_finder_test.py","file_name":"mcs_finder_test.py","file_ext":"py","file_size_in_byte":4057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"166810674","text":"from flask import Flask, render_template, redirect\r\nfrom flask_pymongo import PyMongo\r\nimport scrape_mars\r\n\r\napp = Flask(__name__)\r\n\r\n\r\nmongo = PyMongo(app, uri=\"mongodb://localhost:27017/mars_db\")\r\n\r\n\r\n@app.route(\"/\")\r\ndef home():\r\n\r\n mars_data = mongo.db.collection.find_one()\r\n \r\n\r\n return render_template(\"index.html\", mars_data= mars_data)\r\n\r\n\r\n\r\n@app.route(\"/scrape\")\r\ndef scrape():\r\n mars_data = mongo.db.collection \r\n \r\n data = scrape_mars.scrape()\r\n\r\n \r\n mars_data.update({}, data, upsert = True)\r\n\r\n \r\n return redirect(\"http://localhost:5000/\", code = 302)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)\r\n\r\n\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"133768939","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\nimport os\nimport json\nimport argparse\nfrom easydict import EasyDict as edict\n\nparser = argparse.ArgumentParser(description='Train model')\nparser.add_argument('json_file', default=None, metavar='JSON_FILE', type=str,\n help=\"Path to the json txt\")\nparser.add_argument('save_json', default=None, metavar='SAVE_JSON', type=str,\n help=\"Path to the saved json\")\n\n\ndef add_image(coco, cfg, filename, image_id):\n image_item = dict()\n file_name = os.path.basename(filename)[:-5]\n image_item['file_name'] = file_name + \".jpg\"\n image_item['height'] = cfg.imageShape.get('height')\n image_item['width'] = cfg.imageShape.get('width')\n image_item['id'] = image_id\n coco['images'].append(image_item)\n \n\ndef add_category(coco, name, category_id):\n category_item = dict()\n category_item['supercategory'] = 'none'\n category_item['id'] = category_id\n category_item['name'] = name\n # category_item['keypoints'] = [\n # \"seventh_cervical_vertebra\",\n # \"right_costophrenic_angle\",\n # \"left_costophrenic_angle\"]\n # category_item['skeleton'] = [[2, 3], [1, 2], [1, 3]]\n coco['categories'].append(category_item)\n\n\ndef add_anno(coco, objects, image_id, category_id, annotation_id):\n annotation_item = dict()\n # annotation_item['num_keypoints'] = 3\n annotation_item['segmentation'] = []\n seg, bbox = get_points(objects)\n annotation_item['segmentation'].append(seg)\n annotation_item['image_id'] = image_id\n annotation_item['bbox'] = bbox\n # annotation_item['area'] = get_area(box)\n annotation_item['iscrowd'] = 0\n annotation_item['category_id'] = category_id\n annotation_item['id'] = annotation_id\n coco['annotations'].append(annotation_item)\n\n\ndef get_points(objects):\n point_list = []\n points = objects.get('points')\n if objects.get('type') == 'RectangleRoi':\n x1 = float(points[0].get('X'))\n y1 = float(points[0].get('Y'))\n x2 = float(points[1].get('X'))\n y2 = float(points[1].get('Y'))\n point_list.extend([x1, y1, x1, y2, x2, y2, x2, y1]) \n else:\n for each in points:\n x = each.get('X')\n y = each.get('Y')\n point_list.append(float(x))\n point_list.append(float(y))\n\n bbox = [min(point_list[::2]), min(point_list[1::2]), max(point_list[::2]) - min(point_list[::2]), max(point_list[1::2]) - min(point_list[1::2])]\n return point_list, bbox\n\n'''\ndef get_value(cfg):\n value = [0] * 9 # x, y ,v v=0 point missing v=1 point invisible v=2 point visible\n keep_index = []\n for key_point in cfg.keyPoints:\n if key_point.get('objectLabels')[0] == 'seventh_cervical_vertebra':\n x, y = get_points(key_point)\n value[0:3] = x,y,2\n keep_index.append(0)\n if key_point.get('objectLabels')[0] == 'right_costophrenic_angle':\n x, y = get_points(key_point)\n value[3:6] = x,y,2\n keep_index.append(1)\n if key_point.get('objectLabels')[0] == 'left_costophrenic_angle':\n x, y = get_points(key_point)\n value[6:9] = x,y,2\n keep_index.append(2)\n \n return value, keep_index\n'''\n'''\ndef get_box(value, keep_index, cfg):\n # x, y(left top) && width height\n assert(len(value) == 9)\n value_refined = get_refined(value, keep_index, cfg)\n\n box = [0] * 4\n box[0] = min(value_refined[::3])\n box[1] = min(value_refined[1::3])\n box[2] = max(value_refined[::3]) - box[0]\n box[3] = max(value[1::3]) - box[1]\n return box\n'''\n'''\ndef get_refined(value, keep_index, cfg):\n if len(keep_index) == 3:\n return value\n elif keep_index == [1,2] or keep_index == [2,1]: # missing top\n value_new = value.copy()\n value_new[0] = value[3] # change x\n return value_new\n elif keep_index == [0,1] or keep_index == [1,0]: # missing right\n value_new = value.copy()\n value_new[6] = cfg.imageShape.get('width') # change x\n value_new[7] = value[1] # change y\n return value_new\n elif keep_index == [0,2] or keep_index == [2,0]: # mising left\n value_new = value.copy()\n value_new[4] = value[1] # change y\n return value_new\n elif keep_index == [0]: # mising left and right\n value_new = value.copy()\n value_new[4] = cfg.imageShape.get('height') # change y\n value_new[6] = cfg.imageShape.get('width') # change x\n value_new[7] = cfg.imageShape.get('height') # change y\n return value_new\n elif keep_index == [1]: # mising top and left\n value_new = value.copy()\n value_new[0] = value[3] # change x\n value_new[6] = cfg.imageShape.get('width') # change x\n return value_new\n elif keep_index == [2]: # mising right and top\n return value\n else:\n raise Exception(\"Unexpected index: {}\".format(*keep_index))\n'''\n'''\ndef get_area(box):\n assert(len(box) == 4)\n return (box[3] - box[1]) * (box[2] - box[0])\n'''\n\ndef run(args):\n coco = dict()\n coco['info'] = {\n \"description\": \"COCO 2017 Dataset\",\n \"url\": \"http://cocodataset.org\",\n \"version\": \"1.0\",\n \"year\": 2017,\n \"contributor\": \"COCO Consortium\",\n \"date_created\": \"2017/09/01\"\n }\n coco['licenses'] = [\n {\n \"url\": \"http://creativecommons.org/licenses/by-nc-sa/2.0/\",\n \"id\": 1,\n \"name\": \"Attribution-NonCommercial-ShareAlike License\"\n }\n ]\n coco['images'] = []\n coco['categories'] = []\n coco['annotations'] = []\n\n segs = ['foreign_body', 'implants']\n\n category_id = 0\n image_id = 0\n annotation_id = 0\n for seg in segs:\n add_category(coco, seg, category_id)\n category_id += 1\n \n with open(args.json_file) as json_file:\n for filename in json_file:\n filename = filename.strip('\\n')\n print(\"Converting -----> \", filename)\n with open(filename) as f:\n cfg = edict(json.load(f))\n add_image(coco, cfg, filename, image_id)\n for objects in cfg.objectList:\n for seg in segs:\n if seg in objects['objectLabels']:\n category_id = segs.index(seg)\n add_anno(coco, objects, image_id, category_id, annotation_id)\n annotation_id += 1\n image_id += 1\n\n with open(args.save_json, 'w') as f:\n json.dump(coco, f, indent=1)\n\n\ndef main():\n args = parser.parse_args()\n\n run(args)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"python/json2coco_seg.py","file_name":"json2coco_seg.py","file_ext":"py","file_size_in_byte":6711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"158157005","text":"#!/usr/bin/env python\n\nimport os\nimport ctypes\nimport pytest\n\n\n########################################\n# Tests\n########################################\n\n\ndef test_client_knows_dylib_location(Client, ROOT_DIR):\n client = Client()\n mtengine_file = os.path.join(ROOT_DIR, 'libmtengine.so')\n assert client._mtengine_path == mtengine_file\n\n\n@pytest.mark.ffi\ndef test_Client_gets_response_from_mtengine(Client):\n client = Client()\n payload = b\"{'foo':'bar'}\"\n\n response = client.get_response(payload)\n assert response\n\n\n@pytest.mark.ffi\ndef test_client_decodes_message_to_string(Client, Preprocessor):\n client = Client()\n payload = b\"{'foo':'bar'}\"\n\n response = client.get_response(payload)\n assert response\n\n\n# What to test next\n# * Sends to Rust\n# * Receives from Rust\n","sub_path":"tests/unit/test_client.py","file_name":"test_client.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"161593255","text":"import pygame\n\nimport time\n\nimport random\n\nimport sys\n\nSCREEN_WIDTH = 800\n\nSCREEN_HEIGHT = 560\n\n\n# 地图类 v1.2 完善地图类\n\nclass Map:\n images_list = ['imgs/map1.png', 'imgs/map2.png']\n\n def __init__(self, x, y, image_index):\n self.position = (x, y)\n\n self.image = pygame.image.load(Map.images_list[image_index])\n\n # v1.5 新增是否能种植的属性\n\n self.can_grow = True\n\n # 将当前地图的图片加入到窗口\n\n def display_map(self):\n MainGame.window.blit(self.image, self.position)\n\n\n# 植物类 (父类)\n\nclass Plant(pygame.sprite.Sprite):\n\n def __init__(self):\n super().__init__()\n\n self.live = True\n\n\n# 向日葵类 v1.4 完善向日葵类\n\nclass Sunflower(Plant):\n\n def __init__(self, x, y):\n super(Sunflower, self).__init__()\n\n self.image = pygame.image.load('imgs/sunflower.png')\n\n self.rect = self.image.get_rect()\n\n self.rect.x = x\n\n self.rect.y = y\n\n self.price = 50\n\n self.hp = 100\n\n # v1.6 时间计数器\n\n self.time_count = 0\n\n # v1.6 新增功能:生成阳光\n\n def produce_money(self):\n self.time_count += 1\n\n if self.time_count == 25:\n MainGame.money += 5\n\n self.time_count = 0\n\n # 向日葵加入到窗口中\n\n def display_sunflower(self):\n MainGame.window.blit(self.image, self.rect)\n\n\n# 豌豆射手类\n\n# v1.5 完善 豌豆射手类\n\nclass PeaShooter(Plant):\n\n def __init__(self, x, y):\n\n super(PeaShooter, self).__init__()\n\n # self.image 为一个 surface\n\n self.image = pygame.image.load('imgs/1-4.png')\n\n self.rect = self.image.get_rect()\n\n self.rect.x = x\n\n self.rect.y = y\n\n self.price = 50\n\n self.hp = 200\n\n # v1.7 发射计数器\n\n self.shot_count = 0\n\n # v1.7 增加射击方法\n\n def shot(self):\n\n # v1.9 记录是否应该射击\n\n should_fire = False\n\n for zombie in MainGame.zombie_list:\n\n if zombie.rect.y == self.rect.y and zombie.rect.x < 800 and zombie.rect.x > self.rect.x:\n should_fire = True\n\n # 如果活着\n\n if self.live and should_fire:\n\n self.shot_count += 1\n\n # 计数器到25发射一次\n\n if self.shot_count == 25:\n # 基于当前豌豆射手的位置,创建子弹\n\n peabullet = PeaBullet(self)\n\n # 将子弹存储到子弹列表中\n\n MainGame.peabullet_list.append(peabullet)\n\n self.shot_count = 0\n\n # 将豌豆射手加入到窗口中的方法\n\n def display_peashooter(self):\n\n MainGame.window.blit(self.image, self.rect)\n\n\n# 豌豆子弹类\n\n# v1.6 新增子弹类的功能\n\nclass PeaBullet(pygame.sprite.Sprite):\n\n def __init__(self, peashooter):\n\n self.live = True\n\n self.image = pygame.image.load('imgs/1-6.png')\n\n self.damage = 50\n\n self.speed = 10\n\n self.rect = self.image.get_rect()\n\n self.rect.x = peashooter.rect.x + 40\n\n self.rect.y = peashooter.rect.y + 25\n\n def move_bullet(self):\n\n # 在屏幕范围内,实现往右移动\n\n if self.rect.x < SCREEN_WIDTH:\n\n self.rect.x += self.speed\n\n else:\n\n self.live = False\n\n # v1.9 新增,子弹与僵尸的碰撞\n\n def hit_zombie(self):\n\n for zombie in MainGame.zombie_list:\n\n if pygame.sprite.collide_rect(self, zombie):\n\n # 打中僵尸之后,修改子弹的状态,\n\n self.live = False\n\n # 僵尸掉血\n\n zombie.hp -= self.damage\n\n if zombie.hp <= 0:\n zombie.live = False\n\n def display_peabullet(self):\n\n MainGame.window.blit(self.image, self.rect)\n\n\n# 僵尸类\n\n# v1.8 完善僵尸类\n\nclass Zombie(pygame.sprite.Sprite):\n\n def __init__(self, x, y):\n\n super(Zombie, self).__init__()\n\n self.image = pygame.image.load('imgs/zombie.png')\n\n self.rect = self.image.get_rect()\n\n self.rect.x = x\n\n self.rect.y = y\n\n self.hp = 1000\n\n self.damage = 2\n\n self.speed = 1\n\n self.live = True\n\n self.stop = False\n\n # v1.8僵尸的移动\n\n def move_zombie(self):\n\n if self.live and not self.stop:\n\n self.rect.x -= self.speed\n\n if self.rect.x < -80:\n # 调用游戏结束方法\n\n MainGame().gameOver()\n\n # v1.8将僵尸加载到地图中\n\n def display_zombie(self):\n\n MainGame.window.blit(self.image, self.rect)\n\n\n# 游戏主线类\n\nclass MainGame:\n # 游戏窗口\n\n window = None\n\n # v1.2 新增存储所有坐标点的列表\n\n points_list = []\n\n # v1.2 新增存储所有地图块的列表\n\n maps_list = []\n\n # v1.4 存储所有植物的列表\n\n plants_list = []\n\n # v1.5 记录当前的金钱数\n\n money = 50\n\n # v1.7 存储所有豌豆子弹的列表\n\n peabullet_list = []\n\n # v1.8 新增存储所有僵尸的列表\n\n zombie_list = []\n\n def __init__(self):\n\n pass\n\n # 加载游戏窗口\n\n def init_window(self):\n\n # 调用显示模块的初始化\n\n pygame.display.init()\n\n # 创建窗口\n\n MainGame.window = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) # Surface\n\n # 获取一个包含指定文字的surface\n\n def get_surface_with_content(self, content, size, font_name, color):\n\n # 字体初始化\n\n pygame.font.init()\n\n # 创建字体\n\n font = pygame.font.SysFont(font_name, size)\n\n # 使用对应的字体绘制surface\n\n sf = font.render(content, True, color)\n\n return sf\n\n # v1.2 新增初始化地图坐标的方法\n\n def init_points(self):\n\n for y in range(1, 7): # (1,6)\n\n temp_list = []\n\n for x in range(10): # 0,9\n\n point = (x, y)\n\n temp_list.append(point)\n\n print(temp_list)\n\n MainGame.points_list.append(temp_list)\n\n # v1.2 完成所有地图块的创建,存储到列表中\n\n def init_maps(self):\n\n # 遍历列表的长度 points 为大列表中的小列表\n\n for points in MainGame.points_list:\n\n temp_map_list = []\n\n for p in points:\n\n x = p[0] * 80\n\n y = p[1] * 80\n\n if (p[0] + p[1]) % 2 == 0:\n\n map = Map(x, y, 1)\n\n else:\n\n map = Map(x, y, 0)\n\n temp_map_list.append(map)\n\n # 将存储所有地图的列表存储到大列表中\n\n MainGame.maps_list.append(temp_map_list)\n\n # v1.2 将地图加载到窗口中\n\n def load_maps(self):\n\n for map_list in MainGame.maps_list:\n\n for map in map_list:\n map.display_map()\n\n # v1.4 加载所有的植物\n\n # v1.5 加载豌豆射手处理\n\n # v1.7 增加豌豆射手发射处理\n\n def load_plants(self):\n\n for plant in MainGame.plants_list:\n\n # v1.6 优化加载植物的处理逻辑\n\n if plant.live:\n\n if isinstance(plant, Sunflower):\n\n plant.display_sunflower()\n\n plant.produce_money()\n\n elif isinstance(plant, PeaShooter):\n\n plant.display_peashooter()\n\n plant.shot()\n\n else:\n\n MainGame.plants_list.remove(plant)\n\n # v1.7 加载所有子弹的方法\n\n def load_peabullets(self):\n\n for b in MainGame.peabullet_list:\n\n if b.live:\n\n b.display_peabullet()\n\n b.move_bullet()\n\n # v1.9 调用子弹是否打中僵尸的方法\n\n b.hit_zombie()\n\n else:\n\n MainGame.peabullet_list.remove(b)\n\n # v1.8 新增初始化僵尸的方法\n\n def init_zombies(self):\n\n for i in range(1, 7):\n dis = random.randint(1, 5) * 200\n\n zombie = Zombie(800 + dis, i * 80)\n\n MainGame.zombie_list.append(zombie)\n\n # v1.8 将所有僵尸加载到地图中\n\n def load_zombies(self):\n\n for zombie in MainGame.zombie_list:\n\n if zombie.live:\n\n zombie.display_zombie()\n\n zombie.move_zombie()\n\n else:\n\n MainGame.zombie_list.remove(zombie)\n\n # v1.3 新增事件处理的方法\n\n def deal_events(self):\n\n # 获取所有事件\n\n eventList = pygame.event.get()\n\n # 遍历事件列表,判断\n\n for e in eventList:\n\n if e.type == pygame.QUIT:\n\n self.gameOver()\n\n elif e.type == pygame.MOUSEBUTTONDOWN:\n\n # print('按下鼠标按键')\n\n print(e.pos)\n\n # print(e.button)#左键1 按下滚轮2 上转滚轮为4 下转滚轮为5 右键 3\n\n x = e.pos[0] // 80\n\n y = e.pos[1] // 80\n\n print(x, y)\n\n map = MainGame.maps_list[y - 1][x]\n\n print(map.position)\n\n # v1.5 增加创建时候的地图装填判断以及金钱判断\n\n if e.button == 1:\n\n if map.can_grow and MainGame.money >= 50:\n sunflower = Sunflower(map.position[0], map.position[1])\n\n MainGame.plants_list.append(sunflower)\n\n print('当前植物列表长度:{}'.format(len(MainGame.plants_list)))\n\n map.can_grow = False\n\n MainGame.money -= 50\n\n elif e.button == 3:\n\n if map.can_grow and MainGame.money >= 50:\n peashooter = PeaShooter(map.position[0], map.position[1])\n\n MainGame.plants_list.append(peashooter)\n\n print('当前植物列表长度:{}'.format(len(MainGame.plants_list)))\n\n map.can_grow = False\n\n MainGame.money -= 50\n\n # 游戏开始入口\n\n def startGame(self):\n\n # 调用初始化窗口的方法\n\n self.init_window()\n\n # v1.2 调用初始化坐标点\n\n self.init_points()\n\n # v1.2 调用初始化地图\n\n self.init_maps()\n\n # v1.8 调用初始化僵尸的方法\n\n self.init_zombies()\n\n while True:\n # 设置窗口的填充色\n\n MainGame.window.fill((255, 255, 255))\n\n # v1.5 修改文字加载的位置\n\n # 调用绘制表面\n\n sf = self.get_surface_with_content('剩余金钱{}'.format(MainGame.money), 26, 'kaiti', (255, 0, 0))\n\n # 将包含文字的表面加入到窗口中\n\n MainGame.window.blit(sf, (260, 10))\n\n # v1.2 调用加载地图方法\n\n self.load_maps()\n\n # v1.3 调用事件处理的方法\n\n self.deal_events()\n\n # v1.4 调用加载植物的方法\n\n self.load_plants()\n\n # v1.5 金钱随着时间增加\n\n # MainGame.money += 0.25\n\n # v1.7 调用加载所有子弹的方法\n\n self.load_peabullets()\n\n # v1.8 调用展示僵尸的方法\n\n self.load_zombies()\n\n # 调用窗口刷新功能\n\n pygame.display.update()\n\n # time.sleep(0.025)\n\n # v1.7 pygame自己的休眠\n\n pygame.time.wait(10)\n\n # 程序结束方法\n\n def gameOver(self):\n\n print('僵尸进入了你家后院')\n\n # 结束程序\n\n sys.exit()\n\n\nif __name__ == '__main__':\n game = MainGame()\n\n game.startGame()","sub_path":"yl_python_code/python_code/zhiwu/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"241308249","text":"import numpy as np\nimport cv2\nimport os\n\ndef part3(img1, img2):\n subImg = img1[50:100, 50:150, :].copy()\n subImg[:, :, 1:2] = 0\n superImg = img2.copy()\n superImg[:, :, 0:3:2] = 0\n superImg[50:100, 50:150, :] = subImg\n cv2.imwrite('ps0-3-a-1.png', superImg)\n\nif __name__ == '__main__':\n curDir = os.path.dirname(__file__)\n fileName1 = os.path.join(curDir, '../PS0-1/ps0-1-a-1.png')\n fileName2 = os.path.join(curDir, '../PS0-1/ps0-1-a-2.png')\n\n img1 = cv2.imread(fileName1)\n img2 = cv2.imread(fileName2)\n\n part3(img1, img2)\n\n","sub_path":"CS4495_Computer_Vision/Problem_Set_0/PS0-3/PS0-3-code.py","file_name":"PS0-3-code.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"263679048","text":"'''\nCreated on May 20, 2015\n\n@author: susan\n'''\n\nimport pygame\nimport sys\nfrom pygame.locals import *\nimport random\nfrom game.bullet import Bullet\nfrom game.player import Player\nfrom game.enemy import Enemy\nfrom game.cross_hair import CrossHair\n\nBLACK = pygame.Color(0, 0, 0)\nWHITE = pygame.Color(255, 255, 255)\nGOLD = pygame.Color(255, 215, 0)\nRED = pygame.Color(255, 0, 0)\nBLUE = pygame.Color(9, 24, 84)\nDARK_RED = pygame.Color(153, 32, 18)\n\n\"\"\"\nas the game goes on, the speed at which the enemies descend increases \nand the time between each batch of new enemies decreases\n\"\"\"\n \ndef main():\n pygame.init()\n FPS = 30\n FPS_CLOCK = pygame.time.Clock()\n screen_width = 700\n screen_height = 800\n initialEnemySize = 20\n speedTimer = 500\n generateEnemyTimer = 50000\n \"\"\" when an enemy moves past the red line, it creates this number of new\"\"\"\n initialEnemySplitNum = 2\n \n window_size = (screen_width, screen_height)\n SCREEN = pygame.display.set_mode(window_size)\n\n # set the title of the window\n pygame.display.set_caption(\"Shooting Game\")\n \n all_sprites_list = pygame.sprite.Group()\n\n enemy_list = pygame.sprite.Group()\n\n bullet_list = pygame.sprite.Group()\n crossHair = CrossHair()\n \"\"\"\n make the initial enemies\n \"\"\"\n makeMoreEnemy(enemy_list, all_sprites_list)\n \n # Create a red player block\n player = Player()\n all_sprites_list.add(player)\n \n clock = pygame.time.Clock()\n \n player.rect.y = screen_height -100\n \n gameOver = False\n level = 1\n \n \n MOVE_ENEMY = pygame.USEREVENT+1\n MORE_ENEMY = pygame.USEREVENT+2\n \n pygame.time.set_timer(MOVE_ENEMY, speedTimer)\n pygame.time.set_timer(MORE_ENEMY, generateEnemyTimer)\n \n while True: # <--- main game loop\n \n for event in pygame.event.get():\n if event.type == K_q: \n gameOver = True\n elif event.type == K_RETURN:\n gameOver = False\n elif event.type == QUIT: # QUIT event to exit the game\n pygame.quit()\n sys.exit()\n elif event.type == pygame.MOUSEBUTTONDOWN:\n # Fire a bullet if the user clicks the mouse button\n bullet = Bullet()\n # Set the bullet so it is where the player is\n bullet.rect.x = player.rect.x\n bullet.rect.y = player.rect.y\n # Add the bullet to the lists\n all_sprites_list.add(bullet)\n bullet_list.add(bullet)\n player.bulletCount -= 1\n shot_sound = pygame.mixer.Sound('handGun.wav')\n shot_sound.play()\n elif event.type == pygame.MOUSEMOTION:\n position = event.pos\n crossHair.move(position[0], position[1])\n elif event.type == MOVE_ENEMY and not gameOver:\n for enemy in enemy_list:\n if player.score % 200 == 0 and player.score > 200:\n enemy.speed += 5\n enemy.move()\n if enemy.rect.y >= 800:\n player.health -= 10\n enemy_list.remove()\n all_sprites_list.remove()\n if enemy.rect.y >= enemy.split_limit and enemy.hasSplit == False:\n enemy.split(2)\n \n for enemy_child in enemy.enemy_child_list:\n enemy_list.add(enemy_child)\n all_sprites_list.add(enemy_child)\n elif event.type == MORE_ENEMY:\n makeMoreEnemy(enemy_list, all_sprites_list)\n \n if not gameOver: \n \"\"\"as the player's score increase by 200, the difficulty increases\"\"\" \n if player.score % 200 == 0 and player.score > 200:\n speedTimer = speedTimer / 2\n pygame.time.set_timer(MOVE_ENEMY, speedTimer)\n generateEnemyTimer = generateEnemyTimer /2 \n pygame.time.set_timer(MORE_ENEMY, generateEnemyTimer)\n # --- Game logic\n \n # Call the update() method on all the sprites\n all_sprites_list.update()\n \n for bullet in bullet_list:\n \n # See if it hit a block\n block_hit_list = pygame.sprite.spritecollide(bullet, enemy_list, True)\n \n # For each block hit, remove the bullet and add to the score\n for enemy in block_hit_list:\n player.score += 10\n bullet_list.remove(bullet)\n all_sprites_list.remove(bullet)\n player.score += 1\n \n # Remove the bullet if it flies up off the screen\n if bullet.rect.y < -10:\n bullet_list.remove(bullet)\n all_sprites_list.remove(bullet)\n \n \n # Clear the screen\n SCREEN.fill(WHITE)\n pygame.draw.line(SCREEN, RED, (0,350), (700, 350),3)\n crossHair.draw(SCREEN)\n # Draw all the spites\n all_sprites_list.draw(SCREEN)\n \n # Go ahead and update the screen with what we've drawn.\n \n if player.health < 0 : \n displayGameOver(SCREEN)\n gameOver = True\n \n displayStats(SCREEN, player)\n pygame.display.flip()\n \n FPS_CLOCK.tick(FPS)\ndef makeMoreEnemy(enemy_list, all_sprites_list):\n for i in range(10):\n rand_x = random.randint(0, 700)\n rand_y = random.randint(0, 100)\n rand_size = random.randint(10, 30)\n rand_speed = random.randint(5, 10)\n\n split_limit = 350\n # This represents a block\n enemy = Enemy(rand_x, rand_y, rand_size, rand_speed, BLACK, split_limit )\n\n # Add the block to the list of objects\n enemy_list.add(enemy)\n all_sprites_list.add(enemy)\n\ndef displayStats(SCREEN, player):\n myfont = pygame.font.SysFont(\"monospace\", 15)\n bulletStat = myfont.render(\"Bullet: \" + str(player.bulletCount) + \"/\" + \n str(player.initialBulletCount), True, BLACK)\n text_rect = bulletStat.get_rect()\n text_x = SCREEN.get_width() - text_rect.width - 10\n text_y = SCREEN.get_height() - text_rect.height - 25 \n SCREEN.blit(bulletStat, [text_x, text_y])\n \n scoreStat = myfont.render(\"Score: \" + str(player.score), True, BLACK)\n text_rect = scoreStat.get_rect()\n text_x = SCREEN.get_width() - text_rect.width - 10\n text_y = SCREEN.get_height() - text_rect.height - 15 \n SCREEN.blit(scoreStat, [text_x, text_y])\n \n healthStat = myfont.render(\"Health: \" + str(player.health) + \"% \", True, BLACK)\n text_rect = healthStat.get_rect()\n text_x = SCREEN.get_width() - text_rect.width - 10\n text_y = SCREEN.get_height() - text_rect.height - 5 \n SCREEN.blit(healthStat, [text_x, text_y])\n\ndef displayGameOver(SCREEN):\n myfont = pygame.font.SysFont(\"monospace\", 15)\n gameOver = myfont.render((\"GAME OVER! Press Q to quit or Enter to play again\") , True, BLACK)\n text_rect = gameOver.get_rect()\n text_x = SCREEN.get_width() / 2 - 200\n text_y = SCREEN.get_height() / 2\n SCREEN.blit(gameOver, [text_x, text_y])\n\nif __name__ == \"__main__\":\n main()","sub_path":"src/game/shootingGame.py","file_name":"shootingGame.py","file_ext":"py","file_size_in_byte":7408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"595701530","text":"from Date import Date as d\nimport statistics as s\ntemp = []\nfor line in open('birthdays.txt', encoding='utf8'):\n temp_line = line.strip('\\n').split(' ')\n temp_date = d(temp_line[0], temp_line[1], temp_line[2])\n temp.append(temp_date)\n \ntemp1 = [] \ntemp2 = dict()\nlowestbd = temp[0]\nhighestbd = temp[0]\nmostmonth = temp[0].month\nfor i in range(len(temp)):\n if temp[i] < lowestbd:\n lowestbd = temp[i]\n if temp[i] > highestbd:\n highestbd = temp[i]\n temp1.append(temp[i].month)\n \n \nprint(lowestbd)\nprint(highestbd)\n#print(temp1)\nmonth_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July',\\\n 'August','September', 'October', 'November', 'December' ]\n\nprint(month_names[int(s.mode(temp1))-1])","sub_path":"Labs/lab9/check3.py","file_name":"check3.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"5432431","text":"# import necessary libraries\nfrom sqlalchemy import func\n\nfrom flask import (\n Flask,\n render_template,\n jsonify,\n request,\n redirect)\n\nfrom flask_sqlalchemy import SQLAlchemy\n\n\napp = Flask(__name__)\n\napp.config['SQLALCHEMY_DATABASE_URI'] = \"sqlite:///db/FastFood.sqlite\"\n\ndb = SQLAlchemy(app)\n\n\nclass FastFood(db.Model):\n __tablename__ = 'fastfood'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(64))\n restaurant = db.Column(db.String)\n menuitem = db.Column(db.String)\n\n def __repr__(self):\n return '' % (self.name)\n\n# ====================probably should remove before goign live?===============\n# @app.before_first_request\n# def setup():\n# # Recreate database each time for demo\n# db.drop_all()\n# db.create_all()\n\n\n# create route that renders index.html template\n@app.route(\"/\")\ndef home():\n return render_template(\"index.html\")\n\n\n# Query the database and send the jsonified results\n@app.route(\"/send\", methods=[\"GET\", \"POST\"])\ndef send():\n if request.method == \"POST\":\n name = request.form[\"surveyName\"]\n restaurant = request.form[\"surveyRestaurant\"]\n menuitem = request.form[\"surveyMenu\"]\n\n personaldata = FastFood(name=name, restaurant=restaurant, menuitem=menuitem)\n db.session.add(personaldata)\n db.session.commit()\n return redirect(\"/\", code=302)\n\n return render_template(\"form.html\")\n\n\n\n# create route that returns data for plotting\n@app.route(\"/api/fastfood\")\ndef pals():\n # results = db.session.query(FastFood.name, FastFood.restaurant, FastFood.menuitem).all()\n\n data = db.session.query(FastFood.restaurant, func.count(FastFood.name))\\\n .group_by(FastFood.restaurant).all()\n\n\n return jsonify(data)\n\n@app.route(\"/api/sequence\")\ndef seq():\n results = db.session.query(FastFood.name, FastFood.restaurant, FastFood.menuitem).all()\n\n\n\n return jsonify([r._asdict() for r in results])\n\n@app.route('/Anna')\ndef Anna():\n return render_template('Anna.html')\n\n\n@app.route('/Kim')\ndef Kim():\n return render_template('Kim.html')\n\n\n@app.route('/Cristian')\ndef Cristian():\n return render_template('Cristian.html')\n\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"Fast_Food/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"25652557","text":"import factory\nfrom . import models\nimport json\n\nclass CategoryFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = models.Category\n\n name = factory.Faker('word',locale='es_ES')\n slug= factory.Faker('word',locale='es_ES')\n\nclass EventFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = models.Event\n\n name = factory.Faker('word',locale='es_ES')\n slug = factory.Faker('word',locale='es_ES')\n description = factory.Faker('sentence',locale='es_ES')\n\n @factory.lazy_attribute\n def category(self):\n return CategoryFactory.create()\n\nclass ParameterFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = models.Parameter\n\n name = factory.Faker('word',locale='es_ES')\n human_name = factory.Faker('word',locale='es_ES')\n serializer = ''\n\n @factory.lazy_attribute\n def event(self):\n return EventFactory.create()\n\n\nclass EventNotificationFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = models.EventNotification\n\n name = factory.Faker('word',locale='es_ES')\n subject = factory.Faker('sentence',locale='es_ES')\n message = factory.Faker('sentence',locale='es_ES')\n\n @factory.lazy_attribute\n def event(self):\n return EventFactory.create()\n\nclass EventNotificationRecipientFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = models.EventNotificationRecipient\n\n recipient = \"\"\n type = factory.Iterator(models.RECIPIENT_TYPE)\n\n @factory.lazy_attribute\n def notification(self):\n return EventNotificationFactory.create()","sub_path":"pynot/factories.py","file_name":"factories.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"508747043","text":"# Language: Python v3\n# Description: A priority queue data structure which stores the\n# node having the least cost at the begining (index=0).\n\nfrom NodeInfo import NodeInfo\n\nclass PriorityQueue:\n collection = []\n \n def enqueue(self, nodeId, cost):\n node = NodeInfo(nodeId, cost)\n\n if (self.isEmpty()): \n self.collection.append(node)\n else:\n added = False\n i = 1\n while (i <= len(self.collection)):\n if (node.cost < self.collection[i - 1].cost):\n self.collection.insert(i - 1, node)\n added = True\n break\n i = i + 1\n\n if (added == False):\n self.collection.append(node)\n\n def dequeue(self):\n # Return the node with the smallest cost\n return self.collection.pop(0)\n\n def isEmpty(self):\n return len(self.collection) == 0","sub_path":"PriorityQueue.py","file_name":"PriorityQueue.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"134811336","text":"import json\nimport os\n\ndef count_line():\n ori_filepath = \"/home/wzy/PycharmProjects/DocRED/data/train_annotated.json\"\n ori_data = json.load(open(ori_filepath))\n split_line = list(range(0,len(ori_data),int(len(ori_data)/5)+1))\n data_slices = list()\n for i in range(4):\n data_slices.append(ori_data[split_line[i]:split_line[i+1]])\n data_slices.append(ori_data[split_line[4]:])\n\n total_len = 0\n for _slice in data_slices:\n total_len += len(_slice)\n assert total_len == len(ori_data)\n assert len(ori_data) == 3053\n assert len(data_slices) == 5\n\n for cur in range(5):\n dev_slice = data_slices[cur]\n train_slice = list()\n for _cur in range(5):\n if _cur != cur:\n train_slice.extend(data_slices[_cur])\n if cur != 4:\n assert len(dev_slice) == 611\n assert len(train_slice) == 3053 - 611\n if cur == 4:\n assert len(dev_slice) == 3053 - 4 * 611\n assert len(train_slice) == 4 * 611\n dir_path = \"/home/wzy/PycharmProjects/DocRED/\"+str(cur+1)+\"of5part_data/\"\n json.dump(train_slice, open(os.path.join(dir_path, 'train_annotated.json'), \"w\"))\n json.dump(dev_slice, open(os.path.join(dir_path, 'dev_annotated.json'), \"w\"))\nif __name__ == \"__main__\":\n count_line()","sub_path":"code/m_utils.py","file_name":"m_utils.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"327404774","text":"#!/usr/bin/env python\n\n#####################################################\n#####################################################\n#####################################################\n# #\n# Main Controller Interface #\n# #\n#####################################################\n# #\n# - publishing to Emergency Interrupt (40Hz) #\n# - considers different Logic Flags to trigger #\n# emergency or vehicle halt #\n# - checks whether checkpoint_publisher runs #\n# | essential_topics are available #\n# | mapping_complete | lidar_crash detection #\n# is false etc\n# - 'e' start exploration mode #\n# - 'a' running autonomous racing #\n# - 'r' reinitialize vehicle to last checkpoint #\n# using ros service to request initial pose #\n# #\n# written by Philipp Rothenhaeusler - phirot@kth.se #\n# #\n#####################################################\n#####################################################\n#####################################################\n#####################################################\n\n\nimport os\nimport time\nimport rospy\nimport numpy\nimport threading\nfrom std_msgs.msg import Float64\nfrom control.msg import pwm_interface\nimport scipy.integrate as Integration\nfrom std_msgs.msg import Bool\nfrom nav_msgs.msg import Odometry\nfrom nav_msgs.msg import OccupancyGrid\nfrom geometry_msgs.msg import PoseArray, Pose, Quaternion\n\n\n#####################################################\n# Initialize Threading Class #\n#####################################################\nclass ThreadedFunction(threading.Thread):\n\n #####################################################\n # Initialize Object #\n #####################################################\n def __init__(self, fcn_to_thread):\n threading.Thread.__init__(self)\n\n self.runnable = fcn_to_thread\n self.daemon = True\n\n def run(self):\n self.runnable()\n\n\n#####################################################\n# Initialize Failsafe Class #\n#####################################################\nclass Vehicle:\n\n #####################################################\n # Initialize Object #\n #####################################################\n def __init__(self):\n\n #####################################################\n # Initialize Boolean States for System #\n #####################################################\n self.MAIN_INTERFACE_STARTED = False\n self.SIMULATION_ACTIVE = False\n self.PARAMETERS_INITIALIZED = False\n self.PARAMETER_UPDATED = False\n self.MANUAL_CONTROL_ACTIVATED = False\n self.EXPLORATION_ACTIVATED = False\n self.AUTONOMOUS_RACING_ACTIVATED = False\n self.SAFETY_REGION_WATCHDOG_OK = False # Lidar Safety Region to detect Crash or Obstacles\n self.PUBLISH_RATE_SIM = 40\n self.EMERGENCY_FLAG = False\n self.SUBSCRIBER_ACTIVE = False\n self.PUBLISHER_ACTIVE = True\n\n #####################################################\n # Initialize Locks for Threaded Access #\n #####################################################\n self.PUBLISH_ACTIVE = False\n self.KEY_READ_ACTIVE = False\n\n #####################################################\n # Initialize System Dynamics #\n #####################################################\n self.x_next = 0\n self.x_curr = 0\n self.u_curr = 0\n self.y_next = 0\n self.A = -2/3\n self.PHI = numpy.exp(self.A*(1./self.PUBLISH_RATE_SIM))\n self.B = 1.7/15\n self.C = 1\n self.D = 0\n self.B_INT = Integration.quad(lambda s: self.B*self.state_transition_system(s), 0, 1./self.PUBLISH_RATE_SIM)\n self.THETA = self.B_INT[0]\n\n self.control_input = 0\n self.velocity_output = Float64()\n self.velocity_output.data = 0\n\n self.STATE_UPDATED = False\n self.CONTROL_INPUT_UPDATED = False\n\n rospy.init_node('control_sim_model', anonymous=True)\n self.pub_vehicle_state = rospy.Publisher('sim_model_state', Float64, queue_size=1)\n self.rate = rospy.Rate(self.PUBLISH_RATE_SIM)\n\n #####################################################\n # Define State Transition System #\n #####################################################\n def state_transition_system(self, t):\n return numpy.exp(self.A * t)\n\n #####################################################\n # Clear Screen #\n #####################################################\n def cls(self):\n os.system(\"clear\")\n\n ####################################################\n # Subscribe to pwm_interface #\n ####################################################\n def initialize_subscriber(self):\n while not rospy.is_shutdown():\n rospy.Subscriber(\"/pwm_interface\", pwm_interface, self.fetch_input)\n self.SUBSCRIBER_ACTIVE = True\n rospy.spin()\n self.SUBSCRIBER_ACTIVE = False\n\n ####################################################\n # Publish to /encoder/filtered #\n ####################################################\n def publish_velocity(self):\n while not rospy.is_shutdown():\n self.PUBLISH_ACTIVE = True\n self.pub_vehicle_state.publish(self.velocity_output)\n self.PUBLISH_ACTIVE = False\n self.rate.sleep()\n self.PUBLISHER_ACTIVE = True\n self.PUBLISHER_ACTIVE = False\n\n ####################################################\n # Callback function for updating control input #\n ####################################################\n def fetch_input(self, ctrl_input):\n self.control_input = ctrl_input.velocity\n #print('Received {0}'.format(self.control_input_velocity_PWM))\n self.CONTROL_INPUT_UPDATED = True\n\n\n #####################################################\n # SET PARAMETER #\n #####################################################\n def set_f1vt18_parameter(self, parameter_name, value=False):\n resolved_global_name = \"/f1vt18/\" + parameter_name\n rospy.set_param(resolved_global_name, value)\n\n #####################################################\n # SET PARAMETER #\n #####################################################\n def get_f1vt18_parameter(self, parameter_name, value=False):\n resolved_global_name = \"/f1vt18/\" + parameter_name\n return rospy.get_param(resolved_global_name, value)\n\n #####################################################\n # UPDATE PARAMETERS #\n #####################################################\n def update_parameters(self):\n while not rospy.is_shutdown():\n while not self.PARAMETERS_INITIALIZED:\n self.PARAMETERS_INITIALIZED = self.get_f1vt18_parameter(\"PARAMETERS_INITIALIZED\")\n self.set_f1vt18_parameter(\"MAIN_INTERFACE_STARTED\", self.MAIN_INTERFACE_STARTED)\n pass\n\n self.PARAMETER_UPDATED = True\n self.set_f1vt18_parameter(\"MAIN_INTERFACE_STARTED\", self.MAIN_INTERFACE_STARTED)\n self.MAIN_INTERFACE_STARTED = False\n self.set_f1vt18_parameter(\"MAIN_INTERFACE_STARTED\", self.MAIN_INTERFACE_STARTED)\n\n ####################################################\n # UPDATE STATE #\n ####################################################\n def update_state(self):\n while not rospy.is_shutdown():\n while not self.PARAMETERS_INITIALIZED:\n pass\n self.CONTROL_INPUT_UPDATED = False\n print(\"WAIT FOR CONTROL_INPUT_UPDATED\\r\")\n while not self.CONTROL_INPUT_UPDATED:\n pass\n\n self.u_curr = self.control_input\n print(\"UPDATED CONTROL INPUT SUCCESSFUL\\r\")\n\n print(\"COMPUTING NEW_STATE\\r\")\n print('xc= {0}, xn= {1}, u= {2} '.format(self.x_curr, self.x_next, self.u_curr))\n print('PHI= {0}, THETA= {1} '.format(self.PHI, self.THETA))\n print('A= {0}, B_INT= {1} '.format(self.A, self.B_INT))\n self.x_next = self.PHI*self.x_curr + self.THETA*self.u_curr\n self.y_next = self.C*self.x_next + self.D*self.u_curr\n self.x_curr = self.x_next\n\n while self.PUBLISH_ACTIVE:\n pass\n self.velocity_output.data = self.y_next\n self.SIMULATION_ACTIVE = False\n\n\n #####################################################\n # Initialize Control Interface for Terminal #\n #####################################################\n def display_interface(self):\n #####################################################\n # WHILE LOOP to DISPLAY INTERFACE #\n #####################################################\n while not rospy.is_shutdown():\n print(\"#######################################################\\r\")\n print(\" Waiting for PARAMETERS TO BE INITIALIZED \\r\")\n print(\"-------------------------------------------------------\\r\")\n while not self.PARAMETERS_INITIALIZED and not rospy.is_shutdown():\n pass\n print(\" PARAMETERS INITIALIZED \\r\")\n print(\"-------------------------------------------------------\\r\")\n\n #####################################################\n # UPDATE PARAMETERS FROM ROS PARAMETER SERVER #\n #####################################################\n self.PARAMETER_UPDATED = False\n print(\"#######################################################\\r\")\n print(\" Waiting for PARAMETERS TO BE UPDATED \\r\")\n print(\"-------------------------------------------------------\\r\")\n while not self.PARAMETER_UPDATED and not rospy.is_shutdown():\n pass\n print(\" PARAMETERS UPDATED \\r\")\n print(\"-------------------------------------------------------\\r\")\n\n self.STATE_UPDATED = False\n print(\"#######################################################\\r\")\n print(\" Waiting for STATE TO BE UPDATED \\r\")\n print(\"-------------------------------------------------------\\r\")\n while not self.STATE_UPDATED and not rospy.is_shutdown():\n pass\n print(\" STATE UPDATED \\r\")\n print(\"-------------------------------------------------------\\r\")\n\n\n #####################################################\n # Print Control Interface to Terminal #\n #####################################################\n print(\"-------------------------------------------------------\\r\")\n print(\"#######################################################\\r\")\n print(\"Simulation Model Status : \\r\")\n print(\"-------------------------------------------------------\\r\")\n print(\"#######################################################\\r\")\n\n\n#####################################################\n# Main Function #\n#####################################################\nif __name__ == \"__main__\":\n try:\n print(\"#######################################################\\r\")\n print(\"# PROGRAM HAS BEEN STARTED #\\r\")\n print(\"#######################################################\\r\")\n print(\"... initialize vehicle object \\r\")\n time.sleep(1)\n sim_f1vt18 = Vehicle()\n\n thread_sub = ThreadedFunction(sim_f1vt18.initialize_subscriber)\n thread_pub = ThreadedFunction(sim_f1vt18.publish_velocity)\n thread_upd = ThreadedFunction(sim_f1vt18.update_parameters)\n thread_ini = ThreadedFunction(sim_f1vt18.update_state)\n\n thread_sub.start()\n thread_pub.start()\n thread_upd.start()\n thread_ini.start()\n\n sim_f1vt18.display_interface()\n\n except rospy.ROSInterruptException:\n print(\"#######################################################\\r\")\n print(\"# PROGRAM HAS BEEN INTERRUPTED #\\r\")\n print(\"#######################################################\\r\")\n rospy.set_param('/f1vt18/MAIN_INTERFACE_STARTED', False)\n pass\n","sub_path":"control/src/sim_model.py","file_name":"sim_model.py","file_ext":"py","file_size_in_byte":13234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"20720353","text":"import pickle\nimport time\nimport numpy as np\nfrom collections import defaultdict, OrderedDict\nfrom matplotlib import pyplot as plt\nfrom imagenet1000_clsid_to_human import clsid_to_human\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch import multiprocessing as mp\nimport viz\n\nmean = [0.485, 0.456, 0.406]\nstd = [0.229, 0.224, 0.225]\n\nmean_tensor = torch.cuda.FloatTensor(mean).view(1, -1, 1, 1)\nstd_tensor = torch.cuda.FloatTensor(std).view(1, -1, 1, 1)\n\ndef forward(model, x):\n x_norm = (x - mean_tensor)/std_tensor\n logits = model(x_norm)\n return logits\n\ndef _l2_normalize(d):\n d_reshaped = d.view(d.shape[0], -1, *(1 for _ in range(d.dim() - 2)))\n d /= torch.norm(d_reshaped, 2, dim=1, keepdim=True) + 1e-8\n return d\n\ndef _kl_div(log_probs, probs):\n kld = F.kl_div(log_probs, probs, size_average=False)\n return kld / log_probs.shape[0]\n\ndef _prox(delta, lr, lambda1):\n \"\"\"Compute the proximal operator of delta.\"\"\"\n prod = lr*lambda1\n delta = torch.where(delta<-prod, delta + prod, \n torch.where(delta 0\n delta = self._iterate(model, x, lambda1=lambda1, lambda2=lambda2, n_iter=n_iter, \n optim=optim, lr=lr, init=init, n_samples=n_samples, \n stddev_spread=stddev_spread)\n if magnitude:\n delta = delta.view(delta.shape[0], -1)\n delta = (delta*delta)\n delta = delta/torch.sum(delta, 1, keepdim=True)\n delta = delta.view(x.shape).data\n if times_input:\n delta *= x.data\n return delta\n\n def _iterate(self, model, x, lambda1=0., lambda2=20., n_iter=10, optim='proximal', lr=1e-1, \n init='zero', n_samples=16, stddev_spread=0.15):\n assert init in ['zero', 'random']\n assert optim in ['sgd', 'lbfgs', 'adam', 'proximal']\n x_orig = x\n if self._smooth:\n stddev = stddev_spread * (x.max() - x.min())\n x_repeat = x.repeat(n_samples, 1, 1, 1)\n noise = torch.randn(x_repeat.shape).cuda() * stddev\n x = noise + x_repeat.clone()\n\n if self._second_order:\n if self._full_hessian:\n x_grad, sigma_H, HEV, fn = self._full_eigen(model, x)\n if lambda1 == 0:\n sigma_H = sigma_H.type(torch.cuda.FloatTensor)\n delta = self._hessian_inverse(sigma_H, HEV, x_grad, lambda2)\n return delta\n else:\n if self._smooth:\n x_grad, sigma_H, fn = self._power_eigen(model, x, smooth=True)\n x_grad = x_grad.mean(0, keepdim=True)\n hvp_fn = lambda z: fn(z).mean(0, keepdim=True)\n else:\n x_grad, sigma_H, fn = self._power_eigen(model, x, smooth=False)\n hvp_fn = fn\n# print(sigma_H.shape)\n# print(lambda2.shape)\n lambda2 = sigma_H + lambda2\n else:\n hvp_fn = lambda z: 0.\n x_grad = self.default_gradient(model, x)\n if self._smooth:\n x_grad = x_grad.mean(0, keepdim=True)\n if lambda1 == 0:\n delta = (1/lambda2)*x_grad.detach().view(x_grad.shape[0], -1)\n return delta\n\n x_grad = x_grad.detach().view(x_grad.shape[0], -1)\n delta = self._initialize_delta(x_orig, init)\n if optim=='proximal':\n delta = self._proximal(n_iter, lr, delta, x_grad, \n hvp_fn, lambda1, lambda2)\n else:\n if optim == 'sgd':\n optimizer = torch.optim.SGD([delta], lr=lr, momentum=0.9)\n elif optim == 'lbfgs':\n optimizer = torch.optim.LBFGS([delta], lr=lr, history_size=50)\n elif optim =='adam':\n optimizer = torch.optim.Adam([delta], lr=lr)\n delta = self._optimize(optimizer, n_iter, delta,\n x_grad, hvp_fn, lambda1, lambda2)\n return delta\n\n def _optimize(self, optimizer, n_iter, delta, x_grad, hvp_fn,\n lambda1, lambda2):\n delta = delta.view(delta.shape[0], -1)\n for i in range(n_iter):\n def closure():\n optimizer.zero_grad()\n _, loss, _ = self._loss_and_grad(delta,\n x_grad, hvp_fn, lambda1, lambda2)\n# print('loss: %f' % loss)\n loss.backward()\n return loss\n # update delta\n optimizer.step(closure)\n return delta\n\n def _loss_and_grad(self, delta, x_grad, hvp_fn,\n lambda1, lambda2):\n# print('second_order: ', self._second_order)\n# if not(type(lambda1)==float):\n# print('lambda1.shape: ', lambda1.shape)\n# print('lambda2.shape: ', lambda2.shape)\n\n t1 = (x_grad*delta).sum(1, keepdim=True)\n# print('x_grad.shape: ', x_grad.shape)\n# print('delta.shape: ', delta.shape)\n# print('t1.shape: ', t1.shape)\n\n l1 = delta.abs().sum(1, keepdim=True)\n# print('delta.shape: ', delta.shape)\n# print('l1.shape: ', l1.shape)\n l1 = lambda1 * l1\n\n l2 = 0.5 * (delta * delta).sum(1, keepdim=True)\n# print('l2.shape: ', l2.shape)\n l2 = lambda2 * l2\n# print('l2.shape: ', l2.shape)\n grad = (lambda2 * delta) - x_grad\n# print('grad.shape before: ', grad.shape)\n\n if self._second_order:\n hvp = hvp_fn(delta)\n# print('hvp.shape: ', hvp.shape)\n t2 = 0.5 * (delta * hvp).sum(1, keepdim=True)\n# print('t2.shape: ', t2.shape)\n grad += -hvp\n# print('grad.shape after: ', grad.shape)\n else:\n t2 = torch.zeros_like(l2)\n# print('t2.shape: ', t2.shape)\n\n# print('elementwise loss: ', (-t1-t2+l1+l2))\n t1 = torch.sum(t1)\n l1 = torch.sum(l1)\n t2 = torch.sum(t2)\n l2 = torch.sum(l2)\n\n# print('t1: ', -t1)\n# print('t2: ', -t2)\n# print('l1: ', l1)\n# print('l2: ', l2)\n\n smooth_loss = (- t1 - t2 + l2)\n loss = (- t1 - t2 + l1 + l2)\n return smooth_loss, loss, grad\n\n def _proximal(self, n_iter, lr, delta, x_grad, hvp_fn,\n lambda1, lambda2):\n B = delta\n B_prev = B\n k = 1\n while True:\n mom = (k - 2)/(k + 1)\n V = B + mom*(B - B_prev)\n g_V, loss_V, grad_V = self._loss_and_grad(V, x_grad, \n hvp_fn, lambda1, lambda2)\n\n B_prev = B\n ls_beta = 0.5\n t = lr\n while True:\n # Compute the update based on gradient, then apply prox.\n B = V - t * grad_V\n B = _prox(B, t, lambda1)\n\n if ls_beta is None:\n break\n # The line search condition is to exit when g(b) <= g(v) +\n # grad_v.T@(b - v) + (1/2t)||b - v||^2.\n g_B, loss, grad_B = self._loss_and_grad(B, x_grad, \n hvp_fn, lambda1, lambda2)\n B_V_diff = B - V\n # grad_v.T@(b - v):\n c_2 = (grad_V * B_V_diff).sum()\n # (1/2t)||b - v||^2:\n c_3 = ((B_V_diff ** 2).sum()) / (2. * t)\n\n upper_bound = g_V + c_2 + c_3\n# print('learning rate: %f' % t)\n# print('loss_B: %f' % loss)\n# print('smooth loss: %f' % g_B)\n# print('upper bound loss: %f' % upper_bound)\n if g_B <= upper_bound:\n# print('Condition satisfied')\n break\n else:\n t *= ls_beta\n k = k + 1\n if (k-1)==n_iter:\n break\n return B\n\n def stress_test(self, model, x):\n assert x.shape[0] == 1\n x_grad_full, sigma_H_full, HEV, hvp_fn_full = self._full_eigen(model, x)\n print('Eigenvalues of the full hessian: ', sigma_H_full.cpu().numpy().tolist())\n\n x_grad_power, sigma_H_power, hvp_fn_power = self._power_eigen(model, x)\n print('Power iteration eigenvalue: ', sigma_H_power)\n\n HEV = HEV.t()\n for i,evec in enumerate(HEV[:20]):\n evec = evec.view(1, -1)\n print(evec.shape)\n hvp_evec = hvp_fn_power(evec)\n print('Returned eigenvalue power: ', torch.norm(hvp_evec))\n print('Returned eigenvalue full: ', torch.norm(hvp_fn_full(evec)))\n print('Expected eigenvalue: ', sigma_H_full[i])\n print('Eigenvector difference: ', torch.norm(evec-F.normalize(hvp_evec)))\n\n print('Gradient difference: ', torch.norm(x_grad_power-x_grad_full))\n print(x_grad_full.shape)\n print(HEV.shape)\n grad_evec = HEV.mm(x_grad_full.t()).view(-1)\n print('Gradient Hessian eigenvectors product: ', grad_evec.cpu().numpy().tolist())\n print('Gradient Hessian eigenvectors product norm: ', torch.norm(grad_evec))\n print('Power Gradient norm: ', torch.norm(x_grad_power))\n print('Full Gradient norm: ', torch.norm(x_grad_full))\n return sigma_H_power\n\n def stress_test_hessian_gradient(self, model, x):\n x_grad, sigma_H, hev, hvp_fn = self._power_eigen(model, x, return_vec=True)\n dot_product = torch.abs(torch.sum(x_grad*hev, 1))\n dot_product = dot_product/torch.norm(x_grad, 2, 1)\n return dot_product\n\n def stress_test_gradient_orth(self, model, x):\n x_grad, sigma_H, HEV, hvp_fn = self._full_eigen(model, x)\n dot_product = torch.abs(x_grad.mm(HEV))\n dot_product = dot_product/torch.norm(x_grad, 2, 1)\n par_comp = torch.sum(dot_product*dot_product, 1)\n orth_comp = 1 - par_comp\n return dot_product, orth_comp\n\n def _hessian_inverse(self, sigma_H, HEV, vec, lambda2=1.):\n# print('Inside hessian inverse')\n# print(sigma_H[0])\n lambda2 = lambda2 + sigma_H[0]\n par_components_H = vec.mm(HEV)\n par_eigval_Hinv = torch.reciprocal(lambda2 - sigma_H).view(1, -1)\n par_components_Hinv = par_components_H*par_eigval_Hinv\n\n par_eigvec_H = par_components_H.mm(HEV.t()) #component parallel to eigenvectors of H\n par_eigvec_Hinv = par_components_Hinv.mm(HEV.t()) #component parallel to eigenvectors of Hinv\n orth_eigvec_H = vec - par_eigvec_H #component orthogonal to eigenvectors of H\n orth_eigvec_Hinv = torch.reciprocal(lambda2)*orth_eigvec_H\n Hinv_vec = par_eigvec_Hinv + orth_eigvec_Hinv\n\n Hinv_vec_normalized = Hinv_vec/torch.norm(Hinv_vec)\n# print(torch.norm(Hinv_vec))\n vec_normalized = vec/torch.norm(vec)\n# print(torch.norm(vec))\n par_vec = np.abs(torch.sum(vec_normalized*Hinv_vec_normalized).detach().cpu().numpy())\n par_vec = par_vec*par_vec\n orth_vec = 1 - par_vec\n self.components = np.asarray([par_vec, orth_vec])\n\n# normalized_parallel_components = np.abs((Hinv_vec_normalized.mm(HEV)).detach().cpu().numpy()).flatten()\n# normalized_parallel_components = normalized_parallel_components*normalized_parallel_components\n# self.normalized_parallel_components = normalized_parallel_components\n# print('parallel components: ', normalized_parallel_components[:5])\n# print('total parallel component:', np.sum(normalized_parallel_components))\n# self.normalized_orthogonal_components = max(0, 1 - np.sum(normalized_parallel_components))\n# print('orthogonal components: ', self.normalized_orthogonal_components)\n# print('orthogonal components: ', par_components_H/torch.norm(vec))\n return Hinv_vec\n\n def stress_test_hessian_inverse(self, model, x):\n assert x.shape[0] == 1\n lambda2 = 2.\n x_grad_full, sigma_H_full, HEV, hvp_fn_full = self._full_eigen(model, x)\n lambda2 = torch.tensor(lambda2).type(torch.cuda.FloatTensor)\n sigma_H_full = sigma_H_full.type(torch.cuda.FloatTensor)\n\n random_vec = torch.randn_like(x_grad_full)\n hvp = hvp_fn_full(random_vec)\n lambda2_mul = lambda2 + sigma_H_full[0]\n out = lambda2_mul*random_vec - hvp\n new = self._hessian_inverse(sigma_H_full, HEV, out, lambda2)\n print(torch.norm(new-random_vec))\n return sigma_H_full\n\n def stress_test_power(self, model, x):\n x_grad, sigma_H, hev, hvp_fn = self._power_eigen(model, x, return_vec=True)\n norms_ev = torch.norm(hvp_fn(hev), 2, 1)\n for i in range(len(hev)):\n grad, sigma_N, nhev, hvp_fn = self._power_eigen(model, x[i:i+1], \n return_vec=True)\n print('Returned eigenvalue: ', sigma_N)\n print('Expected eigenvalue: ', sigma_H[i])\n print('Normed eigenvalue: ', norms_ev[i])\n print('Eigenvector difference: ', torch.norm(nhev-hev[i:i+1]))\n return sigma_H\n\n def stress_test_power_multi(self, model, x):\n assert x.shape[0] > 1\n x_grad, sigma_H, hev, hvp_fn = self._power_eigen(model, x, return_vec=True)\n norms_ev = torch.norm(hvp_fn(hev), 2, 1)\n for i in range(len(hev)):\n grad, sigma_N, nhev, hvp_fn = self._power_eigen(model, x[i:i+1], \n return_vec=True)\n print('Returned eigenvalue: ', sigma_N)\n print('Expected eigenvalue: ', sigma_H[i])\n print('Normed eigenvalue: ', norms_ev[i])\n print('Eigenvector difference: ', torch.norm(nhev-hev[i:i+1]))\n return sigma_H\n\n def stress_test_forward(self, model, x):\n print(torch.min(x.view(x.shape[0], -1), dim=1)[0])\n print(torch.max(x.view(x.shape[0], -1), dim=1)[0])\n\n logits = forward(model, x)\n probs = F.softmax(logits, dim=1)\n class_prob, predicted_class = torch.max(probs, 1)\n predicted_class = predicted_class.cpu().numpy().tolist()\n class_prob = class_prob.detach().cpu().numpy().tolist()\n label_names = [clsid_to_human[z] for z in predicted_class]\n rows, columns = 3, 3\n f, ax = plt.subplots(rows, columns, figsize=(4 * columns, 4 * rows))\n max_images = min(rows*columns, x.shape[0])\n for i in range(rows):\n for j in range(columns):\n idx = rows*i + j\n if idx < max_images:\n img = x[idx]\n aax = ax[i, j]\n aax.set_axis_off()\n img = img.cpu().numpy().transpose(1,2,0)\n aax.imshow(img)\n prob_str = '%.2f' % class_prob[idx]\n aax.set_title(label_names[idx] + ', ' + prob_str)\n else:\n aax = ax[i, j]\n aax.set_axis_off()\n plt.tight_layout()\n f.savefig('test_forward.pdf')\n plt.close(f)\n\nclass IntegrateGradExplainer(Explainer):\n '''Integrated gradient. The final input multiplication is optional.\n\n See https://arxiv.org/abs/1703.01365.\n '''\n def __init__(self, n_iter=100, times_input=False):\n self.n_iter = n_iter\n self.times_input = times_input\n\n def explain(self, model, x):\n grad = 0\n x_data = x.clone()\n for alpha in np.arange(1 / self.n_iter, 1.0, 1 / self.n_iter):\n x_var = Variable(x_data * alpha, requires_grad=True)\n output = forward(model, x_var)\n max_logit, y = output.max(1)\n g, = torch.autograd.grad(max_logit, x_var)\n grad += g\n if self.times_input:\n grad *= x_data\n grad = grad / self.n_iter\n return grad\n\nclass SmoothGradExplainer(Explainer):\n '''\n See https://arxiv.org/abs/1706.03825.\n '''\n def __init__(self, base_explainer=None, stdev_spread=0.15,\n n_samples=16, magnitude=False, times_input=False):\n if base_explainer is None:\n base_explainer = VanillaGradExplainer()\n self.base_explainer = base_explainer\n self.stdev_spread = stdev_spread\n self.n_samples = n_samples\n self.magnitude = magnitude\n self.times_input = times_input\n\n def explain(self, model, x):\n stdev = self.stdev_spread * (x.max() - x.min())\n total_gradients = 0\n for i in range(self.n_samples):\n noise = torch.randn(x.shape).cuda() * stdev\n x_var = noise + x.clone()\n grad = self.base_explainer.explain(model, x_var)\n total_gradients += grad\n total_gradients /= self.n_samples\n if self.magnitude:\n total_gradients = total_gradients*total_gradients\n if self.times_input:\n total_gradients *= x\n return total_gradients\n","sub_path":"explainers.py","file_name":"explainers.py","file_ext":"py","file_size_in_byte":25894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"532722058","text":"# ...\nfrom csv import reader\nfrom sys import argv\n\n# ...\nwith open(argv[1], 'r') as file:\n for N, M in reader(file):\n N = int(N)\n M = int(M)\n print(N - int(N/M)*M)\n\n# ...\nfile.close()","sub_path":"Easy/Python/NModM.py","file_name":"NModM.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"282621272","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport time\nimport json\nimport flask\nimport dash\nfrom multiprocessing import Value\nfrom dash.dependencies import Input, Output, State\nimport dash_html_components as html\nimport dash_core_components as dcc\nfrom dash.exceptions import PreventUpdate\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\ntry:\n from urlparse import urlparse\nexcept ImportError:\n from urllib.parse import urlparse\nfrom IntegrationTests import IntegrationTests\n\nTIMEOUT = 10\n\n\nclass Test2(IntegrationTests):\n def setUp(self):\n pass\n\n def wait_for_element_by_css_selector(self, selector):\n return WebDriverWait(self.driver, TIMEOUT).until(\n EC.presence_of_element_located((By.CSS_SELECTOR, selector))\n )\n\n def wait_for_text_to_equal(self, selector, assertion_text):\n def text_equal(driver):\n text = driver.find_element_by_css_selector(selector).text\n return text == assertion_text\n\n WebDriverWait(self.driver, TIMEOUT).until(text_equal)\n\n def snapshot(self, name):\n if \"PERCY_PROJECT\" in os.environ and \"PERCY_TOKEN\" in os.environ:\n python_version = sys.version.split(\" \")[0]\n print(\"Percy Snapshot {}\".format(python_version))\n self.percy_runner.snapshot(name=name)\n\n def test_link_scroll(self):\n app = dash.Dash(__name__)\n app.layout = html.Div(\n [\n dcc.Location(id=\"test-url\", refresh=False),\n html.Div(\n id=\"push-to-bottom\",\n children=[],\n style={\"display\": \"block\", \"height\": \"200vh\"},\n ),\n html.Div(id=\"page-content\"),\n dcc.Link(\"Test link\", href=\"/test-link\", id=\"test-link\"),\n ]\n )\n\n call_count = Value(\"i\", 0)\n\n @app.callback(\n Output(\"page-content\", \"children\"), [Input(\"test-url\", \"pathname\")]\n )\n def display_page(pathname):\n call_count.value = call_count.value + 1\n return \"You are on page {}\".format(pathname)\n\n self.startServer(app=app)\n\n time.sleep(2)\n\n # callback is called twice when defined\n self.assertEqual(call_count.value, 2)\n\n # test if link correctly scrolls back to top of page\n test_link = self.wait_for_element_by_css_selector(\"#test-link\")\n test_link.send_keys(Keys.NULL)\n test_link.click()\n time.sleep(2)\n\n # test link still fires update on Location\n page_content = self.wait_for_element_by_css_selector(\"#page-content\")\n self.assertNotEqual(page_content.text, \"You are on page /\")\n\n self.wait_for_text_to_equal(\n \"#page-content\", \"You are on page /test-link\"\n )\n\n # test if rendered Link's tag has a href attribute\n link_href = test_link.get_attribute(\"href\")\n self.assertEqual(link_href, \"http://localhost:8050/test-link\")\n\n # test if callback is only fired once (offset of 2)\n self.assertEqual(call_count.value, 3)\n\n def test_candlestick(self):\n app = dash.Dash(__name__)\n app.layout = html.Div(\n [\n html.Button(\n id=\"button\", children=\"Update Candlestick\", n_clicks=0\n ),\n dcc.Graph(id=\"graph\"),\n ]\n )\n\n @app.callback(Output(\"graph\", \"figure\"), [Input(\"button\", \"n_clicks\")])\n def update_graph(n_clicks):\n return {\n \"data\": [\n {\n \"open\": [1] * 5,\n \"high\": [3] * 5,\n \"low\": [0] * 5,\n \"close\": [2] * 5,\n \"x\": [n_clicks] * 5,\n \"type\": \"candlestick\",\n }\n ]\n }\n\n self.startServer(app=app)\n\n button = self.wait_for_element_by_css_selector(\"#button\")\n self.snapshot(\"candlestick - initial\")\n button.click()\n time.sleep(1)\n self.snapshot(\"candlestick - 1 click\")\n\n button.click()\n time.sleep(1)\n self.snapshot(\"candlestick - 2 click\")\n\n def test_graphs_with_different_figures(self):\n app = dash.Dash(__name__)\n app.layout = html.Div(\n [\n dcc.Graph(\n id=\"example-graph\",\n figure={\n \"data\": [\n {\n \"x\": [1, 2, 3],\n \"y\": [4, 1, 2],\n \"type\": \"bar\",\n \"name\": \"SF\",\n },\n {\n \"x\": [1, 2, 3],\n \"y\": [2, 4, 5],\n \"type\": \"bar\",\n \"name\": u\"Montréal\",\n },\n ],\n \"layout\": {\"title\": \"Dash Data Visualization\"},\n },\n ),\n dcc.Graph(\n id=\"example-graph-2\",\n figure={\n \"data\": [\n {\n \"x\": [20, 24, 33],\n \"y\": [5, 2, 3],\n \"type\": \"bar\",\n \"name\": \"SF\",\n },\n {\n \"x\": [11, 22, 33],\n \"y\": [22, 44, 55],\n \"type\": \"bar\",\n \"name\": u\"Montréal\",\n },\n ],\n \"layout\": {\"title\": \"Dash Data Visualization\"},\n },\n ),\n html.Div(id=\"restyle-data\"),\n html.Div(id=\"relayout-data\"),\n ]\n )\n\n @app.callback(\n Output(\"restyle-data\", \"children\"),\n [Input(\"example-graph\", \"restyleData\")],\n )\n def show_restyle_data(data):\n if data is None: # ignore initial\n return \"\"\n return json.dumps(data)\n\n @app.callback(\n Output(\"relayout-data\", \"children\"),\n [Input(\"example-graph\", \"relayoutData\")],\n )\n def show_relayout_data(data):\n if (\n data is None or \"autosize\" in data\n ): # ignore initial & auto width\n return \"\"\n return json.dumps(data)\n\n self.startServer(app=app)\n\n # use this opportunity to test restyleData, since there are multiple\n # traces on this graph\n legendToggle = self.driver.find_element_by_css_selector(\n \"#example-graph .traces:first-child .legendtoggle\"\n )\n legendToggle.click()\n self.wait_for_text_to_equal(\n \"#restyle-data\", '[{\"visible\": [\"legendonly\"]}, [0]]'\n )\n\n # move snapshot after click, so it's more stable with the wait\n self.snapshot(\"2 graphs with different figures\")\n\n # and test relayoutData while we're at it\n autoscale = self.driver.find_element_by_css_selector(\n \"#example-graph .ewdrag\"\n )\n autoscale.click()\n autoscale.click()\n self.wait_for_text_to_equal(\n \"#relayout-data\", '{\"xaxis.autorange\": true}'\n )\n\n def test_interval(self):\n app = dash.Dash(__name__)\n app.layout = html.Div(\n [\n html.Div(id=\"output\"),\n dcc.Interval(id=\"interval\", interval=1, max_intervals=2),\n ]\n )\n\n @app.callback(\n Output(\"output\", \"children\"), [Input(\"interval\", \"n_intervals\")]\n )\n def update_text(n):\n return \"{}\".format(n)\n\n self.startServer(app=app)\n\n # wait for interval to finish\n time.sleep(5)\n\n self.wait_for_text_to_equal(\"#output\", \"2\")\n\n def test_if_interval_can_be_restarted(self):\n app = dash.Dash(__name__)\n app.layout = html.Div(\n [\n dcc.Interval(\n id=\"interval\",\n interval=100,\n n_intervals=0,\n max_intervals=-1,\n ),\n html.Button(\"Start\", id=\"start\", n_clicks_timestamp=-1),\n html.Button(\"Stop\", id=\"stop\", n_clicks_timestamp=-1),\n html.Div(id=\"output\"),\n ]\n )\n\n @app.callback(\n Output(\"interval\", \"max_intervals\"),\n [\n Input(\"start\", \"n_clicks_timestamp\"),\n Input(\"stop\", \"n_clicks_timestamp\"),\n ],\n )\n def start_stop(start, stop):\n if start < stop:\n return 0\n else:\n return -1\n\n @app.callback(\n Output(\"output\", \"children\"), [Input(\"interval\", \"n_intervals\")]\n )\n def display_data(n_intervals):\n return \"Updated {}\".format(n_intervals)\n\n self.startServer(app=app)\n\n start_button = self.wait_for_element_by_css_selector(\"#start\")\n stop_button = self.wait_for_element_by_css_selector(\"#stop\")\n\n # interval will start itself, we wait a second before pressing 'stop'\n time.sleep(1)\n\n # get the output after running it for a bit\n output = self.wait_for_element_by_css_selector(\"#output\")\n stop_button.click()\n\n time.sleep(1)\n\n # get the output after it's stopped, it shouldn't be higher than before\n output_stopped = self.wait_for_element_by_css_selector(\"#output\")\n\n self.wait_for_text_to_equal(\"#output\", output_stopped.text)\n\n # This test logic is bad\n # same element check for same text will always be true.\n self.assertEqual(output.text, output_stopped.text)\n\n def _test_confirm(self, app, test_name, add_callback=True):\n count = Value(\"i\", 0)\n\n if add_callback:\n\n @app.callback(\n Output(\"confirmed\", \"children\"),\n [\n Input(\"confirm\", \"submit_n_clicks\"),\n Input(\"confirm\", \"cancel_n_clicks\"),\n ],\n [\n State(\"confirm\", \"submit_n_clicks_timestamp\"),\n State(\"confirm\", \"cancel_n_clicks_timestamp\"),\n ],\n )\n def _on_confirmed(\n submit_n_clicks,\n cancel_n_clicks,\n submit_timestamp,\n cancel_timestamp,\n ):\n if not submit_n_clicks and not cancel_n_clicks:\n return \"\"\n count.value += 1\n if (submit_timestamp and cancel_timestamp is None) or (\n submit_timestamp > cancel_timestamp\n ):\n return \"confirmed\"\n else:\n return \"canceled\"\n\n self.startServer(app)\n button = self.wait_for_element_by_css_selector(\"#button\")\n self.snapshot(test_name + \" -> initial\")\n\n button.click()\n time.sleep(1)\n self.driver.switch_to.alert.accept()\n\n if add_callback:\n self.wait_for_text_to_equal(\"#confirmed\", \"confirmed\")\n self.snapshot(test_name + \" -> confirmed\")\n\n button.click()\n time.sleep(0.5)\n self.driver.switch_to.alert.dismiss()\n time.sleep(0.5)\n\n if add_callback:\n self.wait_for_text_to_equal(\"#confirmed\", \"canceled\")\n self.snapshot(test_name + \" -> canceled\")\n\n if add_callback:\n self.assertEqual(\n 2,\n count.value,\n \"Expected 2 callback but got \" + str(count.value),\n )\n\n def test_confirm(self):\n app = dash.Dash(__name__)\n\n app.layout = html.Div(\n [\n html.Button(id=\"button\", children=\"Send confirm\", n_clicks=0),\n dcc.ConfirmDialog(id=\"confirm\", message=\"Please confirm.\"),\n html.Div(id=\"confirmed\"),\n ]\n )\n\n @app.callback(\n Output(\"confirm\", \"displayed\"), [Input(\"button\", \"n_clicks\")]\n )\n def on_click_confirm(n_clicks):\n if n_clicks:\n return True\n\n self._test_confirm(app, \"ConfirmDialog\")\n\n def test_confirm_dialog_provider(self):\n app = dash.Dash(__name__)\n\n app.layout = html.Div(\n [\n dcc.ConfirmDialogProvider(\n html.Button(\"click me\", id=\"button\"),\n id=\"confirm\",\n message=\"Please confirm.\",\n ),\n html.Div(id=\"confirmed\"),\n ]\n )\n\n self._test_confirm(app, \"ConfirmDialogProvider\")\n\n def test_confirm_without_callback(self):\n app = dash.Dash(__name__)\n app.layout = html.Div(\n [\n dcc.ConfirmDialogProvider(\n html.Button(\"click me\", id=\"button\"),\n id=\"confirm\",\n message=\"Please confirm.\",\n ),\n html.Div(id=\"confirmed\"),\n ]\n )\n self._test_confirm(\n app, \"ConfirmDialogProviderWithoutCallback\", add_callback=False\n )\n\n def test_confirm_as_children(self):\n app = dash.Dash(__name__)\n\n app.layout = html.Div(\n [\n html.Button(id=\"button\", children=\"Send confirm\"),\n html.Div(id=\"confirm-container\"),\n dcc.Location(id=\"dummy-location\"),\n ]\n )\n\n @app.callback(\n Output(\"confirm-container\", \"children\"),\n [Input(\"button\", \"n_clicks\")],\n )\n def on_click(n_clicks):\n if n_clicks:\n return dcc.ConfirmDialog(\n displayed=True, id=\"confirm\", message=\"Please confirm.\"\n )\n\n self.startServer(app)\n\n button = self.wait_for_element_by_css_selector(\"#button\")\n\n button.click()\n time.sleep(2)\n\n self.driver.switch_to.alert.accept()\n\n def test_empty_graph(self):\n app = dash.Dash(__name__)\n\n app.layout = html.Div(\n [\n html.Button(id=\"click\", children=\"Click me\"),\n dcc.Graph(\n id=\"graph\",\n figure={\n \"data\": [\n dict(x=[1, 2, 3], y=[1, 2, 3], type=\"scatter\")\n ]\n },\n ),\n ]\n )\n\n @app.callback(\n dash.dependencies.Output(\"graph\", \"figure\"),\n [dash.dependencies.Input(\"click\", \"n_clicks\")],\n [dash.dependencies.State(\"graph\", \"figure\")],\n )\n def render_content(click, prev_graph):\n if click:\n return {}\n return prev_graph\n\n self.startServer(app)\n button = self.wait_for_element_by_css_selector(\"#click\")\n button.click()\n time.sleep(2) # Wait for graph to re-render\n self.snapshot(\"render-empty-graph\")\n\n def test_graph_extend_trace(self):\n app = dash.Dash(__name__)\n\n def generate_with_id(id, data=None):\n if data is None:\n data = [{\"x\": [0, 1, 2, 3, 4], \"y\": [0, 0.5, 1, 0.5, 0]}]\n\n return html.Div(\n [\n html.P(id),\n dcc.Graph(id=id, figure=dict(data=data)),\n html.Div(id=\"output_{}\".format(id)),\n ]\n )\n\n figs = [\n \"trace_will_extend\",\n \"trace_will_extend_with_no_indices\",\n \"trace_will_extend_with_max_points\",\n ]\n\n layout = [generate_with_id(id) for id in figs]\n\n figs.append(\"trace_will_allow_repeated_extend\")\n data = [{\"y\": [0, 0, 0]}]\n layout.append(generate_with_id(figs[-1], data))\n\n figs.append(\"trace_will_extend_selectively\")\n data = [\n {\"x\": [0, 1, 2, 3, 4], \"y\": [0, 0.5, 1, 0.5, 0]},\n {\"x\": [0, 1, 2, 3, 4], \"y\": [1, 1, 1, 1, 1]},\n ]\n layout.append(generate_with_id(figs[-1], data))\n\n layout.append(\n dcc.Interval(\n id=\"interval_extendablegraph_update\",\n interval=10,\n n_intervals=0,\n max_intervals=1,\n )\n )\n\n layout.append(\n dcc.Interval(\n id=\"interval_extendablegraph_extendtwice\",\n interval=500,\n n_intervals=0,\n max_intervals=2,\n )\n )\n\n app.layout = html.Div(layout)\n\n @app.callback(\n Output(\"trace_will_allow_repeated_extend\", \"extendData\"),\n [Input(\"interval_extendablegraph_extendtwice\", \"n_intervals\")],\n )\n def trace_will_allow_repeated_extend(n_intervals):\n if n_intervals is None or n_intervals < 1:\n raise PreventUpdate\n\n return dict(y=[[0.1, 0.2, 0.3, 0.4, 0.5]])\n\n @app.callback(\n Output(\"trace_will_extend\", \"extendData\"),\n [Input(\"interval_extendablegraph_update\", \"n_intervals\")],\n )\n def trace_will_extend(n_intervals):\n if n_intervals is None or n_intervals < 1:\n raise PreventUpdate\n\n x_new = [5, 6, 7, 8, 9]\n y_new = [0.1, 0.2, 0.3, 0.4, 0.5]\n return dict(x=[x_new], y=[y_new]), [0]\n\n @app.callback(\n Output(\"trace_will_extend_selectively\", \"extendData\"),\n [Input(\"interval_extendablegraph_update\", \"n_intervals\")],\n )\n def trace_will_extend_selectively(n_intervals):\n if n_intervals is None or n_intervals < 1:\n raise PreventUpdate\n\n x_new = [5, 6, 7, 8, 9]\n y_new = [0.1, 0.2, 0.3, 0.4, 0.5]\n return dict(x=[x_new], y=[y_new]), [1]\n\n @app.callback(\n Output(\"trace_will_extend_with_no_indices\", \"extendData\"),\n [Input(\"interval_extendablegraph_update\", \"n_intervals\")],\n )\n def trace_will_extend_with_no_indices(n_intervals):\n if n_intervals is None or n_intervals < 1:\n raise PreventUpdate\n\n x_new = [5, 6, 7, 8, 9]\n y_new = [0.1, 0.2, 0.3, 0.4, 0.5]\n return dict(x=[x_new], y=[y_new])\n\n @app.callback(\n Output(\"trace_will_extend_with_max_points\", \"extendData\"),\n [Input(\"interval_extendablegraph_update\", \"n_intervals\")],\n )\n def trace_will_extend_with_max_points(n_intervals):\n if n_intervals is None or n_intervals < 1:\n raise PreventUpdate\n\n x_new = [5, 6, 7, 8, 9]\n y_new = [0.1, 0.2, 0.3, 0.4, 0.5]\n return dict(x=[x_new], y=[y_new]), [0], 7\n\n for id in figs:\n\n @app.callback(\n Output(\"output_{}\".format(id), \"children\"),\n [Input(id, \"extendData\")],\n [State(id, \"figure\")],\n )\n def display_data(trigger, fig):\n return json.dumps(fig[\"data\"])\n\n self.startServer(app)\n\n comparison = json.dumps(\n [\n dict(\n x=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n y=[0, 0.5, 1, 0.5, 0, 0.1, 0.2, 0.3, 0.4, 0.5],\n )\n ]\n )\n self.wait_for_text_to_equal(\"#output_trace_will_extend\", comparison)\n self.wait_for_text_to_equal(\n \"#output_trace_will_extend_with_no_indices\", comparison\n )\n comparison = json.dumps(\n [\n dict(x=[0, 1, 2, 3, 4], y=[0, 0.5, 1, 0.5, 0]),\n dict(\n x=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n y=[1, 1, 1, 1, 1, 0.1, 0.2, 0.3, 0.4, 0.5],\n ),\n ]\n )\n self.wait_for_text_to_equal(\n \"#output_trace_will_extend_selectively\", comparison\n )\n\n comparison = json.dumps(\n [\n dict(\n x=[3, 4, 5, 6, 7, 8, 9],\n y=[0.5, 0, 0.1, 0.2, 0.3, 0.4, 0.5],\n )\n ]\n )\n self.wait_for_text_to_equal(\n \"#output_trace_will_extend_with_max_points\", comparison\n )\n\n comparison = json.dumps(\n [\n dict(\n y=[\n 0,\n 0,\n 0,\n 0.1,\n 0.2,\n 0.3,\n 0.4,\n 0.5,\n 0.1,\n 0.2,\n 0.3,\n 0.4,\n 0.5,\n ]\n )\n ]\n )\n self.wait_for_text_to_equal(\n \"#output_trace_will_allow_repeated_extend\", comparison\n )\n\n def test_user_supplied_css(self):\n app = dash.Dash(__name__)\n\n app.layout = html.Div(\n className=\"test-input-css\", children=[dcc.Input()]\n )\n\n self.startServer(app)\n\n self.wait_for_element_by_css_selector(\".test-input-css\")\n self.snapshot(\"styled input - width: 100%, border-color: hotpink\")\n\n def test_logout_btn(self):\n app = dash.Dash(__name__)\n\n @app.server.route(\"/_logout\", methods=[\"POST\"])\n def on_logout():\n rep = flask.redirect(\"/logged-out\")\n rep.set_cookie(\"logout-cookie\", \"\", 0)\n return rep\n\n app.layout = html.Div(\n [\n html.H2(\"Logout test\"),\n dcc.Location(id=\"location\"),\n html.Div(id=\"content\"),\n ]\n )\n\n @app.callback(\n Output(\"content\", \"children\"), [Input(\"location\", \"pathname\")]\n )\n def on_location(location_path):\n if location_path is None:\n raise PreventUpdate\n\n if \"logged-out\" in location_path:\n return \"Logged out\"\n else:\n\n @flask.after_this_request\n def _insert_cookie(rep):\n rep.set_cookie(\"logout-cookie\", \"logged-in\")\n return rep\n\n return dcc.LogoutButton(id=\"logout-btn\", logout_url=\"/_logout\")\n\n self.startServer(app)\n time.sleep(1)\n self.snapshot(\"Logout button\")\n\n self.assertEqual(\n \"logged-in\", self.driver.get_cookie(\"logout-cookie\")[\"value\"]\n )\n logout_button = self.wait_for_element_by_css_selector(\"#logout-btn\")\n logout_button.click()\n self.wait_for_text_to_equal(\"#content\", \"Logged out\")\n\n self.assertFalse(self.driver.get_cookie(\"logout-cookie\"))\n\n def test_simple_callback(self):\n app = dash.Dash(__name__)\n app.layout = html.Div(\n [\n dcc.Input(id=\"input\"),\n html.Div(\n html.Div([1.5, None, \"string\", html.Div(id=\"output-1\")])\n ),\n ]\n )\n\n call_count = Value(\"i\", 0)\n\n @app.callback(\n Output(\"output-1\", \"children\"), [Input(\"input\", \"value\")]\n )\n def update_output(value):\n call_count.value = call_count.value + 1\n return value\n\n self.startServer(app)\n\n input1 = self.wait_for_element_by_css_selector(\"#input\")\n input1.send_keys(\"hello world\")\n output1 = self.wait_for_element_by_css_selector(\"#output-1\")\n self.wait_for_text_to_equal(\"#output-1\", \"hello world\")\n output1.click() # Lose focus, no callback sent for value.\n\n self.assertEqual(\n call_count.value,\n # an initial call to retrieve the first value\n # plus one for each hello world character\n 1 + len(\"hello world\"),\n )\n\n def test_disabled_tab(self):\n app = dash.Dash(__name__)\n app.layout = html.Div(\n [\n html.H1(\"Dash Tabs component with disabled tab demo\"),\n dcc.Tabs(\n id=\"tabs-example\",\n value=\"tab-2\",\n children=[\n dcc.Tab(\n label=\"Disabled Tab\",\n value=\"tab-1\",\n id=\"tab-1\",\n className=\"test-custom-tab\",\n disabled=True,\n ),\n dcc.Tab(\n label=\"Active Tab\",\n value=\"tab-2\",\n id=\"tab-2\",\n className=\"test-custom-tab\",\n ),\n ],\n ),\n html.Div(id=\"tabs-content-example\"),\n ]\n )\n self.startServer(app=app)\n\n WebDriverWait(self.driver, TIMEOUT).until(\n EC.element_to_be_clickable((By.ID, \"tab-2\"))\n )\n\n WebDriverWait(self.driver, TIMEOUT).until(\n EC.visibility_of_element_located(\n (By.CSS_SELECTOR, \".tab--disabled\")\n )\n )\n\n def test_unmounted_graph_resize(self):\n app = dash.Dash(__name__)\n\n app.layout = html.Div(\n children=[\n dcc.Tabs(\n id=\"tabs\",\n children=[\n dcc.Tab(\n label=\"Tab one\",\n children=[\n html.Div(\n [\n dcc.Graph(\n id=\"eg-graph-1\",\n figure={\n \"data\": [\n {\n \"x\": [1, 2, 3],\n \"y\": [4, 1, 2],\n \"type\": \"scattergl\",\n \"name\": \"SF\",\n },\n {\n \"x\": [1, 2, 3],\n \"y\": [2, 4, 5],\n \"type\": \"scattergl\",\n \"name\": u\"Montréal\",\n },\n ]\n },\n )\n ],\n id=\"graph-tab-1\",\n )\n ],\n ),\n dcc.Tab(\n label=\"Tab two\",\n children=[\n dcc.Graph(\n id=\"eg-graph-2\",\n figure={\n \"data\": [\n {\n \"x\": [1, 2, 3],\n \"y\": [1, 4, 1],\n \"type\": \"scattergl\",\n \"name\": \"SF\",\n },\n {\n \"x\": [1, 2, 3],\n \"y\": [1, 2, 3],\n \"type\": \"scattergl\",\n \"name\": u\"Montréal\",\n },\n ]\n },\n )\n ],\n id=\"graph-tab-2\",\n ),\n ],\n )\n ]\n )\n\n self.startServer(app)\n\n try:\n self.wait_for_element_by_css_selector(\"#eg-graph-1\")\n except Exception as e:\n print(\n self.wait_for_element_by_css_selector(\n \"#_dash-app-content\"\n ).get_attribute(\"innerHTML\")\n )\n raise e\n\n WebDriverWait(self.driver, 10).until(\n EC.element_to_be_clickable((By.ID, \"graph-tab-2\"))\n )\n\n tab_two = self.wait_for_element_by_css_selector(\"#graph-tab-2\")\n\n tab_two.click()\n\n # save the current window size\n window_size = self.driver.get_window_size()\n\n # resize\n self.driver.set_window_size(800, 600)\n\n for entry in self.get_log():\n raise Exception(\"browser error logged during test\", entry)\n\n # set back to original size\n self.driver.set_window_size(\n window_size[\"width\"], window_size[\"height\"]\n )\n","sub_path":"tests/test_integration_2.py","file_name":"test_integration_2.py","file_ext":"py","file_size_in_byte":29624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"45753840","text":"from pygame.sprite import Sprite\nimport pygame\nfrom math import hypot\nclass Arrow(Sprite):\n def __init__(self,theHero):\n super(Arrow,self).__init__()\n self.x = theHero.x\n self.y = theHero.y\n self.speed = 25\n self.rect = pygame.Rect(0,0,64,64)\n self.rect.centerx = self.x\n self.rect.centery = self.y\n def update_me(self,enemy):\n dx = self.x - enemy.x\n dy = self.y - enemy.y\n dist = hypot(dx,dy)\n dx = dx/dist\n dy = dy/dist\n self.x -= dx*self.speed\n self.y -= dy*self.speed\n","sub_path":"Shooter_Game/Weapon.py","file_name":"Weapon.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"125557369","text":"#############################################################################\n# Copyright (C) 2019 Olaf Japp\n#\n# This file is part of EbookCreator.\n#\n# EbookCreator is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# EbookCreator 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 EbookCreator. If not, see .\n#\n#############################################################################\n\nimport os\nfrom pathlib import Path\nfrom markdown2 import markdown\nfrom generator import addLineNumbers\nfrom PyQt5.QtWebEngineWidgets import QWebEnginePage\nfrom PyQt5.QtGui import QPageLayout, QPageSize\nfrom PyQt5.QtWidgets import QApplication\nfrom PyQt5.QtCore import Qt, QUrl\n\n\nclass PdfExport():\n def __init__(self, filename, book, status_bar):\n QApplication.setOverrideCursor(Qt.WaitCursor)\n self.filename = filename\n self.status_bar = status_bar\n \n html = \"\\n\\n\"\n html += \"\\n\"\n html += \"\\n\"\n html += \"\\n\\n\"\n for part in book._parts:\n self.status_bar.showMessage(\"Processing \" + part.name)\n with open(os.path.join(book.source_path, \"parts\", part.src), \"r\") as i:\n text = i.read()\n htm = markdown(text, html4tags = False, extras=[\"fenced-code-blocks\", \"wiki-tables\", \"tables\", \"header-ids\"])\n htm = addLineNumbers(htm)\n html += htm\n html += \"\\n\\n\"\n\n self.status_bar.showMessage(\"Loading HTML\")\n self.page = QWebEnginePage()\n self.page.loadFinished.connect(self.loadFinished)\n self.page.pdfPrintingFinished.connect(self.printFinished)\n self.page.setHtml(html, QUrl(Path(os.path.join(book.source_path, \"parts\", \"index.html\")).as_uri()))\n\n def loadFinished(self, ok):\n if ok:\n self.status_bar.showMessage(\"Printing PDF\")\n self.page.printToPdf(self.filename, pageLayout=QPageLayout(QPageSize(QPageSize.A5), QPageLayout.Portrait, QMarginsF(30.0, 30.0, 30.0, 30.0)))\n else:\n self.status_bar.showMessage(\"There was an error printing the PDF\")\n\n def printFinished(self, filename, success):\n QApplication.restoreOverrideCursor()\n if success:\n self.status_bar.showMessage(\"PDF created\")\n else:\n self.status_bar.showMessage(\"There was an error printing the PDF\")","sub_path":"pdfexport.py","file_name":"pdfexport.py","file_ext":"py","file_size_in_byte":2999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"31144873","text":"import pyqtgraph as pg\nfrom pyqtgraph.Qt import QtGui, QtCore,QtWidgets\n\n\n# from . tools import *\nfrom . debug_draw import *\nimport pybox2d\n\n\n\nclass DebugDrawViewBox(pg.ViewBox):\n def __init__(self):\n super(DebugDrawViewBox, self).__init__(lockAspect=True,\n enableMouse=True)\n self.framework = None\n\n self.debug_draw_graphics_object = DebugDrawGraphicsObject()\n self.debug_draw = self.debug_draw_graphics_object.debug_draw\n self.addItem(self.debug_draw_graphics_object)\n\n def set_example(self, example):\n self.framework = example\n self.debug_draw_graphics_object.set_example(example)\n\n\n # def keyPressEvent(self, event):\n # print('press the key: \"%s\" '%event.text())\n\n # def keyReleaseEvent(self, event):\n # print('release the key: \"%s\" '%event.text())\n\n def mousePressEvent(self, ev):\n modifiers = QtGui.QApplication.keyboardModifiers()\n ctrl_mod = (modifiers == QtCore.Qt.ControlModifier)\n if ctrl_mod:\n super(DebugDrawViewBox, self).mousePressEvent(ev)\n else:\n debug_draw_graphics_object = self.debug_draw_graphics_object\n pos = ev.pos()\n canvas_pos = self.mapToView( pos)\n if self.framework.on_mouse_down(pybox2d.vec2(canvas_pos.x(),canvas_pos.y())):\n ev.accept()\n else:\n super(DebugDrawViewBox, self).mousePressEvent(ev)\n\n \n def mouseMoveEvent(self, ev):\n pos = ev.pos()\n canvas_pos = self.mapToView( pos)\n if self.framework.on_mouse_move(pybox2d.vec2(canvas_pos.x(),canvas_pos.y())):\n ev.accept()\n else:\n super(DebugDrawViewBox, self).mouseMoveEvent(ev)\n\n def mouseReleaseEvent(self, ev):\n pos = ev.pos()\n canvas_pos = self.mapToView( pos)\n if self.framework.on_mouse_up(pybox2d.vec2(canvas_pos.x(),canvas_pos.y())):\n ev.accept()\n else:\n super(DebugDrawViewBox, self).mouseReleaseEvent(ev)\n\n\n def updateDebugDraw(self):\n \n self.debug_draw_graphics_object.update()\n","sub_path":"liquidfun/Box2D/pybox2d/testbed/framework/framework/pg_gui/debug_draw_view_box.py","file_name":"debug_draw_view_box.py","file_ext":"py","file_size_in_byte":2139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"351596821","text":"# -*- coding: utf-8 -*-\n\nfrom collections import defaultdict\nimport datetime\nimport sys\nsys.path.append(r'E:\\PyCharmWorkplace\\weibo_prediction')\nfrom utils import get_fields, log\n\n\n__author__ = 'lk'\n\n\ndef stat_rtnum_dist(tfilename, retfilename):\n \"\"\"\n 24小时转发数分布\n :param tfilename:\n :param retfilename:\n :param days:\n :return:\n \"\"\"\n mid2rtnum = defaultdict(int)\n rtnum2tnum = defaultdict(int)\n td = datetime.timedelta(seconds=24*60*60)\n\n log('Start collecting data from %s' % tfilename)\n with open(tfilename) as tfile:\n for line in tfile:\n fields = get_fields(line)\n if 'rtMid' not in fields:\n mid = fields['mid']\n mid2rtnum[mid] = 0\n else:\n rtmid = fields['rtMid']\n time = datetime.datetime.strptime(fields['time'], '%Y-%m-%d %H:%M:%S')\n rttime = datetime.datetime.strptime(fields['rtTime'], '%Y-%m-%d %H:%M:%S')\n if time - rttime < td: # 1小时内\n mid2rtnum[rtmid] += 1\n\n for rtnum in mid2rtnum.itervalues():\n rtnum2tnum[rtnum] += 1\n\n items = sorted(rtnum2tnum.items(), key=lambda item: item[0])\n with open(retfilename, 'w') as retfile:\n for rtnum, tnum in items:\n retfile.write('%d\\t%d\\n' % (rtnum, tnum))\n\n\nif __name__ == '__main__':\n\n tfilename = sys.argv[1]\n retfilename = sys.argv[2]\n\n stat_rtnum_dist(tfilename, retfilename)\n","sub_path":"scripts/stat_rtnum_dist.py","file_name":"stat_rtnum_dist.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"168184985","text":"import argparse, importlib, dis, subprocess, os, ast\nimport src.opscodes as ops\n\nparser = argparse.ArgumentParser(add_help=True)\nparser.add_argument('-f', type=str, help=\"file to convert\")\nargs = parser.parse_args()\n\nwith open('pyscripts/'+args.f+'.py') as f:\n\tc = f.read()\n\ta = ast.parse(c, args.f, 'exec')\n\tprint(ast.dump(a))\n\ts = compile(a, args.f, 'exec')\n\n# Write PlusCal\nb = ops.OpsCode(s, args.f)\nb.convert()\n\nwith open('tla/%s.tla' % (args.f, ), 'w') as of:\n\tof.write(b.output.assemble())\n\n# Open Vim to add tests\ncmd = '%s tla/%s.tla' % (os.environ.get('EDITOR', 'vi'), args.f)\nsubprocess.call(cmd, shell=True)\n\n# Translate PlusCal to TLA\nsubprocess.call('pcal tla/%s.tla' % (args.f,), shell=True)\n\n# Run Models\nsubprocess.call('tlc tla/%s.tla' % (args.f,), shell=True)\n\n","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"449247851","text":"import logging\nimport os\nimport random\n\nimport numpy as np\nimport pytorch_lightning as pl\nimport torch\nfrom pytorch_lightning.loggers import WandbLogger\nfrom pytorch_lightning.callbacks.early_stopping import EarlyStopping\nfrom transformers import (\n ALL_PRETRAINED_MODEL_ARCHIVE_MAP,\n AdamW,\n AutoConfig,\n AutoModel,\n AutoModelForPreTraining,\n AutoModelForQuestionAnswering,\n AutoModelForSequenceClassification,\n AutoModelForTokenClassification,\n AutoModelWithLMHead,\n AutoTokenizer,\n get_linear_schedule_with_warmup,\n)\nfrom transformers.modeling_auto import MODEL_MAPPING\n\nlogger = logging.getLogger(__name__)\n\nif os.environ.get(\"LIGHTNING_DEBUG\"):\n LEVEL = logging.DEBUG\nelse:\n LEVEL = logging.INFO\n\nlogging.basicConfig(\n format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', level=LEVEL)\n\nALL_MODELS = tuple(ALL_PRETRAINED_MODEL_ARCHIVE_MAP)\nMODEL_CLASSES = tuple(m.model_type for m in MODEL_MAPPING)\n\nMODEL_MODES = {\n \"base\": AutoModel,\n \"sequence-classification\": AutoModelForSequenceClassification,\n \"question-answering\": AutoModelForQuestionAnswering,\n \"pretraining\": AutoModelForPreTraining,\n \"token-classification\": AutoModelForTokenClassification,\n \"language-modeling\": AutoModelWithLMHead,\n}\n\n\ndef set_seed(args):\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n\n if args.n_gpu > 0:\n torch.cuda.manual_seed_all(args.seed)\n\n\nclass BaseTransformer(pl.LightningModule):\n def __init__(self, hparams, num_labels=None, mode=\"base\"):\n \"Initialize a model.\"\n\n super(BaseTransformer, self).__init__()\n self.hparams = hparams\n self.hparams.model_type = self.hparams.model_type.lower()\n config = AutoConfig.from_pretrained(\n self.hparams.config_name\n\n if self.hparams.config_name else self.hparams.model_name_or_path,\n **({\n \"num_labels\": num_labels\n } if num_labels is not None else {}),\n cache_dir=self.hparams.cache_dir\n\n if self.hparams.cache_dir else None,\n )\n tokenizer = AutoTokenizer.from_pretrained(\n self.hparams.tokenizer_name if self.hparams.tokenizer_name else\n self.hparams.model_name_or_path,\n do_lower_case=self.hparams.do_lower_case,\n cache_dir=self.hparams.cache_dir\n\n if self.hparams.cache_dir else None,\n )\n model = MODEL_MODES[mode].from_pretrained(\n self.hparams.model_name_or_path,\n from_tf=bool(\".ckpt\" in self.hparams.model_name_or_path),\n config=config,\n cache_dir=self.hparams.cache_dir\n\n if self.hparams.cache_dir else None,\n )\n self.config, self.tokenizer, self.model = config, tokenizer, model\n\n def is_logger(self):\n return self.trainer.proc_rank <= 0\n\n def configure_optimizers(self):\n \"Prepare optimizer and schedule (linear warmup and decay)\"\n\n model = self.model\n no_decay = [\"bias\", \"LayerNorm.weight\"]\n optimizer_grouped_parameters = [\n {\n \"params\": [\n p for n, p in model.named_parameters()\n\n if not any(nd in n for nd in no_decay)\n ],\n \"weight_decay\":\n self.hparams.weight_decay,\n },\n {\n \"params\": [\n p for n, p in model.named_parameters()\n\n if any(nd in n for nd in no_decay)\n ],\n \"weight_decay\":\n 0.0,\n },\n ]\n optimizer = AdamW(\n optimizer_grouped_parameters,\n lr=self.hparams.learning_rate,\n eps=self.hparams.adam_epsilon)\n self.opt = optimizer\n\n return [optimizer]\n\n def optimizer_step(self,\n epoch,\n batch_idx,\n optimizer,\n optimizer_idx,\n second_order_closure=None):\n\n if self.trainer.use_tpu:\n xm.optimizer_step(optimizer)\n else:\n optimizer.step()\n optimizer.zero_grad()\n self.lr_scheduler.step()\n\n def get_tqdm_dict(self):\n tqdm_dict = {\n \"loss\": \"{:.3f}\".format(self.trainer.avg_loss),\n \"lr\": self.lr_scheduler.get_last_lr()[-1]\n }\n\n return tqdm_dict\n\n def test_step(self, batch, batch_nb):\n return self.validation_step(batch, batch_nb)\n\n def test_end(self, outputs):\n return self.validation_end(outputs)\n\n def train_dataloader(self):\n train_batch_size = self.hparams.train_batch_size\n dataloader = self.load_dataset(\"train\", train_batch_size)\n\n t_total = ((len(dataloader.dataset)\n // (train_batch_size * max(1, self.hparams.n_gpu)))\n // self.hparams.gradient_accumulation_steps * float(\n self.hparams.num_train_epochs))\n scheduler = get_linear_schedule_with_warmup(\n self.opt,\n num_warmup_steps=self.hparams.warmup_steps,\n num_training_steps=t_total)\n self.lr_scheduler = scheduler\n\n return dataloader\n\n def val_dataloader(self):\n return self.load_dataset(\"dev\", self.hparams.eval_batch_size)\n\n def test_dataloader(self):\n return self.load_dataset(\"test\", self.hparams.eval_batch_size)\n\n def _feature_file(self, mode):\n return os.path.join(\n self.hparams.data_dir,\n \"cached_{}_{}_{}\".format(\n mode,\n list(filter(None,\n self.hparams.model_name_or_path.split(\"/\"))).pop(),\n str(self.hparams.max_seq_length),\n ),\n )\n\n @staticmethod\n def add_model_specific_args(parser, root_dir):\n parser.add_argument(\n \"--model_type\",\n default=None,\n type=str,\n required=True,\n help=\"Model type selected in the list: \"\n + \", \".join(MODEL_CLASSES),\n )\n parser.add_argument(\n \"--model_name_or_path\",\n default=None,\n type=str,\n required=True,\n help=\"Path to pre-trained model or shortcut name selected in the list: \"\n + \", \".join(ALL_MODELS),\n )\n parser.add_argument(\n \"--config_name\",\n default=\"\",\n type=str,\n help=\"Pretrained config name or path if not the same as model_name\"\n )\n parser.add_argument(\n \"--tokenizer_name\",\n default=\"\",\n type=str,\n help=\"Pretrained tokenizer name or path if not the same as model_name\",\n )\n parser.add_argument(\n \"--cache_dir\",\n default=\"\",\n type=str,\n help=\"Where do you want to store the pre-trained models downloaded from s3\",\n )\n parser.add_argument(\n \"--do_lower_case\",\n action=\"store_true\",\n help=\"Set this flag if you are using an uncased model.\")\n parser.add_argument(\n \"--learning_rate\",\n default=5e-5,\n type=float,\n help=\"The initial learning rate for Adam.\")\n parser.add_argument(\n \"--weight_decay\",\n default=0.0,\n type=float,\n help=\"Weight decay if we apply some.\")\n parser.add_argument(\n \"--adam_epsilon\",\n default=1e-8,\n type=float,\n help=\"Epsilon for Adam optimizer.\")\n parser.add_argument(\n \"--warmup_steps\",\n default=0,\n type=int,\n help=\"Linear warmup over warmup_steps.\")\n parser.add_argument(\n \"--num_train_epochs\",\n default=3,\n type=int,\n help=\"Total number of training epochs to perform.\")\n\n parser.add_argument(\"--train_batch_size\", default=32, type=int)\n parser.add_argument(\"--eval_batch_size\", default=32, type=int)\n\n\nclass LoggingCallback(pl.Callback):\n def on_validation_end(self, trainer, pl_module):\n logger.info(\"***** Validation results *****\")\n\n if pl_module.is_logger():\n metrics = trainer.callback_metrics\n # Log results\n\n for key in sorted(metrics):\n if key not in [\"log\", \"progress_bar\"]:\n logger.info(\"{} = {}\\n\".format(key, str(metrics[key])))\n\n def on_test_end(self, trainer, pl_module):\n logger.info(\"***** Test results *****\")\n\n if pl_module.is_logger():\n metrics = trainer.callback_metrics\n\n # Log and save results to file\n output_test_results_file = os.path.join(\n pl_module.hparams.output_dir, \"test_results.txt\")\n with open(output_test_results_file, \"w\") as writer:\n for key in sorted(metrics):\n if key not in [\"log\", \"progress_bar\"]:\n logger.info(\"{} = {}\\n\".format(key, str(metrics[key])))\n writer.write(\"{} = {}\\n\".format(\n key, str(metrics[key])))\n\n\ndef add_generic_args(parser, root_dir):\n parser.add_argument(\n \"--output_dir\",\n default=None,\n type=str,\n required=True,\n help=\"The output directory where the model predictions and checkpoints will be written.\",\n )\n\n parser.add_argument(\n \"--fp16\",\n action=\"store_true\",\n help=\"Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit\",\n )\n\n parser.add_argument(\n \"--fp16_opt_level\",\n type=str,\n default=\"O1\",\n help=\"For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3'].\"\n \"See details at https://nvidia.github.io/apex/amp.html\",\n )\n\n parser.add_argument(\"--n_gpu\", type=int, default=1)\n parser.add_argument(\"--n_tpu_cores\", type=int, default=0)\n parser.add_argument(\n \"--max_grad_norm\", default=1.0, type=float, help=\"Max gradient norm.\")\n parser.add_argument(\n \"--do_train\", action=\"store_true\", help=\"Whether to run training.\")\n parser.add_argument(\n \"--do_predict\",\n action=\"store_true\",\n help=\"Whether to run predictions on the test set.\")\n parser.add_argument(\n \"--gradient_accumulation_steps\",\n type=int,\n default=1,\n help=\"Number of updates steps to accumulate before performing a backward/update pass.\",\n )\n parser.add_argument('--early_stop_patience', default=0, type=int)\n\n parser.add_argument(\n \"--server_ip\", type=str, default=\"\", help=\"For distant debugging.\")\n parser.add_argument(\n \"--server_port\", type=str, default=\"\", help=\"For distant debugging.\")\n parser.add_argument(\n \"--seed\", type=int, default=42, help=\"random seed for initialization\")\n\n\ndef setup_trainer(args):\n # init model\n set_seed(args)\n\n # Setup distant debugging if needed\n\n if args.server_ip and args.server_port:\n # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script\n import ptvsd\n\n print(\"Waiting for debugger attach\")\n ptvsd.enable_attach(\n address=(args.server_ip, args.server_port), redirect_output=True)\n ptvsd.wait_for_attach()\n\n if os.path.exists(args.output_dir) and os.listdir(\n args.output_dir) and args.do_train:\n raise ValueError(\n \"Output directory ({}) already exists and is not empty.\".format(\n args.output_dir))\n\n checkpoint_callback = pl.callbacks.ModelCheckpoint(\n filepath=os.path.join(args.output_dir, '{epoch}'),\n monitor=\"val_loss\",\n mode=\"min\",\n verbose=True,\n save_top_k=1)\n early_stop_callback = EarlyStopping(\n monitor='val_loss',\n min_delta=0.00,\n patience=args.early_stop_patience,\n verbose=True,\n mode='min')\n # wandb logger\n wandb_logger = WandbLogger(project=\"bart-qa-to-nli\")\n train_params = dict(\n accumulate_grad_batches=args.gradient_accumulation_steps,\n gpus=args.n_gpu,\n max_epochs=args.num_train_epochs,\n early_stop_callback=early_stop_callback,\n gradient_clip_val=args.max_grad_norm,\n checkpoint_callback=checkpoint_callback,\n logger=wandb_logger,\n callbacks=[LoggingCallback()],\n val_check_interval=0.25,\n )\n\n if args.fp16:\n train_params[\"use_amp\"] = args.fp16\n train_params[\"amp_level\"] = args.fp16_opt_level\n\n if args.n_tpu_cores > 0:\n global xm\n import torch_xla.core.xla_model as xm\n\n train_params[\"num_tpu_cores\"] = args.n_tpu_cores\n train_params[\"gpus\"] = 0\n\n if args.n_gpu > 1:\n train_params[\"distributed_backend\"] = \"ddp\"\n\n trainer = pl.Trainer(**train_params)\n\n return trainer\n","sub_path":"examples/transformer_base.py","file_name":"transformer_base.py","file_ext":"py","file_size_in_byte":12978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"192874586","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom flask import Flask\nfrom flask import request\nfrom flask import render_template\nfrom time import time\nfrom mwclient import Site\nfrom requests import ConnectionError\nfrom mwtextextractor import get_body_text\n\nimport sqlite3\n\napp = Flask(__name__)\n\ndef error_404():\n return '404'\n response = render_template('404.html')\n response.status_code = 404\n return response\n\ndef read_status(fname):\n stat = open(fname).read()\n statspl = stat.split()\n\n if statspl[0] == 'running':\n stat = 'Updating now... started %d secs ago.' % (int(time()) - int(statspl[1])) \n elif statspl[0] == '0':\n stat = 'Last successful run: ' + ' '.join(statspl[2:]) + '. Runtime was ' + statspl[1] + ' seconds.'\n else:\n stat = 'Failed'\n return stat\n\n@app.route('/')\ndef show_index():\n return render_template('main.html',\n status_no=read_status('/data/project/ukbot/logs/no.status'),\n status_fi=read_status('/data/project/ukbot/logs/fi.status')\n )\n\n@app.route('//')\ndef show_uk_list(lang):\n if lang not in ['no', 'fi']:\n return error_404()\n sql = sqlite3.connect('/data/project/ukbot/storage/%s.db' % lang)\n cur = sql.cursor()\n konk = []\n points = []\n for row in cur.execute(u'SELECT C.name, U.user, U.points, T.summedPoints FROM (SELECT users.contest, users.user, MAX(users.points) usersPoints, SUM(users.points) summedPoints FROM users GROUP BY users.contest) as T JOIN users as U ON U.points=T.usersPoints JOIN contests as C on C.name=U.contest'):\n s = row[0].split()[-1]\n konk.append({'id': s, 'name': row[0], 'winner': {'name': row[1], 'points': row[2]}, 'sum': {'points': row[3]}})\n points.append('%s' % row[3])\n return render_template('uk.html',\n lang=lang,\n points=','.join(points),\n contests=konk\n )\n\n@app.route('//contest//')\ndef show_uk_contest_details(lang, week):\n if lang not in ['no', 'fi']:\n return error_404()\n sql = sqlite3.connect('/data/project/ukbot/storage/%s.db' % lang)\n cur = sql.cursor()\n konk = []\n cur.execute(u'SELECT name FROM contests WHERE name LIKE ?', ['%' + week])\n\n row = cur.fetchone()\n if row:\n name = row[0]\n users = []\n for row2 in cur.execute(u'select user, points, bytes, newpages from users where contest=? ORDER BY points DESC', [name]):\n users.append({ 'name': row2[0], 'points': row2[1], 'bytes': row2[2], 'newpages': row2[3]})\n return render_template('uk_contest_details.html',\n lang=lang, name=name, users=users)\n else:\n return error_404()\n\n@app.route('//user//')\ndef show_uk_user_details(lang, user):\n if lang not in ['no', 'fi']:\n return error_404()\n sql = sqlite3.connect('/data/project/ukbot/storage/%s.db' % lang)\n cur = sql.cursor()\n konk = []\n for row in cur.execute(u'SELECT U.contest, U.points, U.bytes, U.newpages, (SELECT COUNT(DISTINCT(users.points)) FROM users WHERE users.contest=U.contest AND users.points >= U.points) AS place, (SELECT COUNT(DISTINCT(points)) FROM users WHERE users.contest=U.contest) AS npart FROM users AS U WHERE U.user=?', [user]):\n s = row[0].split()[-1]\n konk.append({'id': s, 'name': row[0], 'points': row[1], 'bytes': row[2], 'newpages': row[3], 'pos': row[4], 'cnt': row[5] })\n\n return render_template('uk_user_details.html',\n lang=lang,\n name=user,\n contests=konk\n )\n\ndef validate(data):\n errors = []\n if len(data.get('lang', '')) < 2 or len(data.get('lang', '')) > 3:\n errors.append('invalid_lang')\n if len(data.get('page', '')) < 1:\n errors.append('no_page')\n if len(errors) != 0:\n return None, errors\n try:\n site = Site('{}.wikipedia.org'.format(data.get('lang')))\n except ConnectionError:\n return None, ['invalid_lang']\n page = site.pages[data.get('page')]\n if not page.exists:\n return None, ['invalid_page']\n return page, errors\n\n\n@app.route('/wordcount')\ndef show_wordcount():\n lang = request.args.get('lang', '')\n page = request.args.get('page', '')\n revision = request.args.get('revision', '')\n args = {'lang': lang, 'page': page, 'revision': revision}\n if lang == '' or page == '':\n return render_template('wordcount.html', **args)\n mwpage, errors = validate(request.args)\n if len(errors) != 0:\n return render_template('wordcount.html',\n errors=errors, **args)\n \n if revision == '':\n revision = mwpage.revision\n args['revision'] = revision\n \n rev = next(mwpage.revisions(revision, prop='ids|content', limit=1))\n txt = rev['*']\n body = get_body_text(txt)\n return render_template('wordcount.html',\n body=body,\n word_count=len(body.split()),\n **args\n )\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"src/webinterface/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"11979467","text":"from selenium import webdriver\nfrom selenium.webdriver import ActionChains\nimport pyautogui\n\ndriver = webdriver.Remote('http://134.132.239.40:9999',\n {\"debugConnectToRunningApp\":\"true\"})\n\ndef find_element(search):\n search_result = driver.find_element_by_name(search)\n return search_result\n\ndef get_xy(element1):\n xystring = element1.get_attribute(\"ClickablePoint\")\n xylist = xystring.split(\",\")\n x= int(xylist[0])\n y = int(xylist[1])\n return x, y\n\ndef drag_and_drop(element, ofsetX=0, ofsetY=0):\n pyautogui.mouseDown(get_xy(element)[0], get_xy(element)[1])\n pyautogui.dragTo(get_xy(element)[0]+ofsetX, get_xy(element)[1]+ofsetY)\n pyautogui.mouseUp()\n\ndrag_and_drop(find_element(\"depthbrick.bri, UPGRADE\"),500,300)","sub_path":"sendbox.py","file_name":"sendbox.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"282020098","text":"#Maylene Garcia\r\n#3/7/19\r\n#This program will check if two values have a sum greater, less than or equal to 10.\r\n\r\nnumber1 = int(input(\"What is the value of number 1?\"))\r\nnumber2 = int(input(\"What is the value of number 2?\"))\r\n\r\ndef numberCheck(n1, n2):\r\n if n1 + n2 == 10:\r\n print(\"Equal\")\r\n elif n1 + n2 > 10:\r\n print(\"Greater Than\")\r\n else:\r\n print(\"Less Than\")\r\n\r\n#numberCheck(number1, number2)\r\nprint(numberCheck(number1, number2))\r\n","sub_path":"sumto10.py","file_name":"sumto10.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"306187611","text":"import basilica\n\nimport basilica\nsentences = [\n \"This is a sentence!\",\n \"x\",\n \"I don't think this sentence is very similar at all...\",\n]\n\nwith basilica.Connection('a785c156-9338-9fcd-86c4-b563f1193d0f') as c:\n embeddings = list(c.embed_sentences(sentences))\n # print(list(embeddings)) # [[0.8556405305862427, ...], ...]\n\nfrom scipy import spatial\nprint(spatial.distance.cosine(embeddings[0], embeddings[1]))\nprint(spatial.distance.cosine(embeddings[0], embeddings[2]))\n","sub_path":"practice/basilica_train.py","file_name":"basilica_train.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"8465659","text":"# -*- coding: utf-8 -*-\n\n#\n# Board.py\n#\n# Copyright (c) 2015 Elektro-potkan \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\n\nfrom smbus import SMBus\nfrom RPi import GPIO\n\nfrom DSP_TDA7313 import DSP_TDA7313 as DSP\nfrom TUNER_BIG import TUNER_BIG as TUNER\n\nfrom time import sleep\nimport math\n\n\nclass Board:\n\t# Methods list\n\t# * __init__(gpio_en, gpio_stby, i2cbus = None, gpio_mode_bcm = False)\n\t# * power(on = None)\n\t# * reset()\n\t# * mute(on = None)\n\t\n\t# Constants list\n\t# * DSP - holding instance of DSP control class\n\t# * TUNER - holding instance of TUNER control class\n\t\n\t# Internal variables list\n\t# * _gpio_en - GPIO pin connected to the EN pin of the board\n\t# * _gpio_stby - GPIO pin connected to the ST-BY pin of the board\n\t# * _bus - holding instance of SMBus providing I2C bus for communication with chips on the board\n\t# * _state - dictionary holding current setup of the board\n\t\n\t\n\t#*\n\t#* Inits class\n\t#* @param int gpio_en - GPIO pin connected to the EN pin of board\n\t#* @param int gpio_stby - GPIO pin connected to the ST-BY pin of board\n\t#* @param int i2cbus - number of i2c bus the board is connected to\n\t#* @param bool gpio_mode_bcm - if the mode of GPIO module used for specifying GPIO pins is BCM (True) or BOARD (False)\n\t#*\n\tdef __init__(self, gpio_en, gpio_stby, i2cbus = None, gpio_mode_bcm = False):\n\t\tif i2cbus == None:\n\t\t\traise Exception()#TODO auto selection based on RPI board revision\n\t\t\n\t\tself._gpio_en = gpio_en\n\t\tself._gpio_stby = gpio_stby\n\t\t\n\t\tself._bus = SMBus(i2cbus)\n\t\tsleep(0.5)\n\t\t\n\t\tGPIO.setmode(GPIO.BCM if gpio_mode_bcm else GPIO.BOARD)\n\t\tGPIO.setup(self._gpio_en, GPIO.OUT, GPIO.LOW)\n\t\tGPIO.setup(self._gpio_stby, GPIO.OUT, GPIO.LOW)\n\t\t\n\t\tself._state = {\n\t\t\t\"power\": False,\n\t\t\t\"mute\": True\n\t\t}\n\t\t\n\t\tself.DSP = DSP(self)\n\t\tself.TUNER = TUNER(self)\n\t\t\n\t\t# init GPIOs\n\t\tself.power(False)\n\t\tself.mute(True)\n\t# end of method __init__\n\t\n\t#*\n\t#* Destructor\n\t#*\n\tdef __del__(self):\n\t\tself.power(False)\n\t\tGPIO.cleanup()\n\t# end of method __del__\n\t\n\t\n\t#*\n\t#* Turns on-board voltage regulators on or off\n\t#* @param bool on - True/False for setting the power state, None to return current state only\n\t#* @return bool - if the voltage regulators are on or off (software only)\n\t#*\n\tdef power(self, on = None):\n\t\tif on != None:\n\t\t\told_state = self._state[\"power\"]\n\t\t\t\n\t\t\tself._state[\"power\"] = bool(on)\n\t\t\t\n\t\t\tif not self._state[\"power\"]:\n\t\t\t\tself.mute(True)\n\t\t\t\tself.DSP.beforePowerOff()\n\t\t\t\tself.TUNER.beforePowerOff()\n\t\t\t\tsleep(0.2)\n\t\t\t\n\t\t\tGPIO.output(self._gpio_en, self._state[\"power\"])\n\t\t\t\n\t\t\tif not old_state and self._state[\"power\"]:\n\t\t\t\tsleep(0.5)\n\t\t\t\tself.DSP.afterPowerOn()\n\t\t\t\tself.TUNER.afterPowerOn()\n\t\t\n\t\treturn self._state[\"power\"]\n\t# end of method power\n\t\n\t#*\n\t#* Resets board by turning it off and then on after 2 seconds\n\t#*\n\tdef reset(self):\n\t\tself.power(False)\n\t\tsleep(2)\n\t\tself.power(True)\n\t# end of method reset\n\t\n\t#*\n\t#* Enables or disables amplifier stand-by mode\n\t#* @param bool on - True/False for setting the mute, None to return current state only\n\t#* @return bool - if the amplifier is muted or not (software only)\n\t#*\n\tdef mute(self, on = None):\n\t\tif on != None:\n\t\t\ton = bool(on)\n\t\t\t\n\t\t\tif self._state[\"power\"] or on:\n\t\t\t\tself._state[\"mute\"] = on\n\t\t\t\tGPIO.output(self._gpio_stby, not self._state[\"mute\"])\n\t\t\n\t\treturn self._state[\"mute\"]\n\t# end of method mute\n\t\n\t\n\t#*\n\t#* Send data over I2C if the Board is powered on\n\t#* @param int address - address byte\n\t#* @param tuple/list data - data bytes to be sent\n\t#*\n\tdef _i2c_write(self, address, data):\n\t\tif address < 0 or len(data) < 1:\n\t\t\treturn\n\t\t\n\t\tif not self._state[\"power\"]:# send data to board but only if it is powered\n\t\t\treturn\n\t\t\n\t\tif len(data) > 1:\n\t\t\tself._bus.write_i2c_block_data(address, data[0], data[1:])\n\t\telse:\n\t\t\tself._bus.write_byte(address, data[0])\n\t# end of method _i2c_write\n# end of class Board\n","sub_path":"Board.py","file_name":"Board.py","file_ext":"py","file_size_in_byte":4875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"269427415","text":"# Databricks notebook source\n# MAGIC %md\n# MAGIC \n# MAGIC # Databricks - Credit Scoring\n# MAGIC \n# MAGIC ## Introduction\n# MAGIC \n# MAGIC Banks play a crucial role in market economies. They decide who can get finance and on what terms and can make or break investment decisions. For markets and society to function, individuals and companies need access to credit. \n# MAGIC \n# MAGIC Credit scoring algorithms, which make a guess at the probability of default, are the method banks use to determine whether or not a loan should be granted. \n# MAGIC \n# MAGIC ## The problem\n# MAGIC \n# MAGIC Down below you will find a possible solution to the challenge described in [c/GiveMeSomeCredit](https://www.kaggle.com/c/GiveMeSomeCredit) where participants where required to improve on the state of the art in credit scoring, by predicting the probability that somebody will experience financial distress in the next two years. \n# MAGIC \n# MAGIC ## The data\n# MAGIC \n# MAGIC The training data contains the following variables:\n# MAGIC \n# MAGIC \n# MAGIC | **Variable Name** | **Description** | **Type** |\n# MAGIC |--------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------|------------|\n# MAGIC | SeriousDlqin2yrs | Person experienced 90 days past due delinquency or worse | *Y/N* |\n# MAGIC | RevolvingUtilizationOfUnsecuredLines | Total balance on credit cards and personal lines of credit except real estate and no installment debt like car loans divided by the sum of credit limits | percentage |\n# MAGIC | age | Age of borrower in years | integer |\n# MAGIC | NumberOfTime30-59DaysPastDueNotWorse | Number of times borrower has been 30-59 days past due but no worse in the last 2 years. | integer |\n# MAGIC | DebtRatio | Monthly debt payments, alimony,living costs divided by monthy gross income | percentage |\n# MAGIC | MonthlyIncome | Monthly income | real |\n# MAGIC | NumberOfOpenCreditLinesAndLoans | Number of Open loans (installment like car loan or mortgage) and Lines of credit (e.g. credit cards) | integer |\n# MAGIC | NumberOfTimes90DaysLate | Number of times borrower has been 90 days or more past due. | integer |\n# MAGIC | NumberRealEstateLoansOrLines | Number of mortgage and real estate loans including home equity lines of credit | integer |\n# MAGIC | NumberOfTime60-89DaysPastDueNotWorse | Number of times borrower has been 60-89 days past due but no worse in the last 2 years. | integer |\n# MAGIC | NumberOfDependents | Number of dependents in family excluding themselves (spouse, children etc.) | integer |\n# MAGIC \n# MAGIC The **SeriousDlqin2yrs** is the dependent variable of the dataset, or better named the **label**. This is a boolean value which details if a certain individual has experienced a deliquency of 90 days past due or worse in the last 2 years.\n# MAGIC \n# MAGIC You can get the training data from [here](https://github.com/dlawrences/GlobalAINightBucharest/blob/master/data/cs-training.csv).\n# MAGIC \n# MAGIC This dataset should be used for:\n# MAGIC - creating two smaller sets, one for the actual training (e.g. 80%) and one for testing (e.g. 20%)\n# MAGIC - during cross validation, if you want to do the validation on multiple different folds of data to manage better the bias and the variance\n# MAGIC \n# MAGIC The benchmark/real unseen data you could use to test your model predictions may be downloaded from [here](https://github.com/dlawrences/GlobalAINightBucharest/blob/master/data/cs-test.csv).\n# MAGIC \n# MAGIC ## The Data Science Process\n# MAGIC \n# MAGIC This is the outline of the process we'll be following in this workshop.\n# MAGIC \n# MAGIC ![Data Science Process](https://raw.githubusercontent.com/neaorin/PredictTheWorldCup/master/images/datascience_process.jpg)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Data import\n# MAGIC \n# MAGIC Before starting to do anything else, we need to import the data. First, let's download both datasets and store them in DBFS.\n\n# COMMAND ----------\n\nimport urllib.request\n\ntraining_data_url = \"https://raw.githubusercontent.com/dlawrences/GlobalAINightBucharest/master/data/cs-training.csv\"\ntraining_data_filename = \"cs_training.csv\"\n\ntest_data_url = \"https://raw.githubusercontent.com/dlawrences/GlobalAINightBucharest/master/data/cs-test.csv\"\ntest_data_filename = \"cs_test.csv\"\n\ndbfs_data_folder = \"dbfs/FileStore/data/\"\nproject_name = 'credit-scoring'\n\ndbfs_project_folder = dbfs_data_folder + project_name + \"/\"\n\n# Download files and move them to the final directory in DBFS\nurllib.request.urlretrieve(training_data_url, \"/tmp/\" + training_data_filename)\nurllib.request.urlretrieve(test_data_url, \"/tmp/\" + test_data_filename)\n\n# Create the project directory if it does not exist and move files to it\ndbutils.fs.mkdirs(dbfs_project_folder)\ndbutils.fs.mv(\"file:/tmp/\" + training_data_filename, dbfs_project_folder)\ndbutils.fs.mv(\"file:/tmp/\" + test_data_filename, dbfs_project_folder)\n\n# List the contents of the directory\ndbutils.fs.ls(dbfs_project_folder)\n\n# COMMAND ----------\n\nimport numpy as np # library for linear algebra and stuff\nimport pandas as pd # library for data processing, I/O on csvs etc\nimport matplotlib.pyplot as plt # library for plotting\nimport seaborn as sns # a library which is better for plotting\n\n# File location and type\nfile_location = dbfs_project_folder + training_data_filename\nfile_type = \"csv\"\n\n# CSV options\ninfer_schema = \"true\"\nfirst_row_is_header = \"true\"\ndelimiter = \",\"\n\n# The applied options are for CSV files. For other file types, these will be ignored.\ncreditSDF = spark.read.format(file_type) \\\n .option(\"inferSchema\", infer_schema) \\\n .option(\"header\", first_row_is_header) \\\n .option(\"sep\", delimiter) \\\n .load(file_location)\n\ndisplay(creditSDF)\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC \n# MAGIC Now that we've loaded the dataset, the first thing we're going to do is set aside a part of it - 25 to 30 percent is a usual percentage - and not touch it until it's time to test our models.\n\n# COMMAND ----------\n\ntemp_table_name = \"trainingSDF\"\n\n# Split the data into training and test sets (25% held out for testing)\n(trainingSDF, testingSDF) = creditSDF.randomSplit([0.75, 0.25], seed=1)\n\n# Make the dataframe available in the SQL context\ntrainingSDF.createOrReplaceTempView(temp_table_name)\n\n# COMMAND ----------\n\n# Sample out 10 rows of the dataset\ndisplay(trainingSDF.sample(False, 0.1, seed=0).limit(10))\n\n# COMMAND ----------\n\n# Inspect the schema\ntrainingSDF.printSchema()\n\n# COMMAND ----------\n\n# Check of the summary statistics of the features\ndisplay(trainingSDF.describe())\n\n# COMMAND ----------\n\n# highlight how many missing values we have for every feature\nfrom pyspark.sql.functions import lit, col\n\nrows = trainingSDF.count()\nsummary = trainingSDF.describe().filter(col(\"summary\") == \"count\")\ndisplay(summary.select(*((lit(rows)-col(c)).alias(c) for c in trainingSDF.columns)))\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Quick conclusions:\n# MAGIC - there are a lot of null values for **MonthlyIncome** and **NumberOfDependents**; we will analyse how to impute these next\n# MAGIC - the minimum value for the **age** variable is 0 and it presents an outlier/bad data; this will be imputed with the median\n# MAGIC - the maximum value of **329664** for the **DebtRatio** variable is rather weird given this variable is a mere percentage; from a modelling perspective, thus we will need to understand why there are such big values and decide what to do with them\n# MAGIC - the maximum value of **50708** for the **RevolvingUtilizationOfUnsecuredLines** variable is rather weird given this variable is a mere percentage; rom a modelling perspective, thus we will need to understand why there are such big values and decide what to do with them\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Exploratory Data Analysis & Data Cleaning\n# MAGIC \n# MAGIC We are going to take step by step most of the interesting columns that need visualizing and cleansing to be done.\n# MAGIC \n# MAGIC ### Target class - SeriousDlqin2yrs\n# MAGIC \n# MAGIC Let's understand the distribution of our target class (**SeriousDlqin2yrs**). This could very well influence the algorithm we will want to use to model the problem.\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC \n# MAGIC select SeriousDlqin2yrs, count(*) as TotalCount from trainingSDF group by SeriousDlqin2yrs\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC There seems to be a lot of **class imbalance** going on. Let's understand the positive event rate in our target class.\n\n# COMMAND ----------\n\nclass_0 = trainingSDF.filter(trainingSDF.SeriousDlqin2yrs == 0).count()\nclass_1 = trainingSDF.filter(trainingSDF.SeriousDlqin2yrs == 1).count()\n\nprint(\"Total number of observations with a class of 0: {}\".format(class_0))\nprint(\"Total number of observations with a class of 1: {}\".format(class_1))\nprint(\"Positive event rate: {} %\".format(class_1/(class_0+class_1) * 100))\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC A positive event rate of 6.6% is by no means ideal. Going through with this distribution for the target class may mean that the minorit class will be ignored by the algorithm we are going to use to model the problem, thus the model will be biased to customers which are not likely to default.\n# MAGIC \n# MAGIC A couple of ideas which we are going to take into consideration going further to go around this problem:\n# MAGIC - given we have a lot of training data (100k+ observations), we may actually considering resampling the dataset.\n# MAGIC - we are going to use an evaluation metric which compensates the imbalance between classes, e.g. **ROC AUC**\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### Age variable\n# MAGIC \n# MAGIC We are interested in knowing the distribution of the **age** variable. \n# MAGIC \n# MAGIC We are not looking for customers under the legal age of 18 years. If any, we will impute the age of these with the median of the column.\n\n# COMMAND ----------\n\nimport matplotlib.ticker as ticker\n\n# spark.sql does not have any histogram method, however the RDD api does\nage_histogram = trainingSDF.select('age').rdd.flatMap(lambda x: x).histogram(10)\n\nfig, ax = plt.subplots()\n\n# the computed histogram needs to be loaded in a pandas dataframe so we will be able to plot it using sns\nage_histogram_df = pd.DataFrame(\n list(zip(*age_histogram)), \n columns=['bin', 'frequency']\n)\n\nax = sns.barplot(x = \"bin\", y = \"frequency\", data = age_histogram_df)\n\nax.get_xaxis().set_major_formatter(ticker.FuncFormatter(lambda x, p: format(age_histogram_df.iloc[x]['bin'], '.1f')))\n\ndisplay(fig)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC It seems there may be customers under the legal age. Let's see how many.\n\n# COMMAND ----------\n\n# We can use the filter method to understand what are the observations for which the customers falls under the legal age.\ndisplay(trainingSDF.filter(trainingSDF.age < 18))\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Fortunately there is only one. Let's impute this value with the median.\n\n# COMMAND ----------\n\n# Import functions which will help us code an if statement\nfrom pyspark.sql import functions as F\n\ndef imputeAgeWithMedian(df, medianAge):\n\n # Update with the median for the rows where the age columnis equal to 0\n df = df.withColumn('age',\n F.when(\n F.col('age') == 0,\n medianAge\n ).otherwise(\n F.col('age')\n )\n )\n \n return df\n\n# Compute the median of the age variable\ntrainingMedianAge = np.median(trainingSDF.select('age').dropna().collect())\ntrainingSDF = imputeAgeWithMedian(trainingSDF, trainingMedianAge)\n\n# Check to see that the only row shown above has a new age value\ndisplay(trainingSDF.filter(trainingSDF.Idx == 65696))\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Finally, let's check the distribution of the age for each group, based on the values for the **SeriousDlqin2yrs** target variable.\n# MAGIC \n# MAGIC We're going to use a [box and whiskers plot](https://towardsdatascience.com/understanding-boxplots-5e2df7bcbd51?gi=9e6b6042f263) to better visualize the distribution.\n\n# COMMAND ----------\n\nfig, ax = plt.subplots()\n\nax = sns.boxplot(x=\"SeriousDlqin2yrs\", y=\"age\", data = trainingSDF.toPandas())\n\ndisplay(fig)\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC \n# MAGIC SELECT SeriousDlqin2yrs, age FROM trainingSDF\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Based on the cleaned age column, let's create an age banding column (bins) which might be better predictors to credit risk.\n# MAGIC \n# MAGIC For this example, we are going to use the bins included in this paper: [figure in paper](https://www.researchgate.net/figure/Percentage-of-default-risk-among-different-age-groups_fig2_268345909).\n# MAGIC \n# MAGIC > NOTE: For simplicity we are using a [Spark UDF](https://databricks.com/blog/2017/10/30/introducing-vectorized-udfs-for-pyspark.html) (User-defined function), although that may pose performance problems if the dataset is large. Consider using Scala for the production data preparation pipeline once the data scientist has defined and tested one that should be used in production.\n\n# COMMAND ----------\n\nfrom pyspark.sql.functions import udf\nfrom pyspark.sql.types import StringType\n\ndef bandingFunction(age):\n if (age < 25):\n return '18-25'\n elif (age >= 25 and age < 30): \n return '25-29'\n elif (age >= 30 and age < 35):\n return '30-34'\n elif (age >= 35 and age < 40):\n return '35-39'\n elif (age >= 40 and age < 45):\n return '40-44'\n elif (age >= 45 and age < 50):\n return '45-49'\n elif (age >= 50 and age < 55):\n return '50-54'\n elif (age >= 55 and age < 60):\n return '55-59'\n elif (age >= 60 and age < 65):\n return '60-64'\n elif (age >= 65 and age < 70):\n return '65-69'\n elif (age >= 70 and age < 75):\n return '70-74'\n elif (age >= 75): \n return '75+'\n else: \n return ''\n\nage_banding_udf = udf(bandingFunction, StringType() )\n\ndef addAgeBanding(df):\n df = df.withColumn('age_banding', age_banding_udf(df.age))\n return df.drop('age')\n\ntrainingSDF = addAgeBanding(trainingSDF)\n\ntrainingSDF.createOrReplaceTempView(temp_table_name)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Let's now visualize the distribution.\n# MAGIC \n# MAGIC NOTE: as an alternative to Python-based plotting libraries like *seaborn* or *pyplot* we can also use Databricks' built-in visualizations. Click on the Visualization button below the results of this cell to select a **Bar** chart.\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC select age_banding, count(*) as Counts from trainingSDF group by age_banding order by age_banding\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### MonthlyIncome variable\n# MAGIC \n# MAGIC In credit scoring, the income of the individual - besides the other debt that he is into - is of greater importance than other things when it comes to the final decision.\n# MAGIC \n# MAGIC Let's see how the distribution of this variable looks.\n\n# COMMAND ----------\n\nfig, ax = plt.subplots()\n\nax = sns.boxplot(x=\"SeriousDlqin2yrs\", y=\"MonthlyIncome\", data = trainingSDF.toPandas())\n\ndisplay(fig)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC Hmm, the chart isn't that useful, probably because we have some very large outliers (large *MonthlyIncome* values) skewing the plot. Let's try using a log scale for the y axis:\n\n# COMMAND ----------\n\nfig, ax = plt.subplots()\n\nsns.set(style=\"whitegrid\")\nax = sns.boxplot(x=\"SeriousDlqin2yrs\", y=\"MonthlyIncome\", data = trainingSDF.toPandas())\nax.set_yscale(\"log\")\n\ndisplay(fig)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC We can also display the quartile values of MonthlyIncome for each class, using Spark SQL.\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC \n# MAGIC SELECT SeriousDlqin2yrs, \n# MAGIC percentile(MonthlyIncome,0.25) AS Q1, \n# MAGIC percentile(MonthlyIncome,0.5) AS Q2_Median, \n# MAGIC percentile(MonthlyIncome,0.75) AS Q3\n# MAGIC FROM trainingSDF \n# MAGIC GROUP BY SeriousDlqin2yrs\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC That's better. One thing is certain - people which have gone through issues usually have a lower income. However, from the original summary statistics it also looked like the dataset contained really low values - like 5$ or less a month which is really odd.\n# MAGIC \n# MAGIC For our reference, let's view the [Characteristics of Minimum Wage Workers in the US: 2010](https://www.bls.gov/cps/minwage2010.htm). In this article, it is stated that the prevailing Federal minimum wage was $7.25 per hour.\n# MAGIC \n# MAGIC In this case, considering an individual would work on a full-time basis for 52 weeks straight in a year, that individual would earn **$7.25 X 40 hrs X 52 weeks** = **_$15,080_**.\n# MAGIC \n# MAGIC This translates to approximately **_$1,256_** a month. For a part-time worker, this would mean a wage of **_$628_**. For an individual working only a quarter of the total time, that would mean a wage of only **_$314_**.\n# MAGIC \n# MAGIC According to the [US Census Bureau, Current Population Survey 2016](https://en.wikipedia.org/wiki/Personal_income_in_the_United_States#cite_note-CPS_2015-2), 6.48% of people earned **_$2,500_** or less in a full year. This translates to only **_$208_** a month. Median personal income comes to about **_$31,099_** a year, which is about **_$2,592_** dollars a month.\n# MAGIC \n# MAGIC Given all this information, let's do some more exploratory data analysis to see where this odd **MonthlyIncome** needs patching a bit.\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Off the bat, there is weirdness in having NULL **MonthlyIncome** data, but being able to calculate **DebtRatio**.\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC select avg(DebtRatio), count(1) as Instances from trainingSDF where MonthlyIncome is null\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC It may be the case than whoever gathered this data have replaced **NULL** in this column to 1 to be able to calculate the **DebtRatio** using the data about the **TotalDebt** of the individual they had. This will be need to be treated this way:\n# MAGIC - impute the **NULL** values with the median of the dataset\n# MAGIC - recalculate the **DebtRatio** given we know that the **TotalDebt** is currently equal for those individuals to the value of the **DebtRatio**\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC A very low **MonthlyIncome** between $1 and $7 is again a bit suspicious (having worked under 1hr per month). Let's see a list of people with very small monthly incomes:\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC select MonthlyIncome, count(1) as Instances, avg(DebtRatio) from trainingSDF where MonthlyIncome between 1 and 100 group by MonthlyIncome order by 1\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Given the number of records where **MonthlyIncome** is equal to 1 is suspiciously high, we are going to impute it like we do for the **NULL** values. However, for the other values, there isn't just too much wrong data to draw any conclusions. If we extend the window up to 208:\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC select count(1) as Instances from trainingSDF where MonthlyIncome between 2 and 208\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC 100-odd rows is a low percentage of samples from the whole dataset, so for now we will be keeping these as they are.\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC That's quite a lot of information, so let's wrap up what we are going to do:\n# MAGIC \n# MAGIC For the specifics of this lab, we are going to consider that:\n# MAGIC - observations with a MonthlyIncome of 1 will be processed to get the median MonthlyIncome\n# MAGIC - observations with a MonthlyIncome of null will be processed to get the median MonthlyIncome\n# MAGIC \n# MAGIC Given the **DebtRatio** has been computed as the overall **Debt** divided by the **MonthlyIncome**, we are going to regenerate the initial debt first so we can use it later to recompute the **DebtRatio** based on the then cleaned **MonthlyIncome**.\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC First, we save the initial **Debt** so we are able to recompute the updated DebtRatio afterwards.\n\n# COMMAND ----------\n\nfrom pyspark.sql import functions as F\n\ndef addInitialDebtColumn(df):\n df = df.withColumn(\n 'initialDebt',\n F.when(\n (((F.col('MonthlyIncome') >= 0) & (F.col('MonthlyIncome') <= 1)) | (F.col('MonthlyIncome').isNull())),\n F.col('DebtRatio')\n ).otherwise(\n F.col('MonthlyIncome') * F.col('DebtRatio')\n )\n )\n \n return df\n \ntrainingSDF = addInitialDebtColumn(trainingSDF)\n\n# COMMAND ----------\n\ndisplay(trainingSDF)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC After the initial **Debt** has been saved, we are good to start imputing the **MonthlyIncome** column. \n# MAGIC If the actual value is <= $7 or missing, we manually impute using the **numpy**-calculated median.\n\n# COMMAND ----------\n\ndef imputeMonthlyIncome(df, incomeMedian):\n # Apply income median if the MonthlyIncome is <=7, or null\n \n df = df.withColumn('MonthlyIncome',\n F.when(\n (((F.col('MonthlyIncome') >= 0) & (F.col('MonthlyIncome') <= 7)) | (F.col('MonthlyIncome').isNull())),\n incomeMedian\n ).otherwise(\n F.col('MonthlyIncome')\n )\n )\n \n return df\n\ntrainingIncomeMedian = np.median(trainingSDF.select('MonthlyIncome').dropna().collect())\ntrainingSDF = imputeMonthlyIncome(trainingSDF, trainingIncomeMedian)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Now that the **MonthlyIncome** variable has been imputed, let's recalculate a more correct **DebtRatio** based on the initial **Debt** we have saved previously.\n\n# COMMAND ----------\n\ndef recalculateDebtRatio(df):\n df = df.withColumn(\n 'DebtRatio',\n df.initialDebt/df.MonthlyIncome\n )\n \n return df\n\ntrainingSDF = recalculateDebtRatio(trainingSDF)\n\ntrainingSDF.createOrReplaceTempView(temp_table_name)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Let's see how many values in this column are actually exceeding the threshold of **1** now.\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC select count(1) from trainingSDF where DebtRatio > 1\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Let's see how it looks from a distribution point of view.\n\n# COMMAND ----------\n\nfig, ax = plt.subplots()\n\nax = sns.boxplot(x=\"DebtRatio\", data = trainingSDF.toPandas())\nax.set_xscale(\"log\")\n\ndisplay(fig)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC It seems this values are going up into the hundreds. Individuals may exceed a **DebtRatio** of 1 whenever they are lending more than they are earning (and some people in difficult scenarios tend to do that).\n# MAGIC \n# MAGIC Let's default the higher values to a threshold of **1.5**.\n\n# COMMAND ----------\n\ndef defaultDebtRatioToThreshold(df):\n df = df.withColumn('DebtRatio',\n F.when(\n (F.col('DebtRatio') > 1.5),\n 1.5\n ).otherwise(\n F.col('DebtRatio')\n )\n )\n \n return df\n\ntrainingSDF = defaultDebtRatioToThreshold(trainingSDF)\n\ntrainingSDF.createOrReplaceTempView(temp_table_name)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### RevolvingUtilizationOfUnsecuredLines variable\n# MAGIC Let's understand how many values exceed 1 for this column and default them to this max value.\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC select count(1) from trainingSDF where RevolvingUtilizationOfUnsecuredLines > 1\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Some records have a **RevolvingUtilizationOfUnsecuredLines** value higher than 1. Given the total balance on credit cards and personal lines of credit is divided to the sum of credit limits, this should not exceed 1.\n# MAGIC \n# MAGIC Let's view the distribution of it and then default the weird records to this threshold.\n\n# COMMAND ----------\n\nfig, ax = plt.subplots()\n\nax = sns.boxplot(x=\"RevolvingUtilizationOfUnsecuredLines\", data = trainingSDF.toPandas())\nax.set_xscale(\"log\")\n\n\ndisplay(fig)\n\n# COMMAND ----------\n\ndef defaultRevolvingUtilizationToThreshold(df):\n df = df.withColumn('RevolvingUtilizationOfUnsecuredLines',\n F.when(\n (F.col('RevolvingUtilizationOfUnsecuredLines') > 1),\n 1\n ).otherwise(\n F.col('RevolvingUtilizationOfUnsecuredLines')\n )\n )\n \n return df\n\ntrainingSDF = defaultRevolvingUtilizationToThreshold(trainingSDF)\n\ntrainingSDF.createOrReplaceTempView(temp_table_name)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### NumberOfDependents variable\n# MAGIC \n# MAGIC Let's understand how many missing values this column has.\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC select count(1) from trainingSDF where NumberOfDependents is null\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC About 3000 missing values out of the total number of rows is not bad at all.\n# MAGIC \n# MAGIC Let's see how the distribution of this variable looks. We will understand the mode from it and will be able to impute using it.\n\n# COMMAND ----------\n\n# spark.sql does not have any histogram method, however the RDD api does\ndependents_histogram = trainingSDF.select('NumberOfDependents').rdd.flatMap(lambda x: x).histogram(10)\n\nfig, ax = plt.subplots()\n\n# the computed histogram needs to be loaded in a pandas dataframe so we will be able to plot it using sns\ndependents_histogram_df = pd.DataFrame(\n list(zip(*dependents_histogram)), \n columns=['bin', 'count']\n)\n\nax = sns.barplot(x = \"bin\", y = \"count\", data = dependents_histogram_df)\n\ndisplay(fig)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC We can tell from the barplot above that the mode (most frequent value) of this column is 0. Let's impute the missing values with it.\n\n# COMMAND ----------\n\ndef imputeNumberOfDependents(df):\n df = df.withColumn('NumberOfDependents',\n F.when(\n (F.col('NumberOfDependents').isNull()),\n 0\n ).otherwise(\n F.col('NumberOfDependents')\n )\n )\n\n return df\n\ntrainingSDF = imputeNumberOfDependents(trainingSDF)\n \ntrainingSDF.createOrReplaceTempView(temp_table_name)\n\n# COMMAND ----------\n\n# Check of the summary statistics of the features now\ndisplay(trainingSDF.describe())\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Building our first model\n# MAGIC \n# MAGIC For our first attempt at building a model we will use a relatively simple algorithm, Decision Trees.\n# MAGIC \n# MAGIC ![Decision Tree Example](https://miro.medium.com/max/792/1*XMId5sJqPtm8-RIwVVz2tg.png)\n# MAGIC \n# MAGIC [Click here](https://www.youtube.com/watch?v=7VeUPuFGJHk) for a straightforward video explanation of how Decision Trees work, and how we can build one using Gini Impurity.\n\n# COMMAND ----------\n\nfrom pyspark.ml import Pipeline\nfrom pyspark.ml.classification import DecisionTreeClassifier\nfrom pyspark.ml.feature import VectorAssembler, StringIndexer, MinMaxScaler\n\n# Index categorical features\ncategorical_indexer = StringIndexer(inputCol=\"age_banding\", outputCol=\"age_banding_indexed\")\n\n# assemble all features into a features vector\nfeature_assembler = VectorAssembler(\n inputCols=[\n 'RevolvingUtilizationOfUnsecuredLines',\n 'NumberOfTime30-59DaysPastDueNotWorse',\n 'NumberOfOpenCreditLinesAndLoans',\n 'NumberOfTimes90DaysLate',\n 'NumberRealEstateLoansOrLines',\n 'NumberOfTime60-89DaysPastDueNotWorse',\n 'NumberOfDependents',\n 'age_banding_indexed',\n 'initialDebt',\n 'DebtRatio',\n 'MonthlyIncome'],\n outputCol=\"features\")\n\n\n# Train a DecisionTree model.\ndecision_tree_classifier = DecisionTreeClassifier(labelCol=\"SeriousDlqin2yrs\", featuresCol=\"features\",\n impurity=\"gini\", maxDepth=5, seed=1)\n\n# Chain assembler and model in a Pipeline\ndtc_pipeline = Pipeline(stages=[categorical_indexer, feature_assembler, decision_tree_classifier])\n\n# Train model. \ndtc_model = dtc_pipeline.fit(trainingSDF)\n\nprint(dtc_model.stages[2])\n\n# COMMAND ----------\n\n#let's get a text-based representation of the tree\nprint(dtc_model.stages[2].toDebugString)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC # Testing the model\n# MAGIC \n# MAGIC We will now test the model by predicting on the test data. Once we obtain predictions, we use the predictions and the ground truth values from the test dataset to compute binary classification evaluation metrics.\n# MAGIC \n# MAGIC Before we can use the model, we need to apply to the test data the same transformations we did in the preprocessing stage.\n# MAGIC \n# MAGIC Notice that se are using statistical values like `trainingMedianAge` which were computed on the training data set. It's good practice to treat the test dataset as completely new information, and not use it in any way except actually testing our ML pipeline.\n\n# COMMAND ----------\n\ntestingSDF = imputeAgeWithMedian(testingSDF, trainingMedianAge)\ntestingSDF = addAgeBanding(testingSDF)\ntestingSDF = addInitialDebtColumn(testingSDF)\ntestingSDF = imputeMonthlyIncome(testingSDF, trainingIncomeMedian)\ntestingSDF = recalculateDebtRatio(testingSDF)\ntestingSDF = defaultDebtRatioToThreshold(testingSDF)\ntestingSDF = defaultRevolvingUtilizationToThreshold(testingSDF)\ntestingSDF = imputeNumberOfDependents(testingSDF)\n\n# Make the dataframe available in the SQL context\ntest_temp_table_name = \"testingSDF\"\n\n# Make the dataframe available in the SQL context\ntestingSDF.createOrReplaceTempView(test_temp_table_name)\n\ndisplay(testingSDF)\n\n# COMMAND ----------\n\n# Make predictions.\ndtc_predictions = dtc_model.transform(testingSDF)\n\n# Select example rows to display.\ndisplay(dtc_predictions.select(\"probability\", \"prediction\", \"SeriousDlqin2yrs\"))\n\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC First, we're going to calculate and display the [Confusion Matrix](https://en.wikipedia.org/wiki/Confusion_matrix) for our binary classifier.\n\n# COMMAND ----------\n\n# display the confusion matrix\nfrom sklearn.metrics import confusion_matrix\n\ndef plotConfusionMatrix(confusion_matrix):\n fig, ax = plt.subplots()\n plt.imshow(confusion_matrix, interpolation='nearest', cmap=plt.cm.Wistia)\n classNames = ['Negative','Positive']\n ax.set_title(f'Confusion Matrix')\n ax.set_ylabel('True label')\n ax.set_xlabel('Predicted label')\n tick_marks = np.arange(len(classNames))\n ax.set_xticks(tick_marks)\n ax.set_yticks(tick_marks)\n s = [['TN','FP'], ['FN', 'TP']]\n for i in range(2):\n for j in range(2):\n ax.text(j,i, str(s[i][j])+\" = \"+str(confusion_matrix[i][j]))\n display(fig)\n \n \ndtc_confusion_matrix = confusion_matrix(dtc_predictions.select(\"SeriousDlqin2yrs\").collect(), dtc_predictions.select(\"prediction\").collect())\nplotConfusionMatrix(dtc_confusion_matrix)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ###Precision and Recall\n# MAGIC \n# MAGIC ![Precision and Recall](https://upload.wikimedia.org/wikipedia/commons/thumb/2/26/Precisionrecall.svg/350px-Precisionrecall.svg.png)\n\n# COMMAND ----------\n\ntn, fp, fn, tp = dtc_confusion_matrix.ravel()\nprint(f\"Accuracy = (TP + TN) / (TP + FP + TN + FN) = {(tp+tn)/(tp+fp+tn+fn)}\")\nprint(f\"Precision = TP / (TP + FP) = {tp/(tp+fp)}\")\nprint(f\"Recall = TP / (TP + FN) = {tp/(tp+fn)}\")\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ### Sensitivity and Specificity, and the ROC Curve\n# MAGIC \n# MAGIC ![Sensitivity and specificity](https://upload.wikimedia.org/wikipedia/commons/thumb/e/e7/Sensitivity_and_specificity.svg/350px-Sensitivity_and_specificity.svg.png)\n\n# COMMAND ----------\n\n# plot the ROC curve\nfrom sklearn.metrics import roc_curve, auc\n\ndef plotROCCurve(predictions, show_thresholds=False):\n results = predictions.select(['probability', 'SeriousDlqin2yrs']).collect()\n y_score = [float(i[0][1]) for i in results]\n y_true = [float(i[1]) for i in results]\n\n fpr, tpr, thresholds = roc_curve(y_true, y_score, pos_label = 1)\n roc_auc = auc(fpr, tpr)\n\n fig, ax = plt.subplots()\n ax.plot(fpr, tpr, label='ROC curve (area = %0.4f)' % roc_auc)\n ax.plot([0, 1], [0, 1], 'k--')\n if show_thresholds:\n tr_idx = np.arange(385, len(thresholds), 700)\n for i in tr_idx:\n ax.plot(fpr[i], tpr[i], \"xr\")\n ax.annotate(xy=(fpr[i], tpr[i]), s=\"%0.3f\" % thresholds[i])\n ax.set_xlim([0.0, 1.0])\n ax.set_ylim([0.0, 1.0])\n ax.set_xlabel('False Positive Rate (1 - Specificity)')\n ax.set_ylabel('True Positive Rate (Sensitivity)')\n ax.set_title('Receiver operating characteristic')\n ax.legend(loc=\"lower right\")\n display(fig)\n\nplotROCCurve(dtc_predictions)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ## Gradient Boosted Trees\n# MAGIC \n# MAGIC Now we're going to try an ensemble model: [Gradient Boosted Trees](https://en.wikipedia.org/wiki/Gradient_boosting).\n# MAGIC \n# MAGIC ![GBT](http://uc-r.github.io/public/images/analytics/gbm/boosted-trees-process.png)\n# MAGIC \n# MAGIC [Click here](https://www.youtube.com/watch?v=3CC4N4z3GJc) for a nice visual explanation of how Gradient Boosting works.\n\n# COMMAND ----------\n\nfrom pyspark.ml.classification import GBTClassifier\n\n# scale features \nscaler = MinMaxScaler(inputCol=\"features\", outputCol=\"scaledFeatures\")\n\n# Train a Gradient-boosted tree classifier model.\ngbt_classifier = GBTClassifier(labelCol=\"SeriousDlqin2yrs\", featuresCol=\"features\",\n maxIter=35, seed=1)\n\n# Chain assembler and model in a Pipeline\ngbt_pipeline = Pipeline(stages=[categorical_indexer, feature_assembler, scaler, gbt_classifier])\n\n# Train model. \ngbt_model = gbt_pipeline.fit(trainingSDF)\n\nprint(gbt_model.stages[3])\n\n# COMMAND ----------\n\nprint(gbt_model.stages[3].toDebugString)\n\n# COMMAND ----------\n\n# Make predictions.\ngbt_predictions = gbt_model.transform(testingSDF)\n\n# Select example rows to display.\ndisplay(gbt_predictions.select(\"probability\", \"prediction\", \"SeriousDlqin2yrs\"))\n\n# COMMAND ----------\n\ngbt_confusion_matrix = confusion_matrix(gbt_predictions.select(\"SeriousDlqin2yrs\").collect(), gbt_predictions.select(\"prediction\").collect())\nplotConfusionMatrix(gbt_confusion_matrix)\n\n# COMMAND ----------\n\ntn, fp, fn, tp = gbt_confusion_matrix.ravel()\nprint(f\"Precision = TP / (TP + FP) = {tp/(tp+fp)}\")\nprint(f\"Recall = TP / (TP + FN) = {tp/(tp+fn)}\")\nprint(f\"Sensitivity = TP / (TP + FN) = {tp/(tp+fn)}\")\nprint(f\"Specificity = TN / (TN + FP) = {tn/(tn+fp)}\")\n\n# COMMAND ----------\n\nplotROCCurve(gbt_predictions)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### Selecting a better threshold for class separation\n\n# COMMAND ----------\n\nplotROCCurve(gbt_predictions, show_thresholds = True)\n\n# COMMAND ----------\n\n# select a different threshold for class separation, make predictions based on that threshold, and recalculate Precision, Recall, Sensitivity and Specificity.\nfrom pyspark.sql.types import FloatType\n\nget_positive_probability=udf(lambda v:float(v[1]),FloatType())\n\n\nselected_threshold = 0.11\npred_colname = f'prediction-threshold'\ngbt_predictions_threshold = gbt_predictions.withColumn(pred_colname, \n F.when(get_positive_probability('probability') <= selected_threshold,0)\n .otherwise(1))\n \ndisplay(gbt_predictions_threshold.select(\"probability\", \"prediction\", pred_colname, \"SeriousDlqin2yrs\")) \n\n# COMMAND ----------\n\ngbt_threshold_confusion_matrix = confusion_matrix(gbt_predictions_threshold.select(\"SeriousDlqin2yrs\").collect(), gbt_predictions_threshold.select(\"prediction-threshold\").collect())\nplotConfusionMatrix(gbt_threshold_confusion_matrix)\n\n# COMMAND ----------\n\ntn, fp, fn, tp = gbt_threshold_confusion_matrix.ravel()\n\nprint(f\"Precision = TP / (TP + FP) = {tp/(tp+fp)}\")\nprint(f\"Recall = TP / (TP + FN) = {tp/(tp+fn)}\")\n\nprint(f\"Sensitivity = TP / (TP + FN) = {tp/(tp+fn)}\")\nprint(f\"Specificity = TN / (TN + FP) = {tn/(tn+fp)}\")\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC ## Hyperparameter Tuning\n# MAGIC \n# MAGIC Until now we've built a Gradient Boosted classfier with just the default parameters (except `maxIter` which we set to 35).\n# MAGIC It would be useful to optimize the parameters for the algorithm (also called hyperparameters).\n# MAGIC \n# MAGIC [Hyperparameter optimization](https://en.wikipedia.org/wiki/Hyperparameter_optimization) or tuning is the problem of choosing a set of optimal hyperparameters for a learning algorithm. A hyperparameter is a parameter whose value is used to control the learning process. By contrast, the values of other parameters (typically node weights) are learned.\n# MAGIC \n# MAGIC We will combine Hyperparameter Tuning with [Cross-Validation](https://en.wikipedia.org/wiki/Cross-validation_(statistics)) on the training dataset, so we are able to even out the noise in the training data. It is mainly used in settings where the goal is prediction, and one wants to estimate how accurately a predictive model will perform in practice. \n# MAGIC \n# MAGIC ![HT and CV](https://cambridgecoding.files.wordpress.com/2016/03/gridsearch_cv.png)\n\n# COMMAND ----------\n\nprint(gbt_classifier.explainParams())\n\n# COMMAND ----------\n\nfrom pyspark.ml.tuning import ParamGridBuilder, CrossValidator\nfrom pyspark.ml.evaluation import BinaryClassificationEvaluator\n\n\nparamGrid = (ParamGridBuilder()\n .addGrid(gbt_classifier.maxDepth, [5, 8])\n .addGrid(gbt_classifier.maxIter, [25, 40])\n .addGrid(gbt_classifier.stepSize, [0.1, 0.2])\n .build())\n\n\nevaluator = BinaryClassificationEvaluator(\n rawPredictionCol=\"prediction\", labelCol=\"SeriousDlqin2yrs\", metricName=\"areaUnderROC\")\n\ncv = CrossValidator(estimator=gbt_pipeline, estimatorParamMaps=paramGrid, evaluator=evaluator, numFolds=3)\n\n# Train model. \ngbt_models_cv = cv.fit(trainingSDF)\n\n# COMMAND ----------\n\nbest_model = gbt_models_cv.bestModel.stages[3]\nprint(best_model.explainParams())\n\n# COMMAND ----------\n\n# Make predictions.\ngbt_cv_predictions = gbt_models_cv.transform(testingSDF)\n\n# Select example rows to display.\ndisplay(gbt_cv_predictions.select(\"probability\", \"prediction\", \"SeriousDlqin2yrs\"))\n\n# COMMAND ----------\n\nplotROCCurve(gbt_cv_predictions, show_thresholds = True)\n\n# COMMAND ----------\n\nselected_threshold = 0.11\npred_colname = f'prediction-threshold'\ngbt_cv_predictions_threshold = gbt_cv_predictions.withColumn(pred_colname, \n F.when(get_positive_probability('probability') < selected_threshold,0)\n .otherwise(1))\n \ndisplay(gbt_cv_predictions_threshold.select(\"probability\", \"prediction\", pred_colname, \"SeriousDlqin2yrs\")) \n\n# COMMAND ----------\n\ngbt_cv_threshold_confusion_matrix = confusion_matrix(gbt_cv_predictions_threshold.select(\"SeriousDlqin2yrs\").collect(), gbt_cv_predictions_threshold.select(\"prediction-threshold\").collect())\nplotConfusionMatrix(gbt_cv_threshold_confusion_matrix)\n\n# COMMAND ----------\n\ntn, fp, fn, tp = gbt_cv_threshold_confusion_matrix.ravel()\n\nprint(f\"Precision = TP / (TP + FP) = {tp/(tp+fp)}\")\nprint(f\"Recall = TP / (TP + FN) = {tp/(tp+fn)}\")\n\nprint(f\"Sensitivity = TP / (TP + FN) = {tp/(tp+fn)}\")\nprint(f\"Specificity = TN / (TN + FP) = {tn/(tn+fp)}\")\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ## Using Automated ML from Azure ML Service\n# MAGIC \n# MAGIC We are now going to use the [AutoML feature](https://docs.microsoft.com/en-us/azure/machine-learning/service/concept-automated-ml) from the Azure Machine Learning Service SDK.\n# MAGIC \n# MAGIC Automated machine learning, also referred to as automated ML, is the process of automating the time consuming, iterative tasks of machine learning model development. It allows data scientists, analysts, and developers to build ML models with high scale, efficiency, and productivity all while sustaining model quality. Automated ML is based on a breakthrough from our Microsoft Research division.\n# MAGIC \n# MAGIC Traditional machine learning model development is resource-intensive, requiring significant domain knowledge and time to produce and compare dozens of models. Apply automated ML when you want Azure Machine Learning to train and tune a model for you using the target metric you specify. The service then iterates through ML algorithms paired with feature selections, where each iteration produces a model with a training score. The higher the score, the better the model is considered to \"fit\" your data.\n# MAGIC \n# MAGIC \n# MAGIC We will provide the cleansed training data to Azure ML which will test multiple types of algorithms in order to maximize a certain evaluation criteria we define. As per the [initial challenge from kaggle](https://www.kaggle.com/c/GiveMeSomeCredit), the criteria of choice is AUC (Area Under Curve).\n# MAGIC \n# MAGIC The validation during training is done by using cross validation in 5 folds.\n# MAGIC \n# MAGIC After we are done, the best trained model will be evaluated against a separated dataset (the test dataset) in order to understand real _performance_.\n# MAGIC \n# MAGIC ### Training using AutoML\n# MAGIC \n# MAGIC In order to get things going, we first initialize our Workspace...\n\n# COMMAND ----------\n\nsubscription_id = \"6787a35f-386b-4845-91d1-695f24e0924b\" # the Azure subscription ID you are using\nazureml_resource_group = \"spark-ml-workshop-25\" #you should be owner or contributor\nazureml_workspace_name = \"azureml-lab-25\" #your Azure Machine Learning workspace name\n\nimport azureml.core\n\n# Check core SDK version number - based on build number of preview/master.\nprint(\"Azure ML SDK version:\", azureml.core.VERSION)\n\nfrom azureml.core import Workspace\n\nws = Workspace(workspace_name = azureml_workspace_name,\n subscription_id = subscription_id,\n resource_group = azureml_resource_group)\n\n# Persist the subscription id, resource group name, and workspace name in aml_config/config.json.\nws.write_config()\n\n# COMMAND ----------\n\nws = Workspace.from_config()\n\nprint('Workspace name: ' + ws.name, \n 'Azure region: ' + ws.location, \n 'Subscription id: ' + ws.subscription_id, \n 'Resource group: ' + ws.resource_group, sep = '\\n')\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC And then we make sure we have all the important libraries in place.\n\n# COMMAND ----------\n\nimport logging\nimport os\nimport random\nimport time\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib.pyplot import imshow\nimport numpy as np\nimport pandas as pd\n\nimport azureml.core\nfrom azureml.core.experiment import Experiment\nfrom azureml.core.workspace import Workspace\nfrom azureml.train.automl import AutoMLConfig\nfrom azureml.train.automl.run import AutoMLRun\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC We prepare the experiment properties which will be provided once we issue a training request.\n\n# COMMAND ----------\n\n# Get the last seven letters of the username which will be used to build up exp name\nimport re\n\nregexStr = r'^([^@]+)@[^@]+$'\nemailStr = dbutils.notebook.entry_point.getDbutils().notebook().getContext().tags().apply(\"user\")\nmatchobj = re.search(regexStr, emailStr)\nif not matchobj is None:\n if len(matchobj.group(1)) > 10:\n notebook_username = matchobj.group(1)[-10:]\n else:\n notebook_username = matchobj.group(1)\n \n print(notebook_username)\nelse:\n print(\"Did not match\")\n\n# COMMAND ----------\n\n# Choose a name for the experiment and specify the project folder.\nexperiment_base_name = 'automl-scoring-'\nexperiment_suffix_name = notebook_username.replace(\".\", \"\") + \"-\" + str(random.randint(1000, 9999))\n\nexperiment_name = experiment_base_name + experiment_suffix_name\nproject_folder = './globalainight_projects/automl-credit-scring'\n\nprint(experiment_name)\n\nexperiment = Experiment(ws, experiment_name)\n\noutput = {}\noutput['SDK version'] = azureml.core.VERSION\noutput['Subscription ID'] = ws.subscription_id\noutput['Workspace Name'] = ws.name\noutput['Resource Group'] = ws.resource_group\noutput['Location'] = ws.location\noutput['Project Directory'] = project_folder\noutput['Experiment Name'] = experiment.name\npd.set_option('display.max_colwidth', -1)\npd.DataFrame(data = output, index = ['']).T\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Enabling diagnostics to understand better what's going on.\n\n# COMMAND ----------\n\nfrom azureml.telemetry import set_diagnostics_collection\nset_diagnostics_collection(send_diagnostics = True)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC We save the cleansed training data to CSV files in the DBFS and then we load it separately in two dataflows:\n# MAGIC - **X_train**: contains **_only_** the training variables\n# MAGIC - **Y_train**: contains **_only_** the result\n\n# COMMAND ----------\n\n# prepare the data for AutoML\nimport azureml.dataprep as dataprep\n\ntraining_sdf = trainingSDF\ntraining_sdf = training_sdf.drop(\"Idx\", \"initialDebt\")\n\ntraining_sdf \\\n.drop(\"SeriousDlqin2yrs\") \\\n.toPandas() \\\n.to_csv(\"/dbfs/FileStore/tables/constant-scoring-training-vars.csv\")\n\ntraining_sdf \\\n.select(\"SeriousDlqin2yrs\") \\\n.toPandas() \\\n.to_csv(\"/dbfs/FileStore/tables/constant-scoring-training-res.csv\")\n\nX_train = dataprep.read_csv(path = \"/dbfs/FileStore/tables/constant-scoring-training-vars.csv\", separator = ',')\nX_train = X_train.drop_columns(\"Column1\")\n\nY_train = dataprep.read_csv(path = \"/dbfs/FileStore/tables/constant-scoring-training-res.csv\", separator = ',')\nY_train = Y_train.drop_columns(\"Column1\")\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC Checking to make sure we have data inside.\n\n# COMMAND ----------\n\nX_train.head(5)\n\n# COMMAND ----------\n\nY_train.head(5)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC AutoML in Azure may be configured by passing multiple properties through the [AutoML Config](https://docs.microsoft.com/en-us/python/api/azureml-train-automl/azureml.train.automl.automlconfig?view=azure-ml-py).\n# MAGIC \n# MAGIC We are interested in the following:\n# MAGIC \n# MAGIC |Property|Description|\n# MAGIC |-|-|\n# MAGIC |**task**|classification or regression|\n# MAGIC |**primary_metric**|This is the metric that you want to optimize. Classification supports the following primary metrics:
    accuracy
    AUC_weighted
    average_precision_score_weighted
    norm_macro_recall
    precision_score_weighted|\n# MAGIC |**primary_metric**|This is the metric that you want to optimize. Regression supports the following primary metrics:
    spearman_correlation
    normalized_root_mean_squared_error
    r2_score
    normalized_mean_absolute_error|\n# MAGIC |**iteration_timeout_minutes**|Time limit in minutes for each iteration.|\n# MAGIC |**iterations**|Number of iterations. In each iteration AutoML trains a specific pipeline with the data.|\n# MAGIC |**n_cross_validations**|Number of cross validation splits.|\n# MAGIC |**spark_context**|Spark Context object. for Databricks, use spark_context=sc|\n# MAGIC |**max_concurrent_iterations**|Maximum number of iterations to execute in parallel. This should be <= number of worker nodes in your Azure Databricks cluster.|\n# MAGIC |**X**|(sparse) array-like, shape = [n_samples, n_features]|\n# MAGIC |**y**|(sparse) array-like, shape = [n_samples, ], [n_samples, n_classes]
    Multi-class targets. An indicator matrix turns on multilabel classification. This should be an array of integers.|\n# MAGIC |**path**|Relative path to the project folder. AutoML stores configuration files for the experiment under this folder. You can specify a new empty folder.|\n# MAGIC |**preprocess**|set this to True to enable pre-processing of data eg. string to numeric using one-hot encoding|\n# MAGIC |**exit_score**|Target score for experiment. It is associated with the metric. eg. exit_score=0.995 will exit experiment after that|\n\n# COMMAND ----------\n\nautoml_config = AutoMLConfig(task = 'classification',\n debug_log = 'automl_errors.log',\n primary_metric = 'AUC_weighted',\n iteration_timeout_minutes = 5,\n iterations = 10,\n n_cross_validations = 5,\n max_concurrent_iterations = 1, \n verbosity = logging.INFO,\n spark_context=sc, #databricks/spark related\n X = X_train, \n y = Y_train,\n path = project_folder,\n preprocess = True,\n enable_voting_ensemble = False,\n enable_stack_ensemble = False)\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC We are now ready to submit a new run for our experiment.\n\n# COMMAND ----------\n\nlocal_run = experiment.submit(automl_config, show_output = True) # for higher runs please use show_output=False and use the below\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC And once the run is finished, we are able to retrieve the best model as per the metric we have configured.\n\n# COMMAND ----------\n\nbest_run, fitted_model = local_run.get_output()\nprint(best_run)\nprint(fitted_model)\n\n# COMMAND ----------\n\nprint(fitted_model.steps)\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC **Portal URL for Monitoring Runs**\n# MAGIC \n# MAGIC The following will provide a link to the web interface to explore individual run details and status.\n\n# COMMAND ----------\n\ndisplayHTML(\"
    Your experiment in Azure Portal: {}\".format(local_run.get_portal_url(), local_run.id))\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### Evaluating the best model from AutoML\n# MAGIC \n# MAGIC Now that we are done with training, we can move forward in evaluating how well this model will actually do on the test data.\n\n# COMMAND ----------\n\nautoml_X_test = testingSDF.drop(\"Idx\", \"initialDebt\",\"SeriousDlqin2yrs\")\nautoml_Y_test = testingSDF.select(\"SeriousDlqin2yrs\")\n\n# COMMAND ----------\n\nautoml_predictions_pd = fitted_model.predict_proba(automl_X_test.toPandas())\ntempdf = pd.concat([pd.DataFrame(automl_predictions_pd), automl_Y_test.toPandas()], axis=1)\nautoml_predictions = spark.createDataFrame(tempdf)\ndisplay(automl_predictions)\n\n# COMMAND ----------\n\ndef plotROCCurve2(predictions, show_thresholds=False):\n results = predictions.select(['1', 'SeriousDlqin2yrs']).collect()\n y_score = [float(i[0]) for i in results]\n y_true = [float(i[1]) for i in results]\n\n fpr, tpr, thresholds = roc_curve(y_true, y_score, pos_label = 1)\n roc_auc = auc(fpr, tpr)\n\n fig, ax = plt.subplots()\n ax.plot(fpr, tpr, label='ROC curve (area = %0.4f)' % roc_auc)\n ax.plot([0, 1], [0, 1], 'k--')\n if show_thresholds:\n tr_idx = np.arange(385, len(thresholds), 700)\n for i in tr_idx:\n ax.plot(fpr[i], tpr[i], \"xr\")\n ax.annotate(xy=(fpr[i], tpr[i]), s=\"%0.3f\" % thresholds[i])\n ax.set_xlim([0.0, 1.0])\n ax.set_ylim([0.0, 1.0])\n ax.set_xlabel('False Positive Rate (1 - Specificity)')\n ax.set_ylabel('True Positive Rate (Sensitivity)')\n ax.set_title('Receiver operating characteristic')\n ax.legend(loc=\"lower right\")\n display(fig)\n\nplotROCCurve2(automl_predictions, show_thresholds = True)\n\n# COMMAND ----------\n\nselected_threshold = 0.12\npred_colname = f'prediction-threshold'\nautoml_predictions_threshold = automl_predictions_SDF.withColumn(pred_colname, \n F.when(F.col('1') < selected_threshold, 0)\n .otherwise(1))\ndisplay(automl_predictions_threshold)\n\n# COMMAND ----------\n\nautoml_threshold_confusion_matrix = confusion_matrix(automl_predictions_threshold.select(\"SeriousDlqin2yrs\").collect(), automl_predictions_threshold.select(\"prediction-threshold\").collect())\nplotConfusionMatrix(automl_threshold_confusion_matrix)\n\n# COMMAND ----------\n\ntn, fp, fn, tp = automl_threshold_confusion_matrix.ravel()\n\nprint(f\"Precision = TP / (TP + FP) = {tp/(tp+fp)}\")\nprint(f\"Recall = TP / (TP + FN) = {tp/(tp+fn)}\")\n\nprint(f\"Sensitivity = TP / (TP + FN) = {tp/(tp+fn)}\")\nprint(f\"Specificity = TN / (TN + FP) = {tn/(tn+fp)}\")\n\n# COMMAND ----------\n\n\n","sub_path":"notebooks/Databricks - Credit Scoring.py","file_name":"Databricks - Credit Scoring.py","file_ext":"py","file_size_in_byte":54237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"97271347","text":"from . import rts2_wwwapi\nimport json\n\n\nclass filter_set:\n\n\n \"\"\"Class to simplify look up of filter by name and number\n \n\n uses the python [] operator to lookup filter number\n or name. If you give it the name it will return the \n number and vice versa. it also uses aliases for the\n lookup. RTS2 and the Galil like to use long names\n like \"Harris-U\" observers like short names like \"U\"\n either format is acceptable as long as the alias \n is in the dictionary below. \n \"\"\"\n\n # Filter Name Aliases. \n # The keyword is the name of the filter as told by \n # the galil and RTS2, the value in the dict is a tupple\n # of possible aliases for each filter\n # TODO read this from config\n alias = {\n \"Bessell-U\": (\"U\", 'bessell-u'),\n # \"Harris-U\": (\"U\"), \n \"Harris-R\": (\"R\", \"harris-r\"), \n \"Harris-V\": (\"V\",\"harris-v\" ), \n \"Arizona-I\": (\"I\",), \n \"Harris-B\": (\"B\",),\n \"Schott-8612\": (\"Schott\",),\n \"Open\": (\"Open\", \"open\", \"OPEN\", \"Clear\", \"CLEAR\", \"clear\") }\n\n\n def __init__( self, filters=None, prx=None ):\n \"\"\"I believe that filters and prx should always be None.\n That is to say, we will read the filter list from rts2_wwwapi\"\"\"\n\n if filters is None:\n if prx is None:\n\n self._filter_list = rts2_wwwapi.rts2comm().get_filters()\n\n elif type(filters) == list:\n self._filter_list = filters\n\n elif type(filters) == dict:\n raise TypeError(\"Filters are should not be a dict, it probably should be None\")\n # this assumes that the keywords of the dictionary are \n # the fitler names and the value is the filter number. \n\n\n #sort by filter number and reverse look up. \n # this doesn't work in python3\n #for key, value in sorted(filters.iteritems(), key=lambda (k,v): (v,k)):\n #self._filter_list.append( key )\n\n elif type(filters) == str or type(filters) == unicode:\n self._filter_list = str(filters).split()\n\n else:\n raise TypeError(\"Unexpected filter type {}, type must be string, unicode, list or dict\".format(type(filters)))\n\n\n def check_alias( self, alias ):\n\n for name, aliases in self.alias.items():\n if alias == name:\n return alias\n\n else:\n for al in aliases:\n if al == alias:\n return name\n\n # we didn't find the alias\n return None\n \n def __str__(self):\n return \"\"\n\n def __repr__(self):\n return self.__str__()\n\n def __getitem__(self, key):\n if type(key) == int:\n return self._filter_list[key]\n\n elif type(key) == str or type(key) == unicode:\n realname = self.check_alias(key)\n if realname is not None:\n return self._filter_list.index(realname)\n raise ValueError( \"cannot find filter {}\".format(key) )\n \n\n def __contains__(self, item):\n try:\n val=self.__getitem__(item)\n except ValueError:\n return False\n\n return True\n\n","sub_path":"rts2solib/big61filters.py","file_name":"big61filters.py","file_ext":"py","file_size_in_byte":3248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"224363739","text":"__author__ = 'Максим'\n# -*- coding: utf8 -*-\n\na = b'abc' # let convert string in a bytes sequences, after we can check what can do with it\nif a.isdigit():\n print(a[0])\nelse:\n print('none')\n\ndef tuple_creation():\n t = 1, 'asd', 'lol', False, (2,1j) # we've made a tuple - sequence of different objects contained in one\n print(t) # print the whole sequence\n\n print(t[0]) # call the exactly element you need\n\n u = 1, t, False # put one tuple inside another and add something else\n\n print(u[1][2])\n\n y = False, # make tuple of one element or y = tuple() - create empty tuple\n\ntuple_creation()\n\ndef list_creation():\n\n a = ['1',2,3,\"4\"] # list creation\n\n a[0] = 0 # as list is mutable we can change it from inside\n\n print(a[0])\n\n a[1] = [2,3,4] # put a list inside a list\n\n print(a[1])\nprint(\"-----\")\n\nlist_creation()\n\nprint(\"----\")\ndef bytes_array_creation():\n\n b = bytearray(b'ab') # creation of bytearray\n b.append(97) # add a symbol \"a\" (as it's number is 97) to the 'ab'\n\n print(b) # 'a,b,a'\n\n b[1] = 97\n\n print(b)\n\nbytes_array_creation()","sub_path":"untitled/introToPython/intro.py","file_name":"intro.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"88625585","text":"import calendar\nimport logging\nimport math\nimport os\nfrom datetime import date, timedelta\n\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom django.db.models.aggregates import Sum\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, get_object_or_404\n\n# Create your views here.\nfrom bck.backup_util import backup_db\nfrom mng.export import export_xls\nfrom mng.models import Apply, KV, Notice, ApplyFile\n\nlogger = logging.getLogger(__name__)\n\n\ndef index(request):\n context = {}\n return render(request, 'mng/index.html', context)\n\n\ndef apply(request):\n context = {}\n return render(request, 'mng/apply.html', context)\n\n\n# def view(request, year, month, day):\n# context = {'year': year, 'month': month, 'day': day}\n# return render(request, 'mng/view.html', context)\n\n\ndef faq(request):\n context = {}\n return render(request, 'mng/faq.html', context)\n\n\ndef download(request):\n docs = ApplyFile.objects.all()\n context = {'docs': docs}\n return render(request, 'mng/download.html', context)\n\n\ndef publish(request):\n context = {}\n return render(request, 'mng/publish.html', context)\n\n\ndef setting(request):\n settings = KV.objects\n zero_year = 2016\n zero_month = 2\n zero_day = 28\n desk_max = 20\n tent_max = 20\n umbrella_max = 15\n red_max = 5\n cloth_max = 5\n loud_max = 2\n sound_max = 1\n projector_max = 1\n\n if settings.count() <= 0:\n zero_year_set = KV(set_key='zero_year', set_value=zero_year)\n zero_year_set.save()\n zero_month_set = KV(set_key='zero_month', set_value=zero_month)\n zero_month_set.save()\n zero_day_set = KV(set_key='zero_day', set_value=zero_day)\n zero_day_set.save()\n desk_set = KV(set_key='desk_max', set_value=desk_max)\n desk_set.save()\n tent_set = KV(set_key='tent_max', set_value=tent_max)\n tent_set.save()\n red_set = KV(set_key='red_max', set_value=red_max)\n red_set.save()\n cloth_set = KV(set_key='cloth_max', set_value=cloth_max)\n cloth_set.save()\n umbrella_set = KV(set_key='umbrella_max', set_value=umbrella_max)\n umbrella_set.save()\n loud_set = KV(set_key='loud_max', set_value=loud_max)\n loud_set.save()\n sound_set = KV(set_key='sound_max', set_value=sound_max)\n sound_set.save()\n projector_set = KV(set_key='projector_max', set_value=projector_max)\n projector_set.save()\n settings = KV.objects\n\n zero_year = settings.filter(set_key='zero_year').first().set_value\n zero_month = settings.filter(set_key='zero_month').first().set_value\n zero_day = settings.filter(set_key='zero_day').first().set_value\n desk_max = settings.filter(set_key='desk_max').first().set_value\n tent_max = settings.filter(set_key='tent_max').first().set_value\n umbrella_max = settings.filter(set_key='umbrella_max').first().set_value\n red_max = settings.filter(set_key='red_max').first().set_value\n cloth_max = settings.filter(set_key='cloth_max').first().set_value\n loud_max = settings.filter(set_key='loud_max').first().set_value\n sound_max = settings.filter(set_key='sound_max').first().set_value\n projector_max = settings.filter(set_key='projector_max').first().set_value\n context = {\n 'zero_year': zero_year,\n 'zero_month': zero_month,\n 'zero_day': zero_day,\n 'desk_max': desk_max,\n 'tent_max': tent_max,\n 'umbrella_max': umbrella_max,\n 'red_max': red_max,\n 'cloth_max': cloth_max,\n 'loud_max': loud_max,\n 'sound_max': sound_max,\n 'projector_max': projector_max,\n }\n print(context)\n return render(request, \"mng/setting.html\", context)\n\n\ndef check_info(material_num, material_name, apply_dates):\n invalid_apply = []\n if material_num > 0:\n if material_name == 'projector':\n max_name = 'projector_max'\n else:\n max_name = material_name.replace('_num', '_max')\n material_max = KV.objects.filter(set_key=max_name).first().set_value\n for apply_date in apply_dates:\n cur_sum = Apply.objects.filter(rap__year=apply_date.year, rap__month=apply_date.month, rap__day=apply_date\n .day).aggregate(Sum(material_name))[material_name + '__sum']\n if cur_sum is None:\n cur_sum = 0\n if cur_sum + material_num > int(material_max):\n if material_name == 'desk_num':\n invalid_name = '桌子'\n elif material_name == 'tent_num':\n invalid_name = '帐篷'\n elif material_name == 'umbrella_num':\n invalid_name = '雨伞'\n elif material_name == 'red_num':\n invalid_name = '相机'\n elif material_name == 'cloth_num':\n invalid_name = '展架'\n elif material_name == 'loud_num':\n invalid_name = '麦克风'\n elif material_name == 'sound_num':\n invalid_name = '音响'\n elif material_name == 'projector':\n invalid_name = '投影仪'\n else:\n invalid_name = 'ERROR'\n invalid = [invalid_name, material_num, int(material_max) - cur_sum,\n str(apply_date.year) + '年' + str(apply_date.month) + '月' + str(apply_date.day) + '日']\n invalid_apply.append(invalid)\n return invalid_apply\n\n\ndef check_apply_info(desk_num, tent_num, umbrella_num, red_num, cloth_num, loud_num, sound_num, projector, apply_dates):\n invalid_applies = []\n invalid_applies.extend(check_info(desk_num, 'desk_num', apply_dates))\n invalid_applies.extend(check_info(tent_num, 'tent_num', apply_dates))\n invalid_applies.extend(check_info(umbrella_num, 'umbrella_num', apply_dates))\n invalid_applies.extend(check_info(red_num, 'red_num', apply_dates))\n invalid_applies.extend(check_info(cloth_num, 'cloth_num', apply_dates))\n invalid_applies.extend(check_info(loud_num, 'loud_num', apply_dates))\n invalid_applies.extend(check_info(sound_num, 'sound_num', apply_dates))\n invalid_applies.extend(check_info(projector, 'projector', apply_dates))\n return invalid_applies\n\n\ndef save_apply(request):\n act_name = request.POST['act_name']\n applicant = request.POST['applicant']\n apply_org = request.POST['apply_org']\n tel = request.POST['tel']\n assistant = request.POST['assistant']\n\n chair_num = request.POST['chair_num']\n desk_num = request.POST['desk_num']\n tent_num = request.POST['tent_num']\n umbrella_num = request.POST['umbrella_num']\n red_num = request.POST['red_num']\n cloth_num = request.POST['cloth_num']\n loud_num = request.POST['loud_num']\n sound_num = request.POST['sound_num']\n projector = request.POST['projector']\n\n start_year = request.POST['start_year']\n start_month = request.POST['start_month']\n start_day = request.POST['start_day']\n\n end_year = request.POST['end_year']\n end_month = request.POST['end_month']\n end_day = request.POST['end_day']\n\n start_week = request.POST['start_week']\n end_week = request.POST['end_week']\n week_num = request.POST['week_num']\n\n param_size = len(request.POST)\n li_count = math.floor((param_size - 24) / 3)\n apply_dates = []\n invalid_li_count = 0\n\n for i in range(li_count):\n if request.POST['li_year_%d' % i] == '' or request.POST['li_month_%d' % i] == '' \\\n or request.POST['li_day_%d' % i] == '':\n invalid_li_count += 1\n continue\n apply_dates.append(date(int(request.POST['li_year_%d' % i]), int(request.POST['li_month_%d' % i]),\n int(request.POST['li_day_%d' % i])))\n li_count -= invalid_li_count\n\n if start_year != '' and start_month != '':\n start_date = date(int(start_year), int(start_month), int(start_day))\n end_date = date(int(end_year), int(end_month), int(end_day))\n\n for i in range((end_date - start_date).days + 1):\n cur_date = start_date + timedelta(days=i)\n apply_dates.append(cur_date)\n\n zero_week_year = int(KV.objects.filter(set_key='zero_year').first().set_value)\n zero_week_month = int(KV.objects.filter(set_key='zero_month').first().set_value)\n zero_week_day = int(KV.objects.filter(set_key='zero_day').first().set_value)\n if start_week != '':\n start_week = int(start_week)\n end_week = int(end_week)\n week_num = int(week_num)\n for i in range(end_week - start_week + 1):\n cur_date = date(zero_week_year, zero_week_month, zero_week_day) \\\n + timedelta(weeks=start_week + i - 1, days=week_num - 1)\n apply_dates.append(cur_date)\n\n invalid_applies = check_apply_info(int(desk_num), int(tent_num), int(umbrella_num),\n int(red_num), int(cloth_num), int(loud_num),\n int(sound_num), int(projector), apply_dates)\n if len(invalid_applies) <= 0:\n apply_rcd = Apply(act_name=act_name, applicant=applicant, apply_org=apply_org, tel=tel, assistant=assistant,\n char_num=chair_num, desk_num=desk_num, tent_num=tent_num, umbrella_num=umbrella_num,\n red_num=red_num, cloth_num=cloth_num, loud_num=loud_num, sound_num=sound_num,\n projector=projector)\n apply_rcd.save()\n for i in range(len(apply_dates)):\n apply_rcd.rap.create(year=apply_dates[i].year, month=apply_dates[i].month, day=apply_dates[i].day)\n\n return apply_success(request, apply_rcd.id)\n else:\n return render(request, 'mng/apply_failed.html', {'fails': invalid_applies})\n\n\ndef save_modify(request, apply_id):\n act_name = request.POST['act_name']\n applicant = request.POST['applicant']\n apply_org = request.POST['apply_org']\n tel = request.POST['tel']\n assistant = request.POST['assistant']\n\n chair_num = request.POST['chair_num']\n desk_num = request.POST['desk_num']\n tent_num = request.POST['tent_num']\n umbrella_num = request.POST['umbrella_num']\n red_num = request.POST['red_num']\n cloth_num = request.POST['cloth_num']\n loud_num = request.POST['loud_num']\n sound_num = request.POST['sound_num']\n projector = request.POST['projector']\n\n param_size = len(request.POST)\n li_count = math.floor((param_size - 15) / 3)\n apply_dates = []\n invalid_li_count = 0\n\n for i in range(li_count):\n if request.POST['li_year_%d' % i] == '' or request.POST['li_month_%d' % i] == '' \\\n or request.POST['li_day_%d' % i] == '':\n invalid_li_count += 1\n continue\n apply_dates.append(date(int(request.POST['li_year_%d' % i]), int(request.POST['li_month_%d' % i]),\n int(request.POST['li_day_%d' % i])))\n li_count -= invalid_li_count\n\n apply_rcd = get_object_or_404(Apply, pk=apply_id)\n invalid_applies = check_apply_info(int(desk_num) - int(apply_rcd.desk_num), int(tent_num) - int(apply_rcd.tent_num),\n int(umbrella_num) - int(apply_rcd.umbrella_num),\n int(red_num) - int(apply_rcd.red_num), int(cloth_num) - int(apply_rcd.cloth_num),\n int(loud_num) - int(apply_rcd.loud_num),\n int(sound_num) - int(apply_rcd.sound_num),\n int(projector) - int(apply_rcd.projector), apply_dates)\n if len(invalid_applies) <= 0:\n apply_rcd.act_name = act_name\n apply_rcd.applicant = applicant\n apply_rcd.tel = tel\n apply_rcd.apply_org = apply_org\n apply_rcd.assistant = assistant\n apply_rcd.char_num = chair_num\n apply_rcd.desk_num = desk_num\n apply_rcd.tent_num = tent_num\n apply_rcd.umbrella_num = umbrella_num\n apply_rcd.red_num = red_num\n apply_rcd.cloth_num = cloth_num\n apply_rcd.loud_num = loud_num\n apply_rcd.sound_num = sound_num\n apply_rcd.projector = projector\n apply_rcd.rap.all().delete()\n for i in range(len(apply_dates)):\n apply_rcd.rap.create(year=apply_dates[i].year, month=apply_dates[i].month, day=apply_dates[i].day)\n apply_rcd.save()\n\n return apply_success(request, apply_rcd.id)\n else:\n return render(request, 'mng/apply_failed.html', {'fails': invalid_applies})\n\n\ndef save_notice(request):\n notice_content = request.POST['content']\n notice = Notice(content=notice_content)\n notice.save()\n\n return HttpResponse(\"\")\n\n\ndef remove_notice(request, notice_id):\n notice = get_object_or_404(Notice, pk=notice_id)\n notice.delete()\n return get_notice(request, 1)\n\n\ndef modify_notice(request, notice_id):\n content = request.POST['content']\n Notice.objects.filter(pk=notice_id).update(content=content)\n return get_notice(request, 1)\n\n\ndef get_notice(request, page_num):\n notices = Notice.objects.order_by(\"-id\")\n if notices.count() <= 0:\n return HttpResponse(\"暂时没有通知\")\n limit = 5\n paginator = Paginator(notices, limit)\n page = page_num\n try:\n notice_pages = paginator.page(page) # 获取某页对应的记录\n except PageNotAnInteger: # 如果页码不是个整数\n notice_pages = paginator.page(1) # 取第一页的记录\n except EmptyPage: # 如果页码太大,没有相应的记录\n notice_pages = paginator.page(paginator.num_pages) # 取最后一页的记录\n\n return render(request, 'mng/notice.html', {'notice_pages': notice_pages})\n\n\ndef apply_success(request, apply_id):\n return render(request, 'mng/apply_success.html', {'apply_id': apply_id})\n\n\ndef apply_modify(request, apply_id):\n apply_rcd = get_object_or_404(Apply, pk=apply_id)\n return render(request, 'mng/apply_modify.html', {'apply': apply_rcd})\n\n\ndef apply_remove(request, apply_id):\n apply_rcd = get_object_or_404(Apply, pk=apply_id)\n apply_rcd.delete()\n today = date.today()\n return HttpResponse(\"\")\n\n\ndef save_setting(request):\n zero_year = request.POST['zero_year']\n zero_month = request.POST['zero_month']\n zero_day = request.POST['zero_day']\n desk_max = request.POST['desk_max']\n tent_max = request.POST['tent_max']\n umbrella_max = request.POST['umbrella_max']\n red_max = request.POST['red_max']\n cloth_max = request.POST['cloth_max']\n loud_max = request.POST['loud_max']\n sound_max = request.POST['sound_max']\n projector_max = request.POST['projector_max']\n\n KV.objects.filter(set_key='zero_year').update(set_value=zero_year)\n KV.objects.filter(set_key='zero_month').update(set_value=zero_month)\n KV.objects.filter(set_key='zero_day').update(set_value=zero_day)\n KV.objects.filter(set_key='desk_max').update(set_value=desk_max)\n KV.objects.filter(set_key='tent_max').update(set_value=tent_max)\n KV.objects.filter(set_key='umbrella_max').update(set_value=umbrella_max)\n KV.objects.filter(set_key='red_max').update(set_value=red_max)\n KV.objects.filter(set_key='cloth_max').update(set_value=cloth_max)\n KV.objects.filter(set_key='loud_max').update(set_value=loud_max)\n KV.objects.filter(set_key='sound_max').update(set_value=sound_max)\n KV.objects.filter(set_key='projector_max').update(set_value=projector_max)\n\n return setting(request)\n\n\ndef gen_calendar(year, month):\n month_first = date(year, month, 1)\n calendar_first = month_first - timedelta(days=month_first.weekday())\n calendar_dates = []\n\n for i in range(6):\n week_dates = []\n for j in range(7):\n week_date = calendar_first + timedelta(days=j + i * 7)\n date_items = [week_date.year, week_date.month, week_date.day]\n week_dates.append(date_items)\n\n calendar_dates.append(week_dates)\n\n return calendar_dates\n\n\ndef add_months(source_date, months):\n month = int(source_date.month) - 1 + months\n year = int(source_date.year + month / 12)\n month = month % 12 + 1\n day = min(source_date.day, calendar.monthrange(year, month)[1])\n return date(year, month, day)\n\n\ndef view(request, year, month, day):\n applies = Apply.objects.filter(rap__year=year, rap__month=month, rap__day=day)\n chair_left = '不限'\n chair_sum = Apply.objects.filter(rap__year=year, rap__month=month, rap__day=day) \\\n .aggregate(Sum('char_num'))['char_num__sum']\n if chair_sum is None:\n chair_sum = 0\n desk_sum = Apply.objects.filter(rap__year=year, rap__month=month, rap__day=day) \\\n .aggregate(Sum('desk_num'))['desk_num__sum']\n if desk_sum is None:\n desk_sum = 0\n desk_sum = int(desk_sum)\n desk_max = int(KV.objects.filter(set_key='desk_max').first().set_value)\n desk_left = desk_max - desk_sum\n\n tent_sum = Apply.objects.filter(rap__year=year, rap__month=month, rap__day=day) \\\n .aggregate(Sum('tent_num'))['tent_num__sum']\n if tent_sum is None:\n tent_sum = 0\n tent_sum = tent_sum\n tent_max = int(KV.objects.filter(set_key='tent_max').first().set_value)\n tent_left = tent_max - tent_sum\n\n umbrella_sum = Apply.objects.filter(rap__year=year, rap__month=month, rap__day=day) \\\n .aggregate(Sum('umbrella_num'))['umbrella_num__sum']\n if umbrella_sum is None:\n umbrella_sum = 0\n umbrella_sum = int(umbrella_sum)\n umbrella_max = int(KV.objects.filter(set_key='umbrella_max').first().set_value)\n umbrella_left = umbrella_max - umbrella_sum\n\n red_sum = Apply.objects.filter(rap__year=year, rap__month=month, rap__day=day) \\\n .aggregate(Sum('red_num'))['red_num__sum']\n if red_sum is None:\n red_sum = 0\n red_sum = int(red_sum)\n red_max = int(KV.objects.filter(set_key='red_max').first().set_value)\n red_left = red_max - red_sum\n\n cloth_sum = Apply.objects.filter(rap__year=year, rap__month=month, rap__day=day) \\\n .aggregate(Sum('cloth_num'))['cloth_num__sum']\n if cloth_sum is None:\n cloth_sum = 0\n cloth_sum = int(cloth_sum)\n cloth_max = int(KV.objects.filter(set_key='cloth_max').first().set_value)\n cloth_left = cloth_max - cloth_sum\n\n loud_sum = Apply.objects.filter(rap__year=year, rap__month=month, rap__day=day) \\\n .aggregate(Sum('loud_num'))['loud_num__sum']\n if loud_sum is None:\n loud_sum = 0\n loud_sum = int(loud_sum)\n loud_max = int(KV.objects.filter(set_key='loud_max').first().set_value)\n loud_left = loud_max - loud_sum\n\n sound_sum = Apply.objects.filter(rap__year=year, rap__month=month, rap__day=day) \\\n .aggregate(Sum('sound_num'))['sound_num__sum']\n if sound_sum is None:\n sound_sum = 0\n sound_sum = int(sound_sum)\n sound_max = int(KV.objects.filter(set_key='sound_max').first().set_value)\n sound_left = sound_max - sound_sum\n\n projector_sum = Apply.objects.filter(rap__year=year, rap__month=month, rap__day=day) \\\n .aggregate(Sum('projector'))['projector__sum']\n if projector_sum is None:\n projector_sum = 0\n projector_sum = int(projector_sum)\n projector_max = int(KV.objects.filter(set_key='projector_max').first().set_value)\n projector_left = projector_max - projector_sum\n\n previous_month_date = add_months(date(int(year), int(month), int(day)), -1)\n next_month_date = add_months(date(int(year), int(month), int(day)), 1)\n context = {'cur_year': year, 'cur_month': month, 'cur_day': day,\n 'dates': gen_calendar(int(year), int(month)),\n 'applies': applies, 'apply_cnt': len(applies),\n 'pre_year': previous_month_date.year, 'pre_month': previous_month_date.month,\n 'next_year': next_month_date.year, 'next_month': next_month_date.month,\n 'chair_sum': chair_sum, 'chair_left': chair_left,\n 'desk_sum': desk_sum, 'desk_left': desk_left,\n 'tent_sum': tent_sum, 'tent_left': tent_left,\n 'umbrella_sum': umbrella_sum, 'umbrella_left': umbrella_left,\n 'red_sum': red_sum, 'red_left': red_left,\n 'cloth_sum': cloth_sum, 'cloth_left': cloth_left,\n 'loud_sum': loud_sum, 'loud_left': loud_left,\n 'sound_sum': sound_sum, 'sound_left': sound_left,\n 'project_sum': projector_sum, 'projector_left': projector_left\n }\n return render(request, 'mng/view.html', context)\n\n\ndef backup(request):\n backup_db()\n return HttpResponse(\"success\")\n\n\ndef export(request):\n start_year = int(request.POST['start_year'])\n start_month = int(request.POST['start_month'])\n start_day = int(request.POST['start_day'])\n\n end_year = int(request.POST['end_year'])\n end_month = int(request.POST['end_month'])\n end_day = int(request.POST['end_day'])\n\n return export_xls(date(start_year, start_month, start_day), date(end_year, end_month, end_day))\n\n\ndef export_html(request):\n return render(request, 'mng/export.html', {})\n\n\ndef upload(request):\n name = request.POST['name']\n path = '../../static/doc/%s' % name\n\n f = request.FILES['file']\n with open(path.replace('../..', '../mng/'), 'wb+') as destination:\n for chunk in f.chunks():\n destination.write(chunk)\n\n docs = ApplyFile.objects.all()\n\n doc = ApplyFile(name=name, path=path)\n doc.save()\n return render(request, 'mng/download.html', {'docs': docs})\n\n\ndef rm_doc(request, doc_id):\n doc = get_object_or_404(ApplyFile, pk=doc_id)\n path = doc.path\n print(os.path.abspath('.'))\n os.remove((path.replace('../..', '../mng/')))\n doc.delete()\n docs = ApplyFile.objects.all()\n return render(request, 'mng/download.html', {'docs': docs})\n","sub_path":"mng/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":22124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"558134904","text":"\"\"\"first_login\n\nRevision ID: 9216d150be37\nRevises: bc66587fd935\nCreate Date: 2021-01-16 04:49:37.731725\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '9216d150be37'\ndown_revision = 'bc66587fd935'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('User', sa.Column('first_login', sa.DateTime(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('User', 'first_login')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/9216d150be37_first_login.py","file_name":"9216d150be37_first_login.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"545224522","text":"# coding: utf-8\n\n\"\"\"\n Cisco Firepower Management Center Open API Specification\n\n **Specifies the REST URLs and methods supported in the Cisco Firepower Management Center API. Refer to the version specific [REST API Quick Start Guide](https://www.cisco.com/c/en/us/support/security/defense-center/products-programming-reference-guides-list.html) for additional information.** # noqa: E501\n\n OpenAPI spec version: 1.0.0\n Contact: tac@cisco.com\n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass PrefilterHitCount(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'metadata': 'HitCountMetadata',\n 'last_fetch_time_stamp': 'str',\n 'hit_count': 'int',\n 'first_hit_time_stamp': 'str',\n 'rule': 'IPolicyModel',\n 'last_hit_time_stamp': 'str',\n 'description': 'str',\n 'links': 'ILinks',\n 'type': 'str',\n 'version': 'str'\n }\n\n attribute_map = {\n 'metadata': 'metadata',\n 'last_fetch_time_stamp': 'lastFetchTimeStamp',\n 'hit_count': 'hitCount',\n 'first_hit_time_stamp': 'firstHitTimeStamp',\n 'rule': 'rule',\n 'last_hit_time_stamp': 'lastHitTimeStamp',\n 'description': 'description',\n 'links': 'links',\n 'type': 'type',\n 'version': 'version'\n }\n\n def __init__(self, metadata=None, last_fetch_time_stamp=None, hit_count=None, first_hit_time_stamp=None, rule=None, last_hit_time_stamp=None, description=None, links=None, type=None, version=None): # noqa: E501\n \"\"\"PrefilterHitCount - a model defined in Swagger\"\"\" # noqa: E501\n\n self._metadata = None\n self._last_fetch_time_stamp = None\n self._hit_count = None\n self._first_hit_time_stamp = None\n self._rule = None\n self._last_hit_time_stamp = None\n self._description = None\n self._links = None\n self._type = None\n self._version = None\n self.discriminator = None\n\n if metadata is not None:\n self.metadata = metadata\n if last_fetch_time_stamp is not None:\n self.last_fetch_time_stamp = last_fetch_time_stamp\n if hit_count is not None:\n self.hit_count = hit_count\n if first_hit_time_stamp is not None:\n self.first_hit_time_stamp = first_hit_time_stamp\n if rule is not None:\n self.rule = rule\n if last_hit_time_stamp is not None:\n self.last_hit_time_stamp = last_hit_time_stamp\n if description is not None:\n self.description = description\n if links is not None:\n self.links = links\n if type is not None:\n self.type = type\n if version is not None:\n self.version = version\n\n @property\n def metadata(self):\n \"\"\"Gets the metadata of this PrefilterHitCount. # noqa: E501\n\n Object representing metadata attributes for the hit count entry. # noqa: E501\n\n :return: The metadata of this PrefilterHitCount. # noqa: E501\n :rtype: HitCountMetadata\n \"\"\"\n return self._metadata\n\n @metadata.setter\n def metadata(self, metadata):\n \"\"\"Sets the metadata of this PrefilterHitCount.\n\n Object representing metadata attributes for the hit count entry. # noqa: E501\n\n :param metadata: The metadata of this PrefilterHitCount. # noqa: E501\n :type: HitCountMetadata\n \"\"\"\n\n self._metadata = metadata\n\n @property\n def last_fetch_time_stamp(self):\n \"\"\"Gets the last_fetch_time_stamp of this PrefilterHitCount. # noqa: E501\n\n Indicates the last time (in ISO 8601 format) the hit count was retrieved for the mentioned rule. # noqa: E501\n\n :return: The last_fetch_time_stamp of this PrefilterHitCount. # noqa: E501\n :rtype: str\n \"\"\"\n return self._last_fetch_time_stamp\n\n @last_fetch_time_stamp.setter\n def last_fetch_time_stamp(self, last_fetch_time_stamp):\n \"\"\"Sets the last_fetch_time_stamp of this PrefilterHitCount.\n\n Indicates the last time (in ISO 8601 format) the hit count was retrieved for the mentioned rule. # noqa: E501\n\n :param last_fetch_time_stamp: The last_fetch_time_stamp of this PrefilterHitCount. # noqa: E501\n :type: str\n \"\"\"\n\n self._last_fetch_time_stamp = last_fetch_time_stamp\n\n @property\n def hit_count(self):\n \"\"\"Gets the hit_count of this PrefilterHitCount. # noqa: E501\n\n Indicates the number of times the prefilter rule was hit on the target device. It is based on the data from the last FMC hit count refresh operation. # noqa: E501\n\n :return: The hit_count of this PrefilterHitCount. # noqa: E501\n :rtype: int\n \"\"\"\n return self._hit_count\n\n @hit_count.setter\n def hit_count(self, hit_count):\n \"\"\"Sets the hit_count of this PrefilterHitCount.\n\n Indicates the number of times the prefilter rule was hit on the target device. It is based on the data from the last FMC hit count refresh operation. # noqa: E501\n\n :param hit_count: The hit_count of this PrefilterHitCount. # noqa: E501\n :type: int\n \"\"\"\n\n self._hit_count = hit_count\n\n @property\n def first_hit_time_stamp(self):\n \"\"\"Gets the first_hit_time_stamp of this PrefilterHitCount. # noqa: E501\n\n Indicates the time (in ISO 8601 format) when the hit count was first hit for the mentioned rule. # noqa: E501\n\n :return: The first_hit_time_stamp of this PrefilterHitCount. # noqa: E501\n :rtype: str\n \"\"\"\n return self._first_hit_time_stamp\n\n @first_hit_time_stamp.setter\n def first_hit_time_stamp(self, first_hit_time_stamp):\n \"\"\"Sets the first_hit_time_stamp of this PrefilterHitCount.\n\n Indicates the time (in ISO 8601 format) when the hit count was first hit for the mentioned rule. # noqa: E501\n\n :param first_hit_time_stamp: The first_hit_time_stamp of this PrefilterHitCount. # noqa: E501\n :type: str\n \"\"\"\n\n self._first_hit_time_stamp = first_hit_time_stamp\n\n @property\n def rule(self):\n \"\"\"Gets the rule of this PrefilterHitCount. # noqa: E501\n\n Object representing the prefilter rule against which the hit count information is retrieved. # noqa: E501\n\n :return: The rule of this PrefilterHitCount. # noqa: E501\n :rtype: IPolicyModel\n \"\"\"\n return self._rule\n\n @rule.setter\n def rule(self, rule):\n \"\"\"Sets the rule of this PrefilterHitCount.\n\n Object representing the prefilter rule against which the hit count information is retrieved. # noqa: E501\n\n :param rule: The rule of this PrefilterHitCount. # noqa: E501\n :type: IPolicyModel\n \"\"\"\n\n self._rule = rule\n\n @property\n def last_hit_time_stamp(self):\n \"\"\"Gets the last_hit_time_stamp of this PrefilterHitCount. # noqa: E501\n\n Indicates the time (in ISO 8601 format) when the hit count was last hit for the mentioned rule. # noqa: E501\n\n :return: The last_hit_time_stamp of this PrefilterHitCount. # noqa: E501\n :rtype: str\n \"\"\"\n return self._last_hit_time_stamp\n\n @last_hit_time_stamp.setter\n def last_hit_time_stamp(self, last_hit_time_stamp):\n \"\"\"Sets the last_hit_time_stamp of this PrefilterHitCount.\n\n Indicates the time (in ISO 8601 format) when the hit count was last hit for the mentioned rule. # noqa: E501\n\n :param last_hit_time_stamp: The last_hit_time_stamp of this PrefilterHitCount. # noqa: E501\n :type: str\n \"\"\"\n\n self._last_hit_time_stamp = last_hit_time_stamp\n\n @property\n def description(self):\n \"\"\"Gets the description of this PrefilterHitCount. # noqa: E501\n\n\n :return: The description of this PrefilterHitCount. # noqa: E501\n :rtype: str\n \"\"\"\n return self._description\n\n @description.setter\n def description(self, description):\n \"\"\"Sets the description of this PrefilterHitCount.\n\n\n :param description: The description of this PrefilterHitCount. # noqa: E501\n :type: str\n \"\"\"\n\n self._description = description\n\n @property\n def links(self):\n \"\"\"Gets the links of this PrefilterHitCount. # noqa: E501\n\n Object containing links to this resource. # noqa: E501\n\n :return: The links of this PrefilterHitCount. # noqa: E501\n :rtype: ILinks\n \"\"\"\n return self._links\n\n @links.setter\n def links(self, links):\n \"\"\"Sets the links of this PrefilterHitCount.\n\n Object containing links to this resource. # noqa: E501\n\n :param links: The links of this PrefilterHitCount. # noqa: E501\n :type: ILinks\n \"\"\"\n\n self._links = links\n\n @property\n def type(self):\n \"\"\"Gets the type of this PrefilterHitCount. # noqa: E501\n\n Type must be PrefilterHitCount. # noqa: E501\n\n :return: The type of this PrefilterHitCount. # noqa: E501\n :rtype: str\n \"\"\"\n return self._type\n\n @type.setter\n def type(self, type):\n \"\"\"Sets the type of this PrefilterHitCount.\n\n Type must be PrefilterHitCount. # noqa: E501\n\n :param type: The type of this PrefilterHitCount. # noqa: E501\n :type: str\n \"\"\"\n\n self._type = type\n\n @property\n def version(self):\n \"\"\"Gets the version of this PrefilterHitCount. # noqa: E501\n\n\n :return: The version of this PrefilterHitCount. # noqa: E501\n :rtype: str\n \"\"\"\n return self._version\n\n @version.setter\n def version(self, version):\n \"\"\"Sets the version of this PrefilterHitCount.\n\n\n :param version: The version of this PrefilterHitCount. # noqa: E501\n :type: str\n \"\"\"\n\n self._version = version\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n if issubclass(PrefilterHitCount, dict):\n for key, value in self.items():\n result[key] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, PrefilterHitCount):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"swagger_client/models/prefilter_hit_count.py","file_name":"prefilter_hit_count.py","file_ext":"py","file_size_in_byte":11814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"585394608","text":"import logging\nimport os\n\nfrom arcpy import AddFieldDelimiters\nfrom arcpy.da import UpdateCursor, InsertCursor, Editor\n\nfrom Cache import File\nfrom Exceptions import *\nfrom ToolLogging import critical_info\n\n\ndef log():\n critical_info()\n error_logging = logging.getLogger('ARGADD_errors.CheckForNeeds.LayerStatus')\n return error_logging\n\n\nclass LayerStatus:\n def __init__(self, out_table):\n self.__layers = self.__read_cache()\n self.table = out_table\n self.log = log()\n\n def add_status(self, installation, site, feature_type, status):\n \"\"\"\n status types: 0 - does not exist at installation\n 1 - exists both in HQIIS and in GIS data\n 2 - exists in HQIIS but not in GIS data\n :rtype: bool\n :type status: int\n \"\"\"\n try:\n # Cannot change a 2 status to 1\n if self.__layers[installation][site][feature_type] == 2 and status == 1:\n return True\n else:\n self.__layers[installation][site][feature_type] = status\n except KeyError:\n try:\n self.__layers[installation][site] = {feature_type: status}\n except KeyError:\n self.__layers[installation] = {site: {feature_type: status}}\n\n def post_to_table(self):\n table_fields = [\"Installation\", \"rpsuid\", \"Feature_Type\", \"Status\"]\n inst_f = AddFieldDelimiters(self.table, table_fields[0])\n site_f = AddFieldDelimiters(self.table, table_fields[1])\n ft_f = AddFieldDelimiters(self.table, table_fields[2])\n try:\n with Editor(os.path.split(self.table)[0]) as _:\n for inst in self.__layers:\n for site in self.__layers[inst]:\n for layer in self.__layers[inst][site]:\n status = self.__layers[inst][site][layer]\n with UpdateCursor(self.table, table_fields[3], where_clause=\"{0}='{1}' AND {2}='{3}' AND {4}='{5}'\".format(\n inst_f, str(inst), site_f, str(site), ft_f, layer)) as cursor:\n row_count = 0\n for row in cursor:\n row[0] = str(status)\n cursor.updateRow(row)\n row_count += 1\n if not row_count:\n with InsertCursor(self.table, table_fields) as insert:\n insert.insertRow([str(inst), str(site), layer, str(status)])\n return True\n except Exception as e:\n self.log.exception(e.message)\n raise Exit(\"Failed from LayerStatus.post_to_table\")\n\n def baseline_the_table(self, insts_sites, feature_types):\n \"\"\"\n\n :rtype: bool\n :type feature_types: list\n :type insts_sites: dict\n \"\"\"\n if not self.__layers == {}:\n return True\n table_fields = [\"Installation\", \"rpsuid\", \"Feature_Type\", \"Status\"]\n inst_f = AddFieldDelimiters(self.table, table_fields[0])\n site_f = AddFieldDelimiters(self.table, table_fields[1])\n ft_f = AddFieldDelimiters(self.table, table_fields[2])\n try:\n with Editor(os.path.split(self.table)[0]) as _:\n for inst in insts_sites:\n for site in insts_sites[inst]:\n for layer in feature_types:\n try:\n if self.__layers[inst][site][layer]:\n continue\n except KeyError:\n self.add_status(inst, site, layer, 0)\n ## Code deemed too slow\n # with UpdateCursor(self.table, table_fields[3],\n # where_clause=\"{0}='{1}' AND {2}='{3}' AND {4}='{5}'\".format(\n # inst_f, str(inst), site_f, str(site), ft_f, layer)) as cursor:\n # row_count = 0\n # for row in cursor:\n # row[0] = str(0)\n # cursor.updateRow(row)\n # row_count += 1\n # if not row_count:\n # with InsertCursor(self.table, table_fields) as insert:\n # insert.insertRow([str(inst), str(site), layer, str(0)])\n return True\n except Exception as e:\n self.log.exception(e.message)\n raise Exit(\"Failed from LayerStatus.baseline_the_table\")\n\n def write_cache(self):\n \"\"\"\n\n :rtype: bool\n \"\"\"\n cache = File(\"LayerStatus\", [self.__layers])\n cache.save()\n return True\n\n def __read_cache(self):\n \"\"\"\n\n :rtype: dict\n \"\"\"\n cache = File(\"LayerStatus\")\n out = cache.read()\n if out:\n return out[0]\n return {}\n","sub_path":"Lib/LayerStatus.py","file_name":"LayerStatus.py","file_ext":"py","file_size_in_byte":5194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"389474832","text":"#\n# @lc app=leetcode id=127 lang=python3\n#\n# [127] Word Ladder\n#\n# https://leetcode.com/problems/word-ladder/description/\n#\n# algorithms\n# Hard (31.58%)\n# Likes: 4952\n# Dislikes: 1416\n# Total Accepted: 573.8K\n# Total Submissions: 1.8M\n# Testcase Example: '\"hit\"\\n\"cog\"\\n[\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]'\n#\n# A transformation sequence from word beginWord to word endWord using a\n# dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk\n# such that:\n# \n# \n# Every adjacent pair of words differs by a single letter.\n# Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to\n# be in wordList.\n# sk == endWord\n# \n# \n# Given two words, beginWord and endWord, and a dictionary wordList, return the\n# number of words in the shortest transformation sequence from beginWord to\n# endWord, or 0 if no such sequence exists.\n# \n# \n# Example 1:\n# \n# \n# Input: beginWord = \"hit\", endWord = \"cog\", wordList =\n# [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]\n# Output: 5\n# Explanation: One shortest transformation sequence is \"hit\" -> \"hot\" -> \"dot\"\n# -> \"dog\" -> cog\", which is 5 words long.\n# \n# \n# Example 2:\n# \n# \n# Input: beginWord = \"hit\", endWord = \"cog\", wordList =\n# [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\n# Output: 0\n# Explanation: The endWord \"cog\" is not in wordList, therefore there is no\n# valid transformation sequence.\n# \n# \n# \n# Constraints:\n# \n# \n# 1 <= beginWord.length <= 10\n# endWord.length == beginWord.length\n# 1 <= wordList.length <= 5000\n# wordList[i].length == beginWord.length\n# beginWord, endWord, and wordList[i] consist of lowercase English letters.\n# beginWord != endWord\n# All the words in wordList are unique.\n# \n# \n#\n\n# @lc code=start\nclass Solution:\n # solution 2: 不使用分层遍历的版本。使用 distance 这个 hash 来存储距离来实现记录每个节点的距离。\n def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n if not wordList:\n return 0\n \n wordList.append(endWord)\n queue = collections.deque([beginWord])\n distance = {beginWord: 1}\n\n while queue:\n word = queue.popleft()\n if word == endWord:\n return distance[word]\n \n for nextWord in self.get_next_words(word, wordList):\n if nextWord in distance:\n continue\n \n queue.append(nextWord)\n distance[nextWord] = distance[word] + 1\n \n return 0\n \n def get_next_words(self, word, dict):\n words = []\n for i in range(len(word)):\n left, right = word[:i], word[i + 1:]\n for char in 'abcdefghijklmnopqrstuvwxyz':\n if word[i] == char:\n continue\n next_word = left + char + right\n if next_word in dict:\n words.append(next_word)\n\n return words\n\n\n '''\n # solution 1: 使用分层遍历的BFS版本。\n def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n if not wordList:\n return 0\n\n wordList.append(endWord)\n queue = collections.deque([beginWord])\n visited = set([beginWord])\n\n length = 0\n while queue:\n n = len(queue)\n length +=1\n for i in range(n):\n word = queue.popleft()\n if word == endWord:\n return length\n \n for new_word in self.getNext(word):\n if new_word not in wordList or new_word in visited:\n continue\n\n queue.append(new_word)\n visited.add(new_word)\n \n return 0\n \n def getNext(self, word):\n words = []\n for i in range(len(word)):\n left, right = word[:i], word[i + 1:]\n for char in 'abcdefghijklmnopqrstuvwxyz':\n if word[i] == char:\n continue\n words.append(left + char + right)\n return words\n '''\n \n# @lc code=end\n\n","sub_path":"Python/127.word-ladder.py","file_name":"127.word-ladder.py","file_ext":"py","file_size_in_byte":4126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"391126017","text":"from pif import PIF\nfrom symboltable import SymbolTable\nfrom tokens import *\nimport re\n\n\nclass Scanner:\n def __init__(self, file):\n self._st = SymbolTable()\n self._pif = PIF()\n self._tokens = get_tokens()\n self._file_name = file\n self._separators = separators\n self._operators = operators\n self._reserved_words = reserved_words\n\n def get_string_constant(self, line, start_position):\n string = ''\n quote_count = 0\n i = start_position\n while i < len(line) and quote_count != 2:\n if line[i] == '\"':\n quote_count += 1\n string += line[i]\n i += 1\n return string, i\n\n def is_contained_in_operator(self, token):\n for operator in operators:\n if token in operator:\n return True\n return False\n\n def get_operator(self, line, start_position):\n i = start_position\n token = \"\"\n # if i - 1 > 0 and not self.is_contained_in_operator(line[i-1]):\n # return line[i], i+1\n # if line[i] == '+' or line[i] == '-' or line[i] == '=' or line[i] == '*' or line[i] == '\\\\':\n # if i - 1 > 0 and line[i-1] not in self._separators and self.get_operator(line, i-1)[0] \\\n # and line[i+1] not in self._separators and not self.is_identifier(line[i+1]) and not self.is_constant(line[i+1]):\n # return line[i], i + 1\n # elif i-1 > 0 and self.is_identifier(line[i-1]) and self.is_identifier(line[i+1]) or self.is_constant(line[i+1]) or line[i+1] not in self._separators:\n # return line[i], i + 1\n\n while i < len(line) and line[i] not in operators and self.is_contained_in_operator(line[i]):\n token += line[i]\n i += 1\n if token in operators:\n return token, i\n return None, start_position\n\n def get_tokens_from_line(self, line):\n token = \"\"\n index = 0\n tokens = []\n\n while index < len(line):\n if line[index] == '\"':\n if token:\n tokens.append(token)\n token, index = self.get_string_constant(line, index)\n tokens.append(token)\n token = \"\"\n\n elif line[index] in separators:\n if token:\n tokens.append(token)\n token = \"\"\n tokens.append(line[index])\n index += 1\n\n elif self.is_contained_in_operator(line[index]):\n operator, index = self.get_operator(line, index)\n if operator != None:\n if token:\n tokens.append(token)\n tokens.append(operator)\n token = \"\"\n else:\n token += line[index]\n index += 1\n\n else:\n token += line[index]\n index += 1\n\n if token:\n tokens.append(token)\n\n return tokens\n\n def run(self):\n with open(self._file_name, \"r\", encoding=\"utf-8\") as file:\n line_nr = 1\n ok = True\n for line in file:\n tokens = self.get_tokens_from_line(line)\n print(tokens)\n for token in tokens:\n if token == ' ' or token == '\\n':\n continue\n if token in self._separators or token in self._operators or token in self._reserved_words:\n self._pif.add(token, -1)\n\n elif self.is_identifier(token):\n id = self._st.insert(token)\n self._pif.add('identifier', id)\n\n elif self.is_constant(token):\n id = self._st.insert(token)\n self._pif.add('constant', id)\n\n else:\n # raise Exception(\"Invalid token \" + token + \" at line\" + str(line_nr))\n print('\\033[93m' + \"Invalid token \" + token + \" at line\" + str(line_nr) + '\\033[0m')\n ok = False\n\n line_nr += 1\n\n if ok:\n print(\"lexically correct\")\n print(self._pif)\n self._pif.print_to_file()\n\n self._st.print()\n self._st.print_to_file()\n else:\n print(\"lexically incorrect. PIF and ST will not be printed.\")\n\n def is_identifier(self, token):\n return re.match('^[a-zA-Z_]([a-zA-Z0-9]){,255}$', token) is not None\n\n def is_constant(self, token):\n is_integer = re.match(\"^0$|^(([+\\\\-])?[1-9][0-9]*)$\", token)\n is_string = re.match(\"^\\\"([a-zA-Z0-9_.?,!; @/|(){}\\[\\]\\+\\-*%$])*\\\"$\", token)\n is_bool = token == \"true\" or token == \"false\"\n\n return is_integer or is_string or is_bool\n","sub_path":"lab3-4 - scanner/scanner.py","file_name":"scanner.py","file_ext":"py","file_size_in_byte":4874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"77814916","text":"# The sum of the squares of the first ten natural numbers is:\n# 1^2 + 2^2 + ... + 10^2 = 385\n#\n# The square of the sum of the first ten natural numbers is:\n# (1 + 2 + ... + 10)^2 = 55^2 = 3025\n#\n# Hence the difference between the sum of the squares of the first ten natural\n# numbers and the square of the sum is 3025 − 385 = 2640.\n#\n# Find the difference between the sum of the squares of the first one hundred\n# natural numbers and the square of the sum.\n\n\ndef sumsqdiff(x):\n \"\"\"Find the difference between the sum of the squares and the square of the\n sum.\"\"\"\n # I have no idea of the efficiency of this\n nums = range(1, x+1)\n squares = []\n sums = sum(nums)**2\n\n for n in nums:\n squares.append(n**2)\n\n squares = sum(squares)\n return sums - squares\n\n\nsumsqdiff(100)\n","sub_path":"PythonCode/Project Euler/6- Sum square difference.py","file_name":"6- Sum square difference.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"600070327","text":"#!/usr/bin/env false\n# -*- coding: utf-8 -*-\n\nimport sys\nimport socket\nimport base64\nimport time\nimport re\nimport traceback\nimport os\nfrom threading import Lock, Thread\n\n# Netcat module taken from here: https://gist.github.com/leonjza/f35a7252babdf77c8421\n# and slightly modified\nclass Netcat:\n \"\"\" Python 'netcat like' module \"\"\"\n\n def __init__(self, ip, port):\n self.buff = b''\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.socket.connect((ip, port))\n\n def read(self, length=1024):\n \"\"\" Read 1024 bytes off the socket \"\"\"\n tmp = self.socket.recv(length)\n while len(tmp) < length:\n received = self.socket.recv(length - len(tmp))\n if len(received) == 0:\n self.socket.close()\n raise IOError('Connection closed')\n tmp += received\n return tmp\n\n def read_until(self, data):\n \"\"\" Read data into the buffer until we have data \"\"\"\n while not data in self.buff:\n received = self.socket.recv(1024)\n if len(received) == 0:\n self.socket.close()\n raise IOError('Connection closed')\n self.buff += received\n pos = self.buff.find(data)\n rval = self.buff[:pos + len(data)]\n self.buff = self.buff[pos + len(data):]\n return rval\n\n def write(self, data):\n self.socket.send(data)\n\n def close(self):\n self.socket.close()\n\nclass Class:\n def __init__(self, nc, name):\n self.name = name\n self.nc = nc\n\n def instantiate(self):\n return Object(self, self.nc, self.nc.instantiate_class(self.name))\n\n def get_method(self, method):\n return self.nc.invoke('core.class.getMethod', [self.name, method], 'ss', 'sss')\n\nclass Object:\n def __init__(self, cls, nc, handle):\n self.cls = cls\n self.handle = handle\n self.nc = nc\n\n def get_method(self, method):\n return self.cls.get_method(method)\n\n def call_method(self, method, ls):\n command, arg_types, ret_types = self.get_method(method)\n return self.nc.invoke(command, [self.handle] + ls, arg_types, ret_types)\n\nclass Modcat(Netcat):\n def __init__(self, ip, port, logger):\n Netcat.__init__(self, ip, port)\n self.logger = logger\n self.func_provider_names = {}\n self.func_providers = {}\n\n def recv_header(self):\n self.logger.vlog('Reading host header')\n header = self.read(8).decode()\n if header != 'ModBox/M':\n raise Exception('Invalid server header')\n\n def send_header(self):\n self.logger.vlog('Sending module header')\n self.write(b'ModBox/m')\n\n def recv_reverse_header(self):\n self.logger.vlog('Reading reverse host header')\n header = self.read(8).decode()\n if header != 'ModBox/R':\n raise Exception('Invalid server header')\n\n def send_reverse_header(self):\n self.logger.vlog('Sending reverse module header')\n self.write(b'ModBox/r')\n\n def read_str(self):\n self.logger.vvlog('{}: Reading string...'.format(id(self)))\n s = self.read_until(b'\\x00')[:-1].decode()\n self.logger.vvlog('{}: Reading string: \"{}\"'.format(id(self), s))\n return s\n\n def write_str(self, s):\n if s is None:\n raise Exception('Attempted to send a None value')\n self.logger.vvlog('{}: Writing string: \"{}\"'.format(id(self), s))\n s = str(s)\n s += '\\x00'\n self.write(bytes(s, 'ascii'))\n\n def unblobify(self, blob):\n self.logger.vvlog('unblobify: {}'.format(repr(blob)))\n split_blob = blob.split(b'\\x00')\n\n # Костыль № 9124721\n split_blob = split_blob[:-1]\n\n raw_members = dict([split_blob[i:i+2] for i in range(0, len(split_blob), 2)])\n members = {\n key.decode()[:-1]: (\n key.decode()[-1], self.type_decode(value, key.decode()[-1])\n ) for key, value in raw_members.items()\n }\n return members\n\n def send_arg(self, arg, tp):\n self.logger.vvlog('send_arg: self = {}, arg = {}, tp = {}'.format(id(self), arg, tp))\n if tp in 'iufs':\n self.write_str(arg)\n elif tp == 'b':\n self.write_str(base64.b64encode(arg.encode() if type(arg) is str else arg).decode())\n else:\n raise Exception('Unknown type: \"{}\"'.format(tp))\n\n def recv_arg(self, tp):\n if tp in 'iu':\n return int(self.read_str())\n elif tp == 'f':\n return float(self.read_str())\n elif tp == 's':\n return self.read_str()\n elif tp == 'b':\n return base64.b64decode(self.read_str()).decode()\n else:\n raise Exception('Unknown type: \"{}\"'.format(tp))\n\n def blobify(self, values):\n blob = b''\n for name, (type, value) in values.items():\n blob += bytes(name, 'utf-8') + bytes(type, 'utf-8') + b'\\x00'\n blob += self.type_encode(value, type) + b'\\x00'\n self.logger.vvlog('blobify: {}'.format(repr(blob)))\n return blob\n\n def invoke(self, func, ls, args, ret):\n self.logger.vlog('Invoking {}({})...'.format(func, ', '.join(map(str, ls))))\n self.write_str(func)\n for arg, tp in zip(ls, args):\n self.send_arg(arg, tp)\n exit_code = int(self.read_str())\n if exit_code == 0:\n ret_ls = [self.recv_arg(tp) for tp in ret]\n self.logger.vlog('... = {}'.format(ret_ls))\n return ret_ls\n else:\n error = self.read_str()\n self.logger.vlog('... error: {}'.format(error))\n raise Exception(error)\n\n def register_func_provider(self, storage, func, name, args, ret):\n self.logger.vlog('Registering FuncProvider: \"{}\" ({}) -> {}'.format(name, args, ret))\n self.invoke('core.funcProvider.register', [name, args, ret], 'sss', '')\n storage.func_providers[name] = func, args, ret\n\n def serve_func(self):\n try:\n self.logger.vlog('Serving')\n while True:\n # Wait for a request\n name = self.read_str()\n if name == '_exit':\n # exit\n return\n try:\n # Parse the request\n func, arg_types, ret_types = self.func_providers[name]\n\n # Receive function arguments\n args = [self.recv_arg(type) for type in arg_types]\n\n # Call the function\n ret = func(*args)\n except BaseException as e:\n # Something has gone wrong, exit code is not 0\n self.logger.log('Exception at module function:')\n traceback.print_exc()\n self.write_str(1)\n if self.logger.exit_on_callback_errors:\n self.logger.log('Bye-bye')\n self.logger.nc.close()\n self.logger.rnc.close()\n os._exit(1)\n continue\n\n # Exit code is 0\n self.write_str(0)\n for type, val in zip(ret_types, ret):\n self.send_arg(val, type)\n except BaseException as e:\n self.logger.log('Exception occured at serve_func: ' + str(e))\n os._exit(1)\n\n def spawn_serving_thread(self):\n self.serving_thread = Thread(target=self.serve_func)\n self.serving_thread.start()\n\n def join_serving_thread(self):\n self.serving_thread.join()\n\n def get_class(self, classname):\n return Class(self, classname)\n\n def add_class(self, classname, members, methods, parent=''):\n self.logger.vlog('Adding class \"{}\"'.format(classname))\n members_string = ':'.join(map(lambda pair: ''.join(pair), members))\n methods_string = ':'.join(map(lambda tup: ','.join(tup), methods))\n self.invoke('core.class.add', [parent, classname, members_string, methods_string], 'ssss', '')\n return Class(self, classname)\n\n def instantiate_class(self, classname):\n self.logger.vlog('Instantiating class {}'.format(classname))\n return self.invoke('core.class.instantiate', [classname], 's', 'u')[0]\n\n\nclass Module:\n def __init__(self, module_name):\n self.module_name = module_name\n self.VERBOSE = True\n self.VERY_VERBOSE = False\n self.exit_on_callback_errors = False\n\n self.call_lock = Lock()\n\n self.main_port, self.reverse_port = self.portinfo(sys.argv)\n self.nc = Modcat('localhost', self.main_port, logger=self)\n self.rnc = Modcat('localhost', self.reverse_port, logger=self)\n\n self.nc.recv_header()\n self.nc.send_header()\n self.nc.write_str(module_name)\n self.rnc.recv_reverse_header()\n self.rnc.send_reverse_header()\n self.rnc.write_str(module_name)\n self.rnc.spawn_serving_thread()\n\n def register_func_provider(self, func, command, args, ret):\n self.nc.register_func_provider(self.rnc, func.__get__(self), command, args, ret)\n\n def invoke(self, *args, **kwargs):\n with self.call_lock:\n return self.nc.invoke(*args, **kwargs)\n\n def _get_log_time(self):\n return time.strftime('%02d.%02m.%Y %02H:%02M:%02S')\n\n def log(self, text):\n print(\"[MODLOG ({}) {}] \".format(self.module_name, self._get_log_time()) + str(text))\n sys.stdout.flush()\n\n def vlog(self, text):\n if self.VERBOSE:\n self.log(text)\n\n def vvlog(self, text):\n if self.VERY_VERBOSE:\n self.log(text)\n\n def portinfo(self, argv):\n main_port = None\n reverse_port = None\n self.vlog(argv)\n for arg in argv:\n if re.match(r'^--main-port=[0-9]*$', arg) is not None:\n main_port = int(arg.split('=')[1])\n if re.match(r'^--reverse-port=[0-9]*$', arg) is not None:\n reverse_port = int(arg.split('=')[1])\n if main_port is None:\n raise ValueError('Main port information not provided')\n if reverse_port is None:\n raise ValueError('Reverse port information not provided')\n return main_port, reverse_port\n\n def ready(self):\n self.invoke('module.ready', [], '', '')\n","sub_path":"pymodbox/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":10398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"156120875","text":"#1. they are simulation used to determine general results of a problem\n#2. mostly optimization or approximation\n#3. determine range, set up a condition, take random sample, see how many elements meet the condition\n\n\nimport random\nimport math\n\ndef main(tries):\n\tresults = 0\n\tfor i in range(tries):\n\t\ta = random.uniform(-1,1)\n\t\tb = random.uniform(-1,1)\n\t\tdistance = math.sqrt(a*a+b*b)\n\t\tif distance<=1:\n\t\t\tresults+=1\n\n\tnumber = results*4/tries\n\n\treturn number\n\nprint(main(100))\nprint(main(1000))\nprint(main(10000))\nprint(main(100000))\nprint(main(1000000))\n\n# number get's closer to the pi number = because this is a method to approx pi","sub_path":"darts.py","file_name":"darts.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"477321096","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nCopyright (C) 2014 Axel Mendoza \n\nLicensed under LGPLv3, see LICENSE.txt for terms and conditions.\n\"\"\"\n\nfrom setuptools import setup, find_packages\n\nversion = '0.1'\n\nsetup(\n name = 'zato-mail',\n version = version,\n \n keyword = ' soa eai esb middleware messaging queueing asynchronous integration performance http zeromq framework events agile broker messaging server jms enterprise python middleware clustering amqp nosql websphere mq wmq mqseries ibm amqp zmq openerp mail',\n\n author = 'Msc. Axel Mendoza Pupo',\n author_email = 'aekroft@gmail.com',\n url = 'http://eloquentia.com.mx',\n\n package_dir = {'':'src'},\n packages = find_packages('src'),\n\n namespace_packages = ['zato'],\n \n install_requires=[\n 'html2text',\n ],\n\n zip_safe = False,\n)","sub_path":"mail/code/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"450463008","text":"import matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom math import sqrt\r\n\r\ndef f(x,y):\r\n return x*x*y\r\n\r\ntheta=np.linspace(0,2*np.pi,100)\r\nx=sqrt(3)*np.sin(theta)\r\ny=sqrt(3)*np.cos(theta)\r\nplt.plot(x,y,'r')\r\n\r\nn=100\r\nx=np.linspace(-6,6,n)\r\ny=np.linspace(-6,6,n)\r\nX,Y=np.meshgrid(x,y)\r\nZ=f(X,Y)\r\n\r\nr=plt.contour(X,Y,Z,[-10,-6,-2,-1,-0.2,0,0.2,1,2,6,10])\r\nplt.clabel(r,inline=True,fontsize=10)\r\nplt.show()","sub_path":"scripts/plot_lglrdgxt.py","file_name":"plot_lglrdgxt.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"569762231","text":"import traceback\n\nclass FormulaError(Exception):\n pass\n\ndef parse_input(input):\n # Separa a entrada por espaços\n items = input.split()\n \n if (len(items) != 3):\n raise FormulaError(\"A entrada nao consiste de 3 elementos\")\n src1, op, src2 = items[0], items[1], items[2]\n \n if (op not in [\"+\",\"-\",\"*\",\"/\"]):\n raise FormulaError(f\"{op} nao e um operador valido\")\n \n try:\n src1 = float(src1)\n src2 = float(src2)\n except (ValueError):\n raise FormulaError(\"O primeiro e o terceiro valor de entrada devem ser numeros\")\n \n return src1, op, src2\n\ndef evaluate(src1, op, src2):\n if (op == \"+\"):\n return src1 + src2\n elif (op == \"-\"):\n return src1 - src2\n elif (op == \"*\"):\n return src1 * src2\n elif (op == \"/\"):\n return src1 / src2\n \ndef main():\n entradaValida = True\n while (entradaValida):\n try:\n entrada = input()\n src1, op, src2 = parse_input(entrada)\n print(evaluate(src1,op,src2))\n except:\n entradaValida = False\n traceback.print_exc()\n\nif __name__ == \"__main__\":\n main()","sub_path":"8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"27902742","text":"import numpy as np\r\nfrom CuriosityExperiment.State_Space import State_Space\r\nfrom CuriosityExperiment.Action_Space import Action_Space\r\nfrom CuriosityExperiment.State import State\r\n\r\n\r\nclass Learner:\r\n def __init__(self):\r\n self.initLearner()\r\n self.initPerceiver()\r\n self.sigma = 0.1\r\n self.sigma_hat = self.sigma/(State_Space.num_of_states()-1)\r\n def initLearner(self):\r\n self.learner = np.ones((Action_Space.num_of_actions(),State_Space.num_of_states(),State_Space.num_of_states()))*(1/State_Space.num_of_states())\r\n def initPerceiver(self):\r\n self.perceiver = np.ones((State_Space.num_of_states(),Action_Space.num_of_actions(),State_Space.num_of_states(),State_Space.num_of_states()))*1/State_Space.num_of_states()\r\n self.prevPerceiver = self.perceiver\r\n def getLearner(self,action,state,state2):\r\n index_action = Action_Space.get_index(action)\r\n index_state = State_Space.get_index(state)\r\n index_state2 = State_Space.get_index(state2)\r\n return self.learner[index_action,index_state, index_state2]\r\n def getPerceiver(self,o,action,state,state2):\r\n index_o = State_Space.get_index(o)\r\n index_action = Action_Space.get_index(action)\r\n index_state = State_Space.get_index(state)\r\n index_state2 = State_Space.get_index(state2)\r\n return self.perceiver[index_o,index_action,index_state,index_state2]\r\n def Noise(self,state2,o):\r\n if(State.__eq__(state2,o)):\r\n return (1/(1+self.sigma))\r\n return (self.sigma_hat)/(1+self.sigma)\r\n def update_perceiver(self,o,action,state):\r\n self.prevPerceiver = self.perceiver\r\n temp = np.zeros((State_Space.num_of_states(),State_Space.num_of_states()))\r\n index_o = State_Space.get_index(o)\r\n for k in State_Space.states:\r\n index_k = State_Space.get_index(k)\r\n temp[index_o,index_k] = temp[index_o,index_k]+self.learner(action,state,k)*self.Noise(o,k)\r\n index_action = Action_Space.get_index(action)\r\n index_state = State_Space.get_index(state)\r\n for state2 in State_Space.states:\r\n index_state2 = State_Space.get_index(state2)\r\n self.perceiver[index_o,index_action,index_state,index_state2] = (self.learner[index_action,index_state,index_state2]*self.Noise(state2,o))/(temp)\r\n def update_learner(self, world):\r\n self.update_perceiver(world.get_current_state(), world.get_current_action(), world.get_previous_state())\r\n def Dkl(self,o,action,state):\r\n r = 0\r\n for state2 in State_Space.states:\r\n index_state2 = State_Space.get_index(state2)\r\n r = r + self.getPerceiver(o,action,state,state2) * np.log(self.getPerceiver(o,action,state,state2)/self.getLearner(action,state,state2))\r\n return r\r\n\r\n\r\n\r\n","sub_path":"Learner.py","file_name":"Learner.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"142702967","text":"import FWCore.ParameterSet.Config as cms\n\nofflinePrimaryVerticesFromCosmicTracks = cms.EDProducer(\"PrimaryVertexProducer\",\n PVSelParameters = cms.PSet(\n maxDistanceToBeam = cms.double(0.05), ## 200 microns\n\n minVertexFitProb = cms.double(0.01) ## 1% vertex fit probability\n\n ),\n verbose = cms.untracked.bool(False),\n algorithm = cms.string('AdaptiveVertexFitter'),\n minNdof = cms.double(0.0),\n TkFilterParameters = cms.PSet(\n algorithm=cms.string('filter'),\n maxNormalizedChi2 = cms.double(5.0),\n minSiliconLayersWithHits = cms.int32(7), ## hits > 7\n\n maxD0Significance = cms.double(5.0), ## keep most primary tracks\n\n minPt = cms.double(0.0), ## better for softish events\n\n minPixelLayersWithHits = cms.int32(2), ## hits > 2\n trackQuality = cms.string(\"any\")\n\n ),\n beamSpotLabel = cms.InputTag(\"offlineBeamSpot\"),\n # label of tracks to be used\n TrackLabel = cms.InputTag(\"ctfWithMaterialTracksP5\"),\n useBeamConstraint = cms.bool(False),\n VtxFinderParameters = cms.PSet(\n ptCut = cms.double(0.0),\n vtxFitProbCut = cms.double(0.01), ## 1% vertex fit probability\n\ttrackCompatibilityToSVcut = cms.double(0.01), ## 1%\n trackCompatibilityToPVcut = cms.double(0.05), ## 5%\n maxNbOfVertices = cms.int32(0) ## search all vertices in each cluster\n\n ),\n TkClusParameters = cms.PSet(\n algorithm = cms.string(\"gap\"),\n TkGapClusParameters = cms.PSet( \n zSeparation = cms.double(0.1) ## 1 mm max separation betw. clusters\n )\n )\n)\n\n\n","sub_path":"RecoVertex/PrimaryVertexProducer/python/OfflinePrimaryVerticesFromCosmicTracks_cfi.py","file_name":"OfflinePrimaryVerticesFromCosmicTracks_cfi.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}